diff --git a/Cargo.lock b/Cargo.lock index 47a8d217d..d436bf20c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4283,9 +4283,11 @@ dependencies = [ name = "solidcraft-render" version = "0.40.0-rc.2" dependencies = [ + "flate2", "image", "moxcms", "png", + "robust", "serde", "serde_json", "sha2 0.10.9", diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 0c8a52012..cef280bf3 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -3020,9 +3020,9 @@ "render.adaptive_absolute": "الحد الأدنى المطلق لخطأ RGB", "render.adaptive_coverage": "هدف خطأ التغطية", "render.adaptive_enable": "توزيع العيّنات باستخدام عيّنات استكشافية مستقلة", - "render.adaptive_help": "على GPU فقط. تُستبعد العيّنات الاستكشافية المستقلة، ثم تُوزَّع 16 عيّنة إنتاجية أو أكثر لكل بكسل حتى قيمة «عيّنات لكل بكسل». يوجّه تباين RGB والتغطية هذا التوزيع؛ قد تفوت المسارات النادرة وقد تبقى البكسلات المحدودة مشوشة. يحصي التقرير النهائي العمل الفعلي. لا ضمان معتمد للتشويش أو للزمن.", + "render.adaptive_help": "تُهمل العينات الاستطلاعية المستقلة، ثم يُحدد لكل بكسل 16 عينة إنتاج على الأقل حتى قيمة العينات لكل بكسل. تشمل حدود موارد CPU المرحلتين. يوجه تباين RGB والتغطية التوزيع؛ وقد تبقى ضوضاء في البكسلات التي بلغت الحد. يحصي التقرير النهائي العينات الفعلية.", "render.adaptive_minimum": "الحد الأدنى للعيّنات الإنتاجية", - "render.adaptive_pending": "التوزيع التكيّفي على GPU بعيّنات استكشافية مستقلة وطبقات فرينل الشرطية متاحة. التقارب المعتمد وضمانات الأحداث النادرة والنقل التكيّفي على CPU غير متاحة بعد.", + "render.adaptive_pending": "يتوفر التوزيع التكيفي بعينات استطلاعية مستقلة على CPU وGPU. تتطلب طبقات فرينل الشرطية GPU. لا يضمن التوزيع الإحصائي التقارب.", "render.adaptive_pilots": "العيّنات الاستكشافية لكل بكسل", "render.adaptive_relative": "هدف خطأ RGB النسبي", "render.add_ground": "إضافة أرضية ملائمة إلى الإعداد", @@ -3083,7 +3083,7 @@ "render.appearance_editor.replace": "استبدال الخصائص البصرية المحفوظة لهذا الجسم", "render.appearance_editor.revalidate": "إعادة التحقق من هذا الجسم", "render.appearance_editor.save": "حفظ هذه الخصائص البصرية", - "render.appearance_editor.save_reason": "يتطلب حفظ هذه الخصائص البصرية زجاجًا فيزيائيًا على جسم حالي في بطاقة الرسومات. تبقى الطبقة الشفافة وخرائط الصور المحلية مؤقتة.", + "render.appearance_editor.save_reason": "لحفظ الزجاج، فعّله على جسم حالي يستخدم CPU أو GPU. للطلاء الشفاف استخدم حفظ الطلاء مع اللقطة. تبقى ملفات الصور المحلية مؤقتة.", "render.appearance_editor.saved": "محفوظ مع هذه اللقطة", "render.appearance_editor.saved_state": "هذه الخصائص البصرية محفوظة مع هذه اللقطة.", "render.appearance_editor.scatter_reason": "التشتت الداخلي يتطلب حدًّا لجسم مصمت مغلق.", @@ -3179,7 +3179,7 @@ "render.children.copy_request": "نسخ JSON الطلب", "render.children.coverage_error": "خطأ التغطية", "render.children.cpu": "تتبّع الأشعة على المعالج", - "render.children.denoise": "تقليل التشويش في الصورة النهائية", + "render.children.denoise": "تقليل تشويش الصورة", "render.children.depth": "عمق المسار", "render.children.distortion": "التشويه", "render.children.edge_samples": "عينات الحواف", @@ -3311,7 +3311,7 @@ "render.cpu_point_help": "حتى ثمانية أضواء نقطية تُضاف إلى الإضاءة الاتجاهية المختارة. المسافات بالمليمتر؛ ويجب ألا يتجاوز الحد الأدنى المسافة المرجعية.", "render.cpu_primary_samples": "عيّنات الحواف لكل بكسل", "render.cpu_progressive": "CPU تدريجي", - "render.cpu_progressive_help": "يُراكم مُكامل CPU الحالي على تمريرات من عيّنة أساسية واحدة. الانعكاسات المختارة تتطلب عيّنة واحدة؛ والأضواء المساحية والعوازل وتباين الخواص تتطلب «صورة واحدة».", + "render.cpu_progressive_help": "تُجمع عينات كاميرا CPU الجديدة ويُعرض كل تمرير مكتمل. تستخدم الانعكاسات المحددة محاولة واحدة لكل عينة كاميرا؛ ويحتفظ الزجاج المعتمد والتباين الاتجاهي المستوي بحدودهما الحالية. تتشارك العينات الاستطلاعية التكيفية والإنتاج ميزانية ملف CPU.", "render.cpu_progressive_limits": "بحد أقصى 1,048,576 بكسل و16,777,216 عملية تقييم بكسل × عيّنة. تغيير العيّنات لا يغيّر حجم الصورة تلقائيًا أبدًا.", "render.cpu_progressive_seed": "بذرة عيّنات CPU", "render.cpu_progressive_spp": "عيّنات لكل بكسل", @@ -3487,7 +3487,7 @@ "render.export_display": "تصدير: PNG للعرض", "render.export_image_label": "تصدير الصورة", "render.export_linear": "تصدير: EXR خطي خام", - "render.exr_pending": "يستطيع GPU الاحتفاظ بـ EXR خطي خام. الضغط والصور متعددة الطبقات وتمريرات التصيير المساعدة غير متاحة بعد.", + "render.exr_pending": "يمكن لتتبع الأشعة على CPU وتتبع المسارات على GPU الاحتفاظ بـ EXR خطي خام. الضغط والصور متعددة الطبقات وتمريرات التصيير المساعدة غير متاحة بعد.", "render.film_grain": "حبيبات فوتوغرافية", "render.fit": "ملاءمة المنتج", "render.fixed_camera": "الكاميرا", @@ -3850,7 +3850,7 @@ "render.method_cpu": "تتبع الأشعة على CPU", "render.method_gpu": "تتبع المسارات على GPU", "render.method_limit_raster": "التنقيط يستخدم معاينة الاستوديو المعتمة الثابتة. اختر طريقة تتبع أشعة صريحة لعناصر التحكم البصرية المدعومة.", - "render.method_raster": "تنقيط على CPU", + "render.method_raster": "تصيير نقطي على CPU (تخطيطي)", "render.navigation_help": "تتحرك الكاميرا كما في التصميم (التفضيلات › التنقل). «حفظ الإعداد» يسجّل الكاميرا الحالية.", "render.nested_enable": "عوازل متداخلة معتمدة", "render.nested_help": "حتى 16 طبقة حاوية؛ يجب أن يكون كل أصل محدبًا وكل فرع داخله تمامًا. التقاطعات والأسطح المتلامسة والصفائح الرقيقة ونفاذ الظل المستقيم تُرفض. حالة وجود الكاميرا في الداخل تتبع التسلسل المعتمد. لا يُنشئ سطح سائل ولا يدمج حدود CAD المتلامسة.", @@ -3878,7 +3878,7 @@ "render.output_exr_unavailable": "إعداد مخرجات EXR غير متاح هنا. تصدير EXR الخطي يتطلب صورة GPU مكتملة بنسخة رئيسية خطية محتفظ بها.", "render.output_fit": "ملاءمة", "render.output_format": "الصيغة", - "render.output_format_status": "PNG هو صورة العرض المكتملة بالضبط. EXR الاختياري على GPU يحتفظ بالإشعاع الخام الخطي للمشهد بصيغة FLOAT32 قبل مرشحات العرض. التصدير لا يستبدل أبدًا ذاكرة المعاينة المؤقتة أو مهمة أخرى.", + "render.output_format_status": "PNG هو صورة العرض المكتملة بالضبط. يحتفظ EXR الاختياري على CPU أو GPU بالإشعاع الخام الخطي للمشهد بصيغة FLOAT32 قبل مرشحات العرض. لا يستبدل التصدير أبدًا الصورة بذاكرة المعاينة المؤقتة أو بمهمة مختلفة.", "render.output_grading": "تدرّج الألوان", "render.output_image": "الصورة", "render.output_largest": "الأقصى {width} × {height}", @@ -3963,7 +3963,7 @@ "render.quality_custom": "مخصص", "render.quality_draft": "مسودة", "render.quality_high": "عالية", - "render.quality_projection_help": "إعدادات Q الجاهزة تتضمن متطلبات مستقبلية. هذا الإجراء يُسقط فقط ميزانية PNG مدعومة بعيّنات ثابتة، ويُغفل صراحةً الإيقاف التكيّفي والإخراج الخطي الخام وحدود النفاذ المستقلة.", + "render.quality_projection_help": "تغيّر هذه المراجعة الدقة وميزانية العينات وعمق المسار والبذرة وتقليل التشويش فقط. تُحفظ الإعدادات الأخرى؛ ولا تثبت الميزانية تقارب الصورة.", "render.quality_review": "مراجعة ميزانية العيّنات", "render.queue_pending": "لا توجد في هذه الواجهة قائمة إنتاج تلقائية ولا مُصيّر للرسوم المتحركة. تبقى الصور الثابتة المكتملة قابلة للتصدير كلٌّ على حدة.", "render.radial_assign": "تعيين مظهر", @@ -3994,7 +3994,7 @@ "render.result_navigation": "الإزاحة والتكبير يتبعان تفضيلات التنقل. Space مع السحب يُزيح العرض.", "render.result_open": "فتح الصورة المكتملة في اللوحة الرئيسية.", "render.result_preview": "المعاينة الحية", - "render.result_provisional": "صورة CPU مؤقتة", + "render.result_provisional": "صورة مؤقتة", "render.result_provisional_help": "نقطة التحقق هذه غير قابلة للتصدير. يحتفظ التصدير بآخر نتيجة مكتملة؛ والإلغاء يعود إلى تلك النتيجة.", "render.result_reduced_display": "قُلّصت معاينة العرض إلى حد الجهاز أو الذاكرة المؤقتة لمنطقة العرض. يحتفظ PNG المحفوظ والتصدير بالدقة الكاملة؛ والفحص الأصلي بنسبة 100% غير متاح لهذا العرض المقلّص.", "render.result_retained": "تُعرض آخر صورة مكتملة؛ ولم يستبدلها تصيير أحدث.", @@ -4159,7 +4159,7 @@ "render.stage_panels.prepare_plan": "تجهيز خطة الإنشاء", "render.stage_panels.projects": "ما يُسقط", "render.stage_panels.quality_ack": "أقرّ بالميزانية الثابتة وما تُغفله", - "render.stage_panels.quality_omissions": "التوقف التكيّفي وأهداف الخطأ، وعمق نفاذ منفصل، وقواعد الروليت الروسية، والإخراج الخطي الخام، ونسخة EXR الأصلية، وشهادة التقارب.", + "render.stage_panels.quality_omissions": "لا تضبط هذه الميزانية أهداف الخطأ التكيفي أو حدود النفاذ المستقلة أو قواعد الروليت الروسي أو الاحتفاظ بالأصل الخام، ولا تضمن تقارب الصورة.", "render.stage_panels.reference": "مرجع", "render.stage_panels.references": "مراجع", "render.stage_panels.remove_optics": "إزالة البصريات", @@ -4203,7 +4203,7 @@ "render.stage_panels.subtitle_environment": "بيئة HDR أصلية · المشهد بأكمله", "render.stage_panels.subtitle_maps": "خرائط مكانية مُعدّة · معاينة مؤقتة", "render.stage_panels.subtitle_physical": "خطة للقراءة فقط · لا تُنشأ مادة ولا تُعيَّن", - "render.stage_panels.subtitle_quality": "ميزانية GPU ثابتة · تُغفل المتطلبات المستقبلية", + "render.stage_panels.subtitle_quality": "ميزانية عينات GPU · الحقول المدرجة فقط", "render.stage_panels.subtitle_rig": "طقم إضاءة مُعدّ · باعثات وبطاقات سلبية", "render.stage_panels.subtitle_saved_maps": "خرائط مُعدّة · محفوظة مع هذه اللقطة", "render.stage_panels.subtitle_stage": "أرضية ومنصة فيزيائيتان · ملائمتان للمنتج", @@ -4228,7 +4228,7 @@ "render.studio_area_help": "حتى أربعة مستطيلات أحادية الجانب. نصفا الضلعين المتعامدين U وV يحددان الحجم؛ وحاصل U × V يواجه الجهة المضاءة. الإحداثيات بمليمترات فضاء العالم.", "render.studio_center": "المركز X, Y, Z (mm)", "render.studio_denoise": "تقليل التشويش في الصورة النهائية", - "render.studio_denoise_help": "مرشح نهائي يراعي الحواف؛ وقد تلين التفاصيل الدقيقة. الزجاج والأسطح المرآوية الحادة لا يمر عليها المرشح.", + "render.studio_denoise_help": "تستخدم الصور التدريجية والنهائية مرشحًا يحافظ على الحواف؛ وقد تصبح التفاصيل الدقيقة أنعم. لا يُطبّق المرشح على الزجاج والأسطح ذات الانعكاس الحاد.", "render.studio_direction": "الاتجاه نحو الشمس (X, Y, Z)", "render.studio_environment": "البيئة", "render.studio_environment_bounds": "يجب أن يكون دوران البيئة قيمة محدودة ضمن ±1,000,000 راديان والشدة بين 0 و100.", diff --git a/assets/locales/de.json b/assets/locales/de.json index 091112f01..fa554d642 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -2780,9 +2780,9 @@ "render.adaptive_absolute": "Absolute RGB-Fehleruntergrenze", "render.adaptive_coverage": "Zielwert für den Abdeckungsfehler", "render.adaptive_enable": "Samples mithilfe unabhängiger Pilot-Samples zuteilen", - "render.adaptive_help": "Nur GPU. Unabhängige Pilot-Samples werden verworfen. Anschließend werden pro Pixel 16 oder mehr Produktions-Samples zugeteilt, bis zu den Samples pro Pixel. Die Zuteilung richtet sich nach der RGB- und Abdeckungsvarianz; seltene Pfade können übersehen werden, und Pixel, die ihr Limit erreicht haben, können verrauscht bleiben. Der Abschlussbericht zählt den tatsächlichen Aufwand. Keine zertifizierte Garantie für ein bestimmtes Rauschniveau oder eine bestimmte Renderzeit.", + "render.adaptive_help": "Unabhängige Pilotsamples werden verworfen und bestimmen dann mindestens 16 Produktionssamples pro Pixel bis zum Wert Samples pro Pixel. CPU-Ressourcengrenzen umfassen beide Phasen. RGB- und Abdeckungsvarianz steuern die Verteilung; Pixel am Limit können verrauscht bleiben. Der Abschlussbericht zählt die tatsächlichen Samples.", "render.adaptive_minimum": "Minimale Produktions-Samples", - "render.adaptive_pending": "Die adaptive Zuteilung mit unabhängigen GPU-Pilot-Samples und bedingte Fresnel-Schichten sind verfügbar. Zertifizierte Konvergenz, Garantien für seltene Ereignisse und adaptiver Lichttransport auf der CPU bleiben nicht verfügbar.", + "render.adaptive_pending": "Adaptive Verteilung mit unabhängigen Pilotsamples ist für CPU und GPU verfügbar. Bedingte Fresnel-Schichten erfordern die GPU. Die statistische Verteilung bestätigt keine Konvergenz.", "render.adaptive_pilots": "Pilot-Samples pro Pixel", "render.adaptive_relative": "Zielwert für den relativen RGB-Fehler", "render.add_ground": "Add fitted ground to setup", @@ -2843,7 +2843,7 @@ "render.appearance_editor.replace": "Gespeicherte Optik dieses Körpers ersetzen", "render.appearance_editor.revalidate": "Diesen Körper erneut prüfen", "render.appearance_editor.save": "Diese Optik speichern", - "render.appearance_editor.save_reason": "Zum Speichern wird physikalisches Glas auf einem aktuellen GPU-Körper benötigt. Klarlack und lokale Bildtexturen bleiben vorübergehend.", + "render.appearance_editor.save_reason": "Zum Speichern Glas an einem aktuellen CPU- oder GPU-Körper aktivieren. Für Klarlack „Klarlack in Aufnahme speichern“ verwenden. Lokale Bilddateien bleiben temporär.", "render.appearance_editor.saved": "Mit dieser Aufnahme gespeichert", "render.appearance_editor.saved_state": "Diese Optik ist mit dieser Aufnahme gespeichert.", "render.appearance_editor.scatter_reason": "Innere Streuung benötigt einen geschlossenen Körper.", @@ -2939,7 +2939,7 @@ "render.children.copy_request": "Anfrage-JSON kopieren", "render.children.coverage_error": "Abdeckungsfehler", "render.children.cpu": "CPU-Raytracing", - "render.children.denoise": "Rauschen im fertigen Bild reduzieren", + "render.children.denoise": "Bildrauschen reduzieren", "render.children.depth": "Pfadtiefe", "render.children.distortion": "Verzeichnung", "render.children.edge_samples": "Kanten-Samples", @@ -3071,7 +3071,7 @@ "render.cpu_point_help": "Bis zu acht Punktlichter, zusätzlich zur gewählten Richtungsbeleuchtung. Abstände in mm; der Mindestabstand darf den Referenzabstand nicht überschreiten.", "render.cpu_primary_samples": "Kanten-Samples pro Pixel", "render.cpu_progressive": "CPU progressiv", - "render.cpu_progressive_help": "Den vorhandenen CPU-Integrator in Durchgängen mit je einem Primär-Sample akkumulieren. Ausgewählte Reflexionen erfordern ein Sample; Flächenlichter, Dielektrika und Anisotropie erfordern „Einzelbild“.", + "render.cpu_progressive_help": "Neue CPU-Kamerasamples sammeln und jeden vollständigen Durchgang zeigen. Ausgewählte Reflexionen verwenden einen Versuch pro Kamerasample; zertifiziertes Glas und planare Anisotropie behalten ihre bisherigen Grenzen. Adaptive Pilot- und Produktionssamples teilen sich das CPU-Profilbudget.", "render.cpu_progressive_limits": "Höchstens 1.048.576 Pixel und 16.777.216 Auswertungen von Pixel × Sample. Das Ändern der Samples passt die Bildgröße nie automatisch an.", "render.cpu_progressive_seed": "Startwert für das CPU-Sampling", "render.cpu_progressive_spp": "Samples pro Pixel", @@ -3247,7 +3247,7 @@ "render.export_display": "Export: Anzeige-PNG", "render.export_image_label": "Bild exportieren", "render.export_linear": "Export: lineares Roh-EXR", - "render.exr_pending": "Die GPU kann rohe lineare EXR-Dateien behalten. Kompression, mehrschichtige Bilder und zusätzliche Renderpässe bleiben nicht verfügbar.", + "render.exr_pending": "CPU-Raytracing und GPU-Pathtracing können rohe lineare EXR-Dateien behalten. Kompression, mehrschichtige Bilder und zusätzliche Renderpässe bleiben nicht verfügbar.", "render.film_grain": "Fotografisches Korn", "render.fit": "Produkt einpassen", "render.fixed_camera": "Kamera", @@ -3610,7 +3610,7 @@ "render.method_cpu": "CPU-Raytracing", "render.method_gpu": "GPU-Pathtracing", "render.method_limit_raster": "Die Rasterung verwendet die feste undurchsichtige Studiovorschau. Wählen Sie ausdrücklich eine Raytracing-Methode für die unterstützten optischen Einstellungen.", - "render.method_raster": "CPU-Rasterung", + "render.method_raster": "CPU-Rasterung (schematisch)", "render.navigation_help": "Die Kamera bewegt sich wie im Konstruieren (Einstellungen › Navigation). Setup speichern übernimmt die aktuelle Kamera.", "render.nested_enable": "Zertifizierte verschachtelte Dielektrika", "render.nested_help": "Bis zu 16 umschließende Schichten; jedes übergeordnete Element muss konvex und jedes untergeordnete strikt darin enthalten sein. Überschneidungen, sich berührende Flächen, dünne Schichten und die Transmission gerader Schattenstrahlen werden abgelehnt. Der Zustand „Kamera im Inneren“ folgt der zertifizierten Hierarchie. Erzeugt keine Flüssigkeitsoberfläche und verschmilzt keine sich berührenden CAD-Grenzflächen.", @@ -3638,7 +3638,7 @@ "render.output_exr_unavailable": "EXR-Ausgabeeinstellungen sind hier nicht verfügbar. Linearer EXR-Export erfordert ein fertiges GPU-Bild mit gespeichertem linearem Original.", "render.output_fit": "Einpassen", "render.output_format": "Format", - "render.output_format_status": "PNG enthält das exakte fertige Anzeigebild. Optionales GPU-EXR bewahrt rohe lineare FLOAT32-Strahldichte vor Filtern. Export ersetzt nie durch Vorschaucache oder anderen Auftrag.", + "render.output_format_status": "PNG enthält das exakte fertige Anzeigebild. Optionales CPU/GPU-EXR bewahrt rohe lineare FLOAT32-Strahldichte vor Anzeigefiltern. Der Export verwendet nie den Vorschaucache oder einen anderen Auftrag.", "render.output_grading": "Farbkorrektur", "render.output_image": "Bild", "render.output_largest": "{width} × {height} max.", @@ -3723,7 +3723,7 @@ "render.quality_custom": "Benutzerdefiniert", "render.quality_draft": "Entwurf", "render.quality_high": "Hoch", - "render.quality_projection_help": "Q-Vorgaben enthalten künftige Anforderungen. Diese Aktion projiziert nur ein unterstütztes PNG-Budget mit festen Samples und lässt adaptives Stoppen, rohe lineare Ausgabe und unabhängige Transmissionslimits ausdrücklich aus.", + "render.quality_projection_help": "Diese Prüfung ändert nur Auflösung, Abtastbudget, Pfadtiefe, Startwert und Rauschreduzierung. Andere Einstellungen bleiben erhalten; das Budget garantiert keine Konvergenz.", "render.quality_review": "Sampling-Budget prüfen", "render.queue_pending": "In dieser Oberfläche gibt es keine automatische Produktionswarteschlange und keinen Animations-Renderer. Fertige Einzelbilder bleiben separat exportierbar.", "render.radial_assign": "Erscheinungsbild zuweisen", @@ -3754,7 +3754,7 @@ "render.result_navigation": "Verschieben und Zoomen folgen den Navigationseinstellungen. Leertaste + Ziehen verschiebt.", "render.result_open": "Das fertige Bild in der Hauptansicht öffnen.", "render.result_preview": "Live-Vorschau", - "render.result_provisional": "Vorläufiges CPU-Bild", + "render.result_provisional": "Vorläufiges Bild", "render.result_provisional_help": "Dieser Zwischenstand ist nicht exportierbar. Der Export behält das letzte fertige Ergebnis; ein Abbruch kehrt zu diesem Ergebnis zurück.", "render.result_reduced_display": "Anzeigevorschau auf die Geräte-/Cachegrenze reduziert. PNG und Export behalten die volle Auflösung; native 100%-Ansicht ist hier nicht verfügbar.", "render.result_retained": "Das zuletzt fertiggestellte Bild wird angezeigt; ein neueres Rendering hat es noch nicht ersetzt.", @@ -3919,7 +3919,7 @@ "render.stage_panels.prepare_plan": "Erstellungsplan vorbereiten", "render.stage_panels.projects": "Projiziert", "render.stage_panels.quality_ack": "Ich bestätige das feste Budget und seine Auslassungen", - "render.stage_panels.quality_omissions": "Adaptives Stoppen und Fehlerziele, separate Transmissionstiefe, Russian-Roulette-Regeln, lineare Rohausgabe, EXR-Master und Konvergenznachweis.", + "render.stage_panels.quality_omissions": "Dieses Budget legt keine adaptiven Fehlerziele, eigenen Transmissionsgrenzen, Russian-Roulette-Regeln oder Speicherung des linearen Masters fest und garantiert keine Konvergenz.", "render.stage_panels.reference": "Referenz", "render.stage_panels.references": "Referenzen", "render.stage_panels.remove_optics": "Optik entfernen", @@ -3963,7 +3963,7 @@ "render.stage_panels.subtitle_environment": "Originale HDR-Umgebung · gesamte Szene", "render.stage_panels.subtitle_maps": "Erstellte räumliche Texturen · temporäre Vorschau", "render.stage_panels.subtitle_physical": "Schreibgeschützter Plan · kein Material erstellt oder zugewiesen", - "render.stage_panels.subtitle_quality": "Festes GPU-Budget · zukünftige Anforderungen ausgelassen", + "render.stage_panels.subtitle_quality": "GPU-Abtastbudget · nur aufgeführte Einstellungen", "render.stage_panels.subtitle_rig": "Erstellter Lichtaufbau · Lichtquellen und passive Flächen", "render.stage_panels.subtitle_saved_maps": "Erstellte Texturen · mit dieser Aufnahme gespeichert", "render.stage_panels.subtitle_stage": "Physischer Boden und Bühne · an das Produkt angepasst", @@ -3988,7 +3988,7 @@ "render.studio_area_help": "Bis zu vier einseitige Rechtecke. Orthogonale Halbkanten U und V bestimmen die Größe; U × V zeigt zur beleuchteten Seite. Die Koordinaten sind Weltmillimeter.", "render.studio_center": "Mittelpunkt X, Y, Z (mm)", "render.studio_denoise": "Rauschen im fertigen Bild reduzieren", - "render.studio_denoise_help": "Abschließender kantenerhaltender Filter; feine Details können weicher werden. Glas und scharfe spiegelnde Oberflächen umgehen den Filter.", + "render.studio_denoise_help": "Kantenerhaltender Filter für progressive und fertige Bilder; feine Details können weicher werden. Glas und scharfe spiegelnde Oberflächen umgehen den Filter.", "render.studio_direction": "Richtung zur Sonne (X, Y, Z)", "render.studio_environment": "Umgebung", "render.studio_environment_bounds": "Die Umgebungsdrehung muss endlich und innerhalb von ±1.000.000 Radiant liegen, die Intensität zwischen 0 und 100.", diff --git a/assets/locales/en.json b/assets/locales/en.json index ade4fab05..bb9d9c1ce 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -3020,9 +3020,9 @@ "render.adaptive_absolute": "Absolute RGB error floor", "render.adaptive_coverage": "Coverage error target", "render.adaptive_enable": "Allocate samples with independent pilots", - "render.adaptive_help": "GPU only. Independent pilot samples are discarded, then allocate 16 or more production samples per pixel up to Samples per pixel. RGB and coverage variance guide allocation; rare paths may be missed and capped pixels may remain noisy. The final report counts actual work. No certified noise or time guarantee.", + "render.adaptive_help": "Independent pilot samples are discarded, then choose 16 or more production samples per pixel up to Samples per pixel. CPU resource limits include both stages. RGB and coverage variance guide allocation; capped pixels can remain noisy. The final report counts actual samples.", "render.adaptive_minimum": "Minimum production samples", - "render.adaptive_pending": "GPU independent-pilot adaptive allocation and conditional Fresnel strata are available. Certified convergence, rare-event guarantees and CPU adaptive transport remain unavailable.", + "render.adaptive_pending": "Independent-pilot adaptive allocation is available for CPU and GPU. Conditional Fresnel strata require GPU. Statistical allocation does not certify convergence.", "render.adaptive_pilots": "Pilot samples per pixel", "render.adaptive_relative": "Relative RGB error target", "render.add_ground": "Add fitted ground to setup", @@ -3083,7 +3083,7 @@ "render.appearance_editor.replace": "Replace this body's saved optics", "render.appearance_editor.revalidate": "Revalidate this body", "render.appearance_editor.save": "Save these optics", - "render.appearance_editor.save_reason": "Saving these optics needs physical glass on a current GPU body. Coat and local image maps remain temporary.", + "render.appearance_editor.save_reason": "To save Glass, enable it on a current CPU or GPU body. Use Save coat to shot for clear coat. Local image files remain temporary.", "render.appearance_editor.saved": "Saved with this shot", "render.appearance_editor.saved_state": "These optics are saved with this shot.", "render.appearance_editor.scatter_reason": "Interior scattering needs a closed solid boundary.", @@ -3179,7 +3179,7 @@ "render.children.copy_request": "Copy request JSON", "render.children.coverage_error": "Coverage error", "render.children.cpu": "CPU ray tracing", - "render.children.denoise": "Reduce noise in the finished image", + "render.children.denoise": "Reduce image noise", "render.children.depth": "Path depth", "render.children.distortion": "Distortion", "render.children.edge_samples": "Edge samples", @@ -3311,7 +3311,7 @@ "render.cpu_point_help": "Up to eight point lights, added to the selected directional lighting. Distances are in mm; the minimum must not exceed the reference distance.", "render.cpu_primary_samples": "Edge samples per pixel", "render.cpu_progressive": "CPU progressive", - "render.cpu_progressive_help": "Accumulate the existing CPU integrator in passes of one primary sample. Selected reflections require one sample; area lights, dielectrics and anisotropy require Single image.", + "render.cpu_progressive_help": "Accumulate fresh CPU camera samples and show every complete pass. Selected reflections use one attempt per camera sample; certified glass and planar anisotropy keep their existing limits. Adaptive pilots and production share the CPU profile budget.", "render.cpu_progressive_limits": "At most 1,048,576 pixels and 16,777,216 pixel × sample evaluations. Changing samples never resizes the image automatically.", "render.cpu_progressive_seed": "CPU sampling seed", "render.cpu_progressive_spp": "samples per pixel", @@ -3487,7 +3487,7 @@ "render.export_display": "Export: display PNG", "render.export_image_label": "Export Image", "render.export_linear": "Export: raw linear EXR", - "render.exr_pending": "GPU can retain raw linear EXR. Compression, multilayer images and auxiliary render passes remain unavailable.", + "render.exr_pending": "CPU ray tracing and GPU path tracing can retain raw linear EXR. Compression, multilayer images and auxiliary render passes remain unavailable.", "render.film_grain": "Photographic grain", "render.fit": "Fit Product", "render.fixed_camera": "Camera", @@ -3850,7 +3850,7 @@ "render.method_cpu": "CPU ray tracing", "render.method_gpu": "GPU path tracing", "render.method_limit_raster": "Raster uses the fixed opaque studio preview. Select an explicit raytracing method for supported optical controls.", - "render.method_raster": "CPU raster", + "render.method_raster": "CPU raster (schematic)", "render.navigation_help": "The camera moves as in Design (Preferences › Navigation). Save Setup records the current camera.", "render.nested_enable": "Certified nested dielectrics", "render.nested_help": "Up to 16 containing layers; every parent must be convex and every child strictly inside it. Intersections, touching surfaces, thin sheets and straight-shadow transmission refuse. Camera-inside state follows the certified hierarchy. Does not create a liquid surface or merge touching CAD boundaries.", @@ -3878,7 +3878,7 @@ "render.output_exr_unavailable": "EXR output setup is unavailable here. Linear EXR export requires a completed GPU image with a retained linear master.", "render.output_fit": "Fit", "render.output_format": "Format", - "render.output_format_status": "PNG is the exact completed display image. Optional GPU EXR retains raw scene-linear FLOAT32 radiance before display filters. Export never substitutes the preview cache or a different job.", + "render.output_format_status": "PNG is the exact completed display image. Optional CPU/GPU EXR retains raw scene-linear FLOAT32 radiance before display filters. Export never substitutes the preview cache or a different job.", "render.output_grading": "Grading", "render.output_image": "Image", "render.output_largest": "{width} × {height} max", @@ -3963,7 +3963,7 @@ "render.quality_custom": "Custom", "render.quality_draft": "Draft", "render.quality_high": "High", - "render.quality_projection_help": "Q presets include future requirements. This action projects only a supported fixed-sample PNG budget and explicitly omits adaptive stopping, raw linear output and independent transmission limits.", + "render.quality_projection_help": "This review changes only resolution, sample budget, path depth, seed and noise reduction. Other settings are kept; the budget does not certify convergence.", "render.quality_review": "Review sampling budget", "render.queue_pending": "There is no automatic production queue or animation renderer in this UI. Completed still images remain separately exportable.", "render.radial_assign": "Assign Appearance", @@ -3994,7 +3994,7 @@ "render.result_navigation": "Pan and zoom use Navigation preferences. Space + drag pans.", "render.result_open": "Open the completed image in the main canvas.", "render.result_preview": "Live Preview", - "render.result_provisional": "Provisional CPU image", + "render.result_provisional": "Provisional image", "render.result_provisional_help": "This checkpoint is not exportable. Export keeps the last completed result; cancellation returns to that result.", "render.result_reduced_display": "Display preview reduced to the viewport device/cache limit. The retained PNG and export keep full resolution; native 100% inspection is unavailable for this reduced view.", "render.result_retained": "Showing the last completed image; a newer render has not replaced it.", @@ -4159,7 +4159,7 @@ "render.stage_panels.prepare_plan": "Prepare creation plan", "render.stage_panels.projects": "Projects", "render.stage_panels.quality_ack": "I acknowledge the fixed budget and its omissions", - "render.stage_panels.quality_omissions": "Adaptive stopping and error targets, separate transmission depth, Russian roulette rules, raw linear output, EXR master and convergence certification.", + "render.stage_panels.quality_omissions": "This budget does not set adaptive error targets, independent transmission limits, Russian roulette rules or raw-master retention, and does not guarantee convergence.", "render.stage_panels.reference": "Reference", "render.stage_panels.references": "References", "render.stage_panels.remove_optics": "Remove optics", @@ -4203,7 +4203,7 @@ "render.stage_panels.subtitle_environment": "Original HDR environment · whole scene", "render.stage_panels.subtitle_maps": "Authored spatial maps · temporary preview", "render.stage_panels.subtitle_physical": "Read-only plan · no material created or assigned", - "render.stage_panels.subtitle_quality": "Fixed GPU budget · future requirements omitted", + "render.stage_panels.subtitle_quality": "GPU sampling budget · listed fields only", "render.stage_panels.subtitle_rig": "Authored light rig · emitters and passive cards", "render.stage_panels.subtitle_saved_maps": "Authored maps · saved with this shot", "render.stage_panels.subtitle_stage": "Physical ground and stage · fitted to the product", @@ -4228,7 +4228,7 @@ "render.studio_area_help": "Up to four one-sided rectangles. Orthogonal half-edges U and V define size; U × V faces the lit side. Coordinates are world-space millimeters.", "render.studio_center": "Center X, Y, Z (mm)", "render.studio_denoise": "Reduce noise in the finished image", - "render.studio_denoise_help": "Final edge-aware filter; fine detail can soften. Glass and sharp specular surfaces bypass the filter.", + "render.studio_denoise_help": "Progressive and final images use an edge-aware filter; fine detail may soften. Glass and sharp specular surfaces bypass it.", "render.studio_direction": "Direction toward sun (X, Y, Z)", "render.studio_environment": "Environment", "render.studio_environment_bounds": "Environment rotation must be finite within ±1,000,000 radians and intensity between 0 and 100.", diff --git a/assets/locales/he.json b/assets/locales/he.json index d234fb5d6..a17d8dbd0 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -3020,9 +3020,9 @@ "render.adaptive_absolute": "רצפת שגיאת RGB מוחלטת", "render.adaptive_coverage": "יעד שגיאת כיסוי", "render.adaptive_enable": "הקצאת דגימות באמצעות דגימות גישוש עצמאיות", - "render.adaptive_help": "GPU בלבד. דגימות הגישוש העצמאיות מושלכות, ואז מוקצות 16 דגימות הפקה או יותר לכל פיקסל עד לערך „דגימות לכל פיקסל”. השונות של RGB ושל הכיסוי מכוונת את ההקצאה; מסלולים נדירים עלולים להיות מוחמצים ופיקסלים שהגיעו לתקרה עשויים להישאר רועשים. הדוח הסופי סופר את העבודה בפועל. אין ערובה מאושרת לרמת הרעש או לזמן.", + "render.adaptive_help": "דגימות החלוץ העצמאיות נזרקות, ואז נקבעות לכל פיקסל לפחות 16 דגימות הפקה, עד לערך דגימות לפיקסל. מגבלות משאבי CPU כוללות את שני השלבים. השונות ב-RGB ובכיסוי מנחה את ההקצאה; פיקסלים שהגיעו לתקרה עשויים להישאר רועשים. הדוח הסופי מונה את הדגימות בפועל.", "render.adaptive_minimum": "מינימום דגימות הפקה", - "render.adaptive_pending": "הקצאה אדפטיבית ב־GPU עם דגימות גישוש עצמאיות ושכבות פרנל מותנות זמינות. התכנסות מאושרת, ערובה לאירועים נדירים והעברה אדפטיבית ב־CPU עדיין אינן זמינות.", + "render.adaptive_pending": "הקצאה מסתגלת עם דגימות חלוץ עצמאיות זמינה ב-CPU וב-GPU. שכבות פרנל מותנות דורשות GPU. ההקצאה הסטטיסטית אינה מבטיחה התכנסות.", "render.adaptive_pilots": "דגימות גישוש לכל פיקסל", "render.adaptive_relative": "יעד שגיאת RGB יחסית", "render.add_ground": "הוספת קרקע מותאמת להגדרה", @@ -3083,7 +3083,7 @@ "render.appearance_editor.replace": "החלף את האופטיקה השמורה של גוף זה", "render.appearance_editor.revalidate": "אמת מחדש גוף זה", "render.appearance_editor.save": "שמור אופטיקה זו", - "render.appearance_editor.save_reason": "שמירת האופטיקה הזו דורשת זכוכית פיזיקלית בגוף GPU עדכני. הציפוי ומפות התמונה המקומיות נשארים זמניים.", + "render.appearance_editor.save_reason": "כדי לשמור זכוכית, יש להפעיל אותה בגוף CPU או GPU עדכני. לציפוי שקוף יש להשתמש בשמירת הציפוי בתצלום. קובצי תמונה מקומיים נשארים זמניים.", "render.appearance_editor.saved": "נשמר עם הצילום הזה", "render.appearance_editor.saved_state": "האופטיקה הזו נשמרת עם הצילום הזה.", "render.appearance_editor.scatter_reason": "פיזור פנימי דורש גבול של גוף מלא סגור.", @@ -3179,7 +3179,7 @@ "render.children.copy_request": "העתק JSON של הבקשה", "render.children.coverage_error": "שגיאת כיסוי", "render.children.cpu": "מעקב קרניים במעבד", - "render.children.denoise": "הפחת רעש בתמונה המוגמרת", + "render.children.denoise": "הפחתת רעש בתמונה", "render.children.depth": "עומק נתיב", "render.children.distortion": "עיוות", "render.children.edge_samples": "דגימות קצה", @@ -3311,7 +3311,7 @@ "render.cpu_point_help": "עד שמונה אורות נקודתיים, המתווספים לתאורה הכיוונית שנבחרה. המרחקים במילימטרים; המינימום אינו יכול לעלות על מרחק הייחוס.", "render.cpu_primary_samples": "דגימות קצה לכל פיקסל", "render.cpu_progressive": "CPU הדרגתי", - "render.cpu_progressive_help": "צבירה של אינטגרטור ה־CPU הקיים במעברים של דגימה ראשית אחת. החזרות שנבחרו דורשות דגימה אחת; אורות שטח, דיאלקטריים ואנאיזוטרופיה דורשים תמונה בודדת.", + "render.cpu_progressive_help": "נאספות דגימות מצלמת CPU חדשות ומוצג כל מעבר שהושלם. השתקפויות נבחרות משתמשות בניסיון אחד לכל דגימת מצלמה; זכוכית מאושרת ואנאיזוטרופיה מישורית שומרות על מגבלותיהן הקיימות. דגימות החלוץ וההפקה המסתגלות חולקות את תקציב פרופיל CPU.", "render.cpu_progressive_limits": "לכל היותר 1,048,576 פיקסלים ו־16,777,216 הערכות פיקסל × דגימה. שינוי הדגימות לעולם אינו משנה את גודל התמונה אוטומטית.", "render.cpu_progressive_seed": "זרע דגימה ב־CPU", "render.cpu_progressive_spp": "דגימות לכל פיקסל", @@ -3487,7 +3487,7 @@ "render.export_display": "ייצוא: PNG לתצוגה", "render.export_image_label": "ייצוא תמונה", "render.export_linear": "ייצוא: EXR ליניארי גולמי", - "render.exr_pending": "GPU יכול לשמור EXR ליניארי גולמי. דחיסה, תמונות רב־שכבתיות ומעברי הדמיה נלווים עדיין אינם זמינים.", + "render.exr_pending": "עקיבת קרניים ב־CPU ועקיבת נתיבים ב־GPU יכולות לשמור EXR ליניארי גולמי. דחיסה, תמונות רב־שכבתיות ומעברי הדמיה נלווים עדיין אינם זמינים.", "render.film_grain": "גרעיניות צילומית", "render.fit": "התאמת המוצר לתצוגה", "render.fixed_camera": "מצלמה", @@ -3850,7 +3850,7 @@ "render.method_cpu": "מעקב קרניים ב־CPU", "render.method_gpu": "מעקב מסלולים ב־GPU", "render.method_limit_raster": "רסטר משתמש בתצוגה המקדימה הקבועה של הסטודיו האטום. לפקדים האופטיים הנתמכים יש לבחור שיטת מעקב קרניים מפורשת.", - "render.method_raster": "רסטר ב־CPU", + "render.method_raster": "רסטר ב־CPU (סכמטי)", "render.navigation_help": "המצלמה נעה כמו בתכן (העדפות › ניווט). שמירת ההגדרה מתעדת את המצלמה הנוכחית.", "render.nested_enable": "דיאלקטריים מקוננים מאושרים", "render.nested_help": "עד 16 שכבות מכילות; כל הורה חייב להיות קמור וכל צאצא חייב להיות בתוכו לגמרי. חיתוכים, משטחים נוגעים, יריעות דקות והעברת צל ישרה נדחים. מצב מצלמה בפנים עוקב אחר ההיררכיה המאושרת. אינו יוצר משטח נוזל ואינו ממזג גבולות CAD נוגעים.", @@ -3878,7 +3878,7 @@ "render.output_exr_unavailable": "הגדרת פלט EXR אינה זמינה כאן. ייצוא EXR לינארי דורש תמונת GPU שהושלמה עם מאסטר לינארי שנשמר.", "render.output_fit": "התאם", "render.output_format": "פורמט", - "render.output_format_status": "PNG הוא תמונת התצוגה הגמורה המדויקת. EXR אופציונלי ב־GPU שומר קרינה גולמית ליניארית של הסצנה ב־FLOAT32 לפני מסנני התצוגה. הייצוא לעולם אינו מחליף אותה במטמון התצוגה המקדימה או במשימה אחרת.", + "render.output_format_status": "PNG הוא תמונת התצוגה הגמורה המדויקת. EXR אופציונלי ב־CPU או ב־GPU שומר קרינה גולמית ליניארית של הסצנה ב־FLOAT32 לפני מסנני התצוגה. הייצוא לעולם אינו מחליף אותה במטמון התצוגה המקדימה או במשימה אחרת.", "render.output_grading": "גריידינג", "render.output_image": "תמונה", "render.output_largest": "מקס׳ {width} × {height}", @@ -3963,7 +3963,7 @@ "render.quality_custom": "מותאם", "render.quality_draft": "טיוטה", "render.quality_high": "גבוהה", - "render.quality_projection_help": "פרופילי Q מוכנים כוללים דרישות עתידיות. פעולה זו משליכה רק תקציב PNG נתמך בדגימות קבועות, ומשמיטה במפורש עצירה אדפטיבית, פלט ליניארי גולמי ומגבלות העברה עצמאיות.", + "render.quality_projection_help": "בדיקה זו משנה רק רזולוציה, תקציב דגימות, עומק נתיב, זרע והפחתת רעש. ההגדרות האחרות נשמרות; התקציב אינו מעיד על התכנסות התמונה.", "render.quality_review": "סקירת תקציב הדגימה", "render.queue_pending": "בממשק זה אין תור הפקה אוטומטי ואין מנוע הדמיה לאנימציה. תמונות סטילס גמורות נשארות ניתנות לייצוא כל אחת בנפרד.", "render.radial_assign": "הקצה מראה", @@ -3994,7 +3994,7 @@ "render.result_navigation": "הזזה וזום משתמשים בהעדפות הניווט. רווח + גרירה מזיזים.", "render.result_open": "פתיחת התמונה הגמורה בקנבס הראשי.", "render.result_preview": "תצוגה מקדימה חיה", - "render.result_provisional": "תמונת CPU זמנית", + "render.result_provisional": "תמונה זמנית", "render.result_provisional_help": "נקודת ביקורת זו אינה ניתנת לייצוא. הייצוא שומר את התוצאה הגמורה האחרונה; ביטול חוזר לתוצאה הזאת.", "render.result_reduced_display": "התצוגה המקדימה הוקטנה למגבלת המכשיר או המטמון של אזור התצוגה. ה־PNG השמור והייצוא שומרים על רזולוציה מלאה; בדיקה ברזולוציה המקורית (100%) אינה זמינה בתצוגה המוקטנת הזאת.", "render.result_retained": "מוצגת התמונה הגמורה האחרונה; הדמיה חדשה יותר לא החליפה אותה.", @@ -4159,7 +4159,7 @@ "render.stage_panels.prepare_plan": "הכנת תוכנית יצירה", "render.stage_panels.projects": "מקרין", "render.stage_panels.quality_ack": "ידוע לי על התקציב הקבוע והפרטים המושמטים בו", - "render.stage_panels.quality_omissions": "עצירה מסתגלת ויעדי שגיאה, עומק העברה נפרד, כללי רולטה רוסית, פלט ליניארי גולמי, קובץ מקור EXR ואישור התכנסות.", + "render.stage_panels.quality_omissions": "תקציב זה אינו קובע יעדי שגיאה אדפטיביים, מגבלות מעבר אור נפרדות, כללי רולטה רוסית או שמירת מקור גולמי, ואינו מבטיח התכנסות של התמונה.", "render.stage_panels.reference": "ייחוס", "render.stage_panels.references": "ייחוסים", "render.stage_panels.remove_optics": "הסרת האופטיקה", @@ -4203,7 +4203,7 @@ "render.stage_panels.subtitle_environment": "סביבת HDR מקורית · הסצנה כולה", "render.stage_panels.subtitle_maps": "מפות מרחביות מעוצבות · תצוגה מקדימה זמנית", "render.stage_panels.subtitle_physical": "תוכנית לקריאה בלבד · לא נוצר או משויך חומר", - "render.stage_panels.subtitle_quality": "תקציב GPU קבוע · דרישות עתידיות מושמטות", + "render.stage_panels.subtitle_quality": "תקציב דגימה ב־GPU · השדות המפורטים בלבד", "render.stage_panels.subtitle_rig": "מערך תאורה מעוצב · פולטי אור וכרטיסים סבילים", "render.stage_panels.subtitle_saved_maps": "מפות מעוצבות · נשמרות עם צילום זה", "render.stage_panels.subtitle_stage": "קרקע ובמה פיזיות · מותאמות למוצר", @@ -4228,7 +4228,7 @@ "render.studio_area_help": "עד ארבעה מלבנים חד־צדדיים. חצאי הצלעות הניצבים U ו־V קובעים את הגודל; U × V פונה אל הצד המואר. הקואורדינטות במילימטרים של מרחב העולם.", "render.studio_center": "מרכז X, Y, Z (mm)", "render.studio_denoise": "הפחתת רעש בתמונה הסופית", - "render.studio_denoise_help": "מסנן סופי שמתחשב בקצוות; פרטים עדינים עלולים להתרכך. זכוכית ומשטחים ספקולריים חדים עוקפים את המסנן.", + "render.studio_denoise_help": "תמונות הדרגתיות וסופיות משתמשות במסנן שומר קצוות; פרטים עדינים עלולים להתרכך. זכוכית ומשטחים בעלי החזר חד אינם עוברים סינון.", "render.studio_direction": "כיוון אל השמש (X, Y, Z)", "render.studio_environment": "סביבה", "render.studio_environment_bounds": "סיבוב הסביבה חייב להיות סופי בטווח ±1,000,000 רדיאנים והעוצמה בין 0 ל־100.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index edfaf49f7..4495c01ed 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -3020,9 +3020,9 @@ "render.adaptive_absolute": "RGB 絶対誤差の下限", "render.adaptive_coverage": "被覆率の誤差目標", "render.adaptive_enable": "独立した予備サンプルで配分", - "render.adaptive_help": "GPU 専用。独立した予備サンプルは破棄され、各ピクセルに最小16から設定上限までの本サンプルを配分します。RGB と被覆率の分散を目安にしますが、まれな経路を見逃したり上限でノイズが残ったりします。最終レポートは実際の処理量を示します。ノイズや時間を保証しません。", + "render.adaptive_help": "独立したパイロットサンプルは破棄され、ピクセルごとに16以上、「ピクセルあたりのサンプル数」以下の本番サンプル数を決めます。CPUのリソース上限には両段階が含まれます。RGBとカバレッジの分散から配分し、上限に達したピクセルにはノイズが残ることがあります。最終レポートには実際のサンプル数を記録します。", "render.adaptive_minimum": "最小本サンプル数", - "render.adaptive_pending": "GPU の独立予備サンプルによる適応配分と条件付きフレネル層化が利用できます。収束の認証、まれな事象の保証、CPU 適応輸送は未対応です。", + "render.adaptive_pending": "独立したパイロットによる適応配分はCPUとGPUで利用できます。条件付きフレネル層にはGPUが必要です。統計的な配分は収束を保証しません。", "render.adaptive_pilots": "ピクセルごとの予備サンプル", "render.adaptive_relative": "RGB 相対誤差の目標", "render.add_ground": "フィットした床をセットアップに追加", @@ -3083,7 +3083,7 @@ "render.appearance_editor.replace": "このボディの保存済み光学設定を置換", "render.appearance_editor.revalidate": "このボディを再検証", "render.appearance_editor.save": "この光学設定を保存", - "render.appearance_editor.save_reason": "保存には現在のGPUボディの物理ガラスが必要です。コートとローカル画像マップは一時設定のままです。", + "render.appearance_editor.save_reason": "ガラスを保存するには、現在のCPUまたはGPUボディで有効にしてください。クリアコートは「コートをショットに保存」を使用します。ローカル画像ファイルは一時設定のままです。", "render.appearance_editor.saved": "このショットに保存", "render.appearance_editor.saved_state": "この光学設定はこのショットに保存されています。", "render.appearance_editor.scatter_reason": "内部散乱には閉じたソリッド境界が必要です。", @@ -3179,7 +3179,7 @@ "render.children.copy_request": "リクエストJSONをコピー", "render.children.coverage_error": "カバレッジ誤差", "render.children.cpu": "CPUレイトレーシング", - "render.children.denoise": "完成画像のノイズを低減", + "render.children.denoise": "画像のノイズを低減", "render.children.depth": "パス深度", "render.children.distortion": "歪み", "render.children.edge_samples": "エッジサンプル", @@ -3311,7 +3311,7 @@ "render.cpu_point_help": "選択した平行光に最大8個の点光源を追加できます。距離はmmで、最小距離は基準距離以下にしてください。", "render.cpu_primary_samples": "輪郭サンプル数/ピクセル", "render.cpu_progressive": "CPUプログレッシブ", - "render.cpu_progressive_help": "既存のCPU積分器を、一次サンプル1個ずつのパスで累積します。選択した反射は1サンプルが必要です。面光源、誘電体、異方性には固定画像を使用してください。", + "render.cpu_progressive_help": "新しいCPUカメラサンプルを蓄積し、完了したすべてのパスを表示します。選択した反射はカメラサンプルごとに1回評価します。認証済みガラスと平面異方性には従来の制限が適用されます。適応サンプリングのパイロットと本番は同じCPUプロファイル予算を使います。", "render.cpu_progressive_limits": "最大1,048,576ピクセル、ピクセル×サンプルの合計は16,777,216以下です。サンプル数を変えても画像サイズは自動変更されません。", "render.cpu_progressive_seed": "CPUサンプリングシード", "render.cpu_progressive_spp": "サンプル/ピクセル", @@ -3487,7 +3487,7 @@ "render.export_display": "書き出し:表示PNG", "render.export_image_label": "画像を書き出す", "render.export_linear": "書き出し:生の線形EXR", - "render.exr_pending": "GPUでは線形EXRを保持できます。圧縮、複数レイヤー、補助パスは未実装です。", + "render.exr_pending": "CPUレイトレーシングとGPUパストレーシングでは生の線形EXRを保持できます。圧縮、複数レイヤー、補助パスは未実装です。", "render.film_grain": "写真粒子", "render.fit": "製品を画面に合わせる", "render.fixed_camera": "カメラ", @@ -3850,7 +3850,7 @@ "render.method_cpu": "CPU レイトレーシング", "render.method_gpu": "GPU パストレーシング", "render.method_limit_raster": "ラスターは固定の不透明スタジオプレビューを使用します。対応する光学設定には明示的なレイトレーシング方式を選択してください。", - "render.method_raster": "CPU ラスター", + "render.method_raster": "CPU ラスター(模式図)", "render.navigation_help": "カメラはデザインと同じように動きます(環境設定 › ナビゲーション)。「セットアップを保存」で現在のカメラを記録します。", "render.nested_enable": "検証済み入れ子誘電体", "render.nested_help": "最大16層。親は凸形状、子は厳密に内部である必要があります。交差・接触・薄膜・直線透過影は拒否します。内部カメラは検証した階層を使います。液面の生成や接触するCAD境界の結合は行いません。", @@ -3878,7 +3878,7 @@ "render.output_exr_unavailable": "ここではEXR出力設定を利用できません。リニアEXR書き出しには、リニアマスターを保持した完成GPU画像が必要です。", "render.output_fit": "全体表示", "render.output_format": "形式", - "render.output_format_status": "PNGは完了した表示画像そのものです。GPUの任意EXRは表示フィルター前の生の線形FLOAT32放射輝度を保持します。プレビューキャッシュや別ジョブへの置換はありません。", + "render.output_format_status": "PNGは完了した表示画像そのものです。CPU/GPUの任意EXRは表示フィルター前の生の線形FLOAT32放射輝度を保持します。プレビューキャッシュや別ジョブへの置換はありません。", "render.output_grading": "カラーグレーディング", "render.output_image": "画像", "render.output_largest": "{width} × {height} 最大", @@ -3963,7 +3963,7 @@ "render.quality_custom": "カスタム", "render.quality_draft": "ドラフト", "render.quality_high": "高品質", - "render.quality_projection_help": "Qプリセットには将来の要件も含まれます。この操作は対応する固定サンプルPNG予算のみを適用し、適応的停止、生の線形出力、独立した透過制限は含みません。", + "render.quality_projection_help": "この確認で変更するのは、解像度、サンプル予算、パス深度、シード、ノイズ低減だけです。他の設定は維持され、収束は保証されません。", "render.quality_review": "サンプリング予算を確認", "render.queue_pending": "このUIには自動の本番キューやアニメーションレンダラーはありません。完了した静止画像は個別に書き出せます。", "render.radial_assign": "外観を割り当て", @@ -3994,7 +3994,7 @@ "render.result_navigation": "移動とズームはナビゲーション設定に従います。スペースキーを押しながらドラッグすると移動します。", "render.result_open": "完成した画像をメインキャンバスに表示します。", "render.result_preview": "ライブプレビュー", - "render.result_provisional": "CPU仮画像", + "render.result_provisional": "仮画像", "render.result_provisional_help": "この中間画像はエクスポートできません。最後に完成した結果をエクスポートします。キャンセルするとその結果に戻ります。", "render.result_reduced_display": "表示プレビューをビューポート機器またはキャッシュの上限に縮小しています。保持したPNGと書き出しは元の解像度です。この縮小表示ではネイティブ100%表示はできません。", "render.result_retained": "最後に完成した画像を表示しています。新しいレンダリングにはまだ置き換わっていません。", @@ -4159,7 +4159,7 @@ "render.stage_panels.prepare_plan": "作成計画を準備", "render.stage_panels.projects": "投影", "render.stage_panels.quality_ack": "固定予算と省略事項を確認しました", - "render.stage_panels.quality_omissions": "適応停止と誤差目標、個別の透過深度、ロシアンルーレット規則、線形RAW出力、EXRマスター、収束認証。", + "render.stage_panels.quality_omissions": "この予算は、適応サンプリングの誤差目標、独立した透過制限、ロシアンルーレット規則、リニアマスターの保持を設定しません。収束も保証しません。", "render.stage_panels.reference": "参照", "render.stage_panels.references": "参照", "render.stage_panels.remove_optics": "光学設定を削除", @@ -4203,7 +4203,7 @@ "render.stage_panels.subtitle_environment": "オリジナルHDR環境・シーン全体", "render.stage_panels.subtitle_maps": "作成済み空間マップ・一時プレビュー", "render.stage_panels.subtitle_physical": "読み取り専用計画・マテリアルの作成や割り当てなし", - "render.stage_panels.subtitle_quality": "固定GPU予算・将来の要件は省略", + "render.stage_panels.subtitle_quality": "GPUサンプリング予算 · 記載された設定のみ", "render.stage_panels.subtitle_rig": "作成済みライトリグ・光源と受動カード", "render.stage_panels.subtitle_saved_maps": "作成済みマップ・このショットに保存", "render.stage_panels.subtitle_stage": "物理的な地面とステージ・製品にフィット", @@ -4228,7 +4228,7 @@ "render.studio_area_help": "最大 4 個の片面矩形です。直交する半辺 U と V でサイズを定め、U × V が発光方向になります。座標はワールド空間の mm です。", "render.studio_center": "中心 X, Y, Z (mm)", "render.studio_denoise": "完成画像のノイズを低減", - "render.studio_denoise_help": "輪郭を保持する最終フィルターです。微細な描写が柔らかくなることがあります。ガラスと鋭い鏡面反射は対象外です。", + "render.studio_denoise_help": "プログレッシブ画像と完成画像に輪郭を保持するフィルターを適用します。微細な描写が柔らかくなることがあります。ガラスと鋭い鏡面反射は対象外です。", "render.studio_direction": "太陽に向かう方向 (X, Y, Z)", "render.studio_environment": "環境", "render.studio_environment_bounds": "環境回転は±1,000,000ラジアン以内の有限値、強度は0~100でなければなりません。", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index b4f612470..932aa85d6 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -2368,7 +2368,7 @@ "render.appearance_editor.replace": "이 바디의 저장된 광학 설정 교체", "render.appearance_editor.revalidate": "이 바디 다시 검증", "render.appearance_editor.save": "이 광학 설정 저장", - "render.appearance_editor.save_reason": "저장하려면 현재 GPU 바디에 물리 유리가 필요합니다. 코트와 로컬 이미지 맵은 임시로 유지됩니다.", + "render.appearance_editor.save_reason": "유리를 저장하려면 현재 CPU 또는 GPU 바디에서 활성화하세요. 클리어 코트는 샷에 코트 저장을 사용하세요. 로컬 이미지 파일은 임시 설정으로 유지됩니다.", "render.appearance_editor.saved": "이 샷에 저장됨", "render.appearance_editor.saved_state": "이 광학 설정은 이 샷과 함께 저장되어 있습니다.", "render.appearance_editor.scatter_reason": "내부 산란에는 닫힌 솔리드 경계가 필요합니다.", @@ -2464,7 +2464,7 @@ "render.children.copy_request": "요청 JSON 복사", "render.children.coverage_error": "커버리지 오차", "render.children.cpu": "CPU 레이 트레이싱", - "render.children.denoise": "완성 이미지의 노이즈 줄이기", + "render.children.denoise": "이미지 노이즈 줄이기", "render.children.depth": "경로 깊이", "render.children.distortion": "왜곡", "render.children.edge_samples": "모서리 샘플", @@ -2772,7 +2772,7 @@ "render.export_display": "내보내기: 표시 PNG", "render.export_image_label": "이미지 내보내기", "render.export_linear": "내보내기: 원본 선형 EXR", - "render.exr_pending": "GPU는 원본 선형 EXR을 보존할 수 있습니다. 압축, 다중 레이어 이미지 및 보조 렌더 패스는 아직 사용할 수 없습니다.", + "render.exr_pending": "CPU 레이 트레이싱과 GPU 패스 트레이싱은 원본 선형 EXR을 보존할 수 있습니다. 압축, 다중 레이어 이미지 및 보조 렌더 패스는 아직 사용할 수 없습니다.", "render.film_grain": "사진 그레인", "render.fit": "제품에 맞추기", "render.fixed_camera": "카메라", @@ -3133,7 +3133,6 @@ "render.method_cpu": "CPU 레이 트레이싱", "render.method_gpu": "GPU 패스 트레이싱", "render.method_limit_raster": "래스터는 고정된 불투명 스튜디오 미리보기를 사용합니다. 지원되는 광학 컨트롤을 쓰려면 명시적인 레이 트레이싱 방식을 선택하세요.", - "render.method_raster": "CPU 래스터", "render.navigation_help": "카메라는 디자인에서와 같이 움직입니다(환경설정 › 탐색). 설정 저장은 현재 카메라를 기록합니다.", "render.nested_enable": "보증된 중첩 유전체", "render.nested_help": "최대 16개의 포함 레이어. 모든 부모는 볼록해야 하고 모든 자식은 부모 안에 완전히 들어가야 합니다. 교차, 맞닿은 표면, 얇은 판, 직선 그림자 투과는 거부됩니다. 카메라 내부 상태는 보증된 계층을 따릅니다. 액체 표면을 만들거나 맞닿은 CAD 경계를 병합하지는 않습니다.", @@ -3161,7 +3160,7 @@ "render.output_exr_unavailable": "여기서는 EXR 출력을 설정할 수 없습니다. 선형 EXR 내보내기에는 선형 원본을 보관한 완료된 GPU 이미지가 필요합니다.", "render.output_fit": "맞춤", "render.output_format": "형식", - "render.output_format_status": "PNG는 완료된 표시 이미지 그대로입니다. 선택적 GPU EXR은 표시 필터 전 선형 FLOAT32 방사 휘도를 보존합니다. 미리보기 캐시나 다른 작업으로 바꾸어 내보내지 않습니다.", + "render.output_format_status": "PNG는 완료된 표시 이미지 그대로입니다. 선택적 CPU/GPU EXR은 표시 필터 전 선형 FLOAT32 방사 휘도를 보존합니다. 미리보기 캐시나 다른 작업으로 바꾸어 내보내지 않습니다.", "render.output_grading": "색 보정", "render.output_image": "이미지", "render.output_largest": "{width} × {height} 최대", @@ -3246,7 +3245,7 @@ "render.quality_custom": "사용자 지정", "render.quality_draft": "초안", "render.quality_high": "높음", - "render.quality_projection_help": "Q 프리셋에는 향후 요구 사항이 포함됩니다. 이 동작은 지원되는 고정 샘플 PNG 예산만 변환하며, 적응형 중지, 원본 선형 출력, 독립 투과 제한은 명시적으로 생략합니다.", + "render.quality_projection_help": "이 검토에서는 해상도, 샘플 예산, 경로 깊이, 시드 및 노이즈 제거만 변경합니다. 다른 설정은 유지되며 수렴은 보장되지 않습니다.", "render.quality_review": "샘플링 예산 검토", "render.queue_pending": "이 UI에는 자동 프로덕션 대기열이나 애니메이션 렌더러가 없습니다. 완료된 정지 이미지는 별도로 내보낼 수 있습니다.", "render.radial_assign": "외관 지정", @@ -3277,7 +3276,6 @@ "render.result_navigation": "이동과 확대/축소는 탐색 환경 설정을 따릅니다. Space + 드래그로 이동합니다.", "render.result_open": "완료된 이미지를 메인 캔버스에서 엽니다.", "render.result_preview": "실시간 미리보기", - "render.result_provisional": "임시 CPU 이미지", "render.result_provisional_help": "이 체크포인트는 내보낼 수 없습니다. 내보내기는 마지막 완료 결과를 유지하며, 취소하면 그 결과로 돌아갑니다.", "render.result_reduced_display": "표시 미리보기를 뷰포트 장치 또는 캐시 제한에 맞춰 축소했습니다. 보관된 PNG와 내보내기는 전체 해상도를 유지합니다. 이 축소 보기에서는 원본 100% 검사가 불가능합니다.", "render.result_retained": "마지막 완료 이미지를 표시하고 있습니다. 더 새로운 렌더링이 이를 대체하지 않았습니다.", @@ -3441,7 +3439,7 @@ "render.stage_panels.prepare_plan": "생성 계획 준비", "render.stage_panels.projects": "투영", "render.stage_panels.quality_ack": "고정 예산과 생략 사항을 확인했습니다", - "render.stage_panels.quality_omissions": "적응형 중지 및 오차 목표, 별도 투과 깊이, 러시안 룰렛 규칙, 원시 선형 출력, EXR 마스터 및 수렴 인증.", + "render.stage_panels.quality_omissions": "이 예산은 적응형 오차 목표, 독립적인 투과 한도, 러시안 룰렛 규칙 또는 선형 마스터 보존을 설정하지 않으며 수렴을 보장하지 않습니다.", "render.stage_panels.reference": "참조", "render.stage_panels.references": "참조", "render.stage_panels.remove_optics": "광학 설정 제거", @@ -3485,7 +3483,7 @@ "render.stage_panels.subtitle_environment": "원본 HDR 환경 · 전체 장면", "render.stage_panels.subtitle_maps": "제작된 공간 맵 · 임시 미리 보기", "render.stage_panels.subtitle_physical": "읽기 전용 계획 · 재질 생성 또는 할당 없음", - "render.stage_panels.subtitle_quality": "고정 GPU 예산 · 향후 요구 사항 생략", + "render.stage_panels.subtitle_quality": "GPU 샘플링 예산 · 표시된 설정만 변경", "render.stage_panels.subtitle_rig": "제작된 조명 리그 · 광원 및 수동 카드", "render.stage_panels.subtitle_saved_maps": "제작된 맵 · 이 샷에 저장", "render.stage_panels.subtitle_stage": "물리적 바닥 및 스테이지 · 제품에 맞춤", @@ -3510,7 +3508,7 @@ "render.studio_area_help": "단면 직사각형 최대 네 개. 직교하는 반변 U와 V가 크기를 정하고, U × V가 비추는 쪽을 향합니다. 좌표는 월드 공간 밀리미터입니다.", "render.studio_center": "중심 X, Y, Z (mm)", "render.studio_denoise": "완성 이미지의 노이즈 줄이기", - "render.studio_denoise_help": "최종 가장자리 인식 필터입니다. 미세한 디테일이 부드러워질 수 있습니다. 유리와 날카로운 정반사 표면은 필터를 거치지 않습니다.", + "render.studio_denoise_help": "프로그레시브 이미지와 완성 이미지에 경계를 보존하는 필터를 적용합니다. 미세한 디테일이 부드러워질 수 있습니다. 유리와 날카로운 정반사 표면은 필터를 거치지 않습니다.", "render.studio_direction": "태양 방향 (X, Y, Z)", "render.studio_environment": "환경", "render.studio_environment_bounds": "환경 회전은 ±1,000,000라디안 이내의 유한한 값이어야 하고 강도는 0과 100 사이여야 합니다.", diff --git a/assets/locales/pending/cpu-aging.json b/assets/locales/pending/cpu-aging.json new file mode 100644 index 000000000..cf013c4cf --- /dev/null +++ b/assets/locales/pending/cpu-aging.json @@ -0,0 +1,29 @@ +{ + "ar": { + "render.aging_raytrace_help": "يُطبّق التعتيق في تتبع الأشعة على المعالج وتتبع المسارات على المعالج الرسومي. يبقى التصيير النقطي تخطيطياً." + }, + "de": { + "render.aging_raytrace_help": "Alterung wird beim CPU-Raytracing und GPU-Pathtracing angewendet. Raster bleibt eine schematische Darstellung." + }, + "en": { + "render.aging_raytrace_help": "Aging is applied by CPU ray tracing and GPU path tracing. Raster keeps schematic rendering." + }, + "en-GB": { + "render.aging_raytrace_help": "Ageing is applied by CPU ray tracing and GPU path tracing. Raster keeps schematic rendering." + }, + "he": { + "render.aging_raytrace_help": "התיישנות מוחלת במעקב קרניים במעבד ובמעקב מסלולים במעבד הגרפי. רינדור רסטר נשאר סכמטי." + }, + "ja": { + "render.aging_raytrace_help": "エイジングはCPUレイトレーシングとGPUパストレーシングで適用されます。ラスタは模式的な描画を維持します。" + }, + "ko": { + "render.aging_raytrace_help": "에이징은 CPU 광선 추적과 GPU 경로 추적에 적용됩니다. 래스터는 도식적인 렌더링을 유지합니다." + }, + "vi": { + "render.aging_raytrace_help": "Hiệu ứng lão hoá được áp dụng khi dò tia bằng CPU và dò đường đi bằng GPU. Kết xuất raster giữ kiểu sơ đồ." + }, + "zh": { + "render.aging_raytrace_help": "老化效果适用于CPU光线追踪和GPU路径追踪。光栅保持示意渲染。" + } +} diff --git a/assets/locales/pending/cpu-atmosphere-ui.json b/assets/locales/pending/cpu-atmosphere-ui.json new file mode 100644 index 000000000..fb68e9f74 --- /dev/null +++ b/assets/locales/pending/cpu-atmosphere-ui.json @@ -0,0 +1,98 @@ +{ + "ar": { + "render.cpu_volume_enable_path": "تفعيل الإضاءة غير المباشرة", + "render.cpu_volume_enable_path_plan": "تتبع أشعة CPU · عمق المسار {depth} · {spp} عينة/بكسل · بذرة {seed} · ظلال متتبعة. يحتفظ بالغلاف الجوي وميزانية الصورة المحددين.", + "render.cpu_volume_help": "يستخدم الغلاف الجوي على CPU الإضاءة غير المباشرة. يحافظ الانطفاء الصفري على الصندوق المحفوظ دون ضباب.", + "render.cpu_volume_method_adopt": "تتبع أشعة CPU مع إضاءة غير مباشرة", + "render.cpu_volume_method_incompatible": "لا يمكن نقل إعدادات الإضاءة أو أخذ العينات أو الغلاف الجوي هذه إلى هذه الطريقة. تبقى إعداداتك محفوظة.", + "render.cpu_volume_path_required": "فعّل الإضاءة غير المباشرة لاستخدام الغلاف الجوي على CPU.", + "render.volume_denoise_required": "أوقف تقليل الضوضاء لاستخدام الغلاف الجوي.", + "render.volume_glass_required": "لا يمكن الجمع بين الغلاف الجوي والزجاج في هذا الإعداد.", + "render.volume_lighting_required": "اختر بيئة أو مجموعة إضاءة محددة لتصيير الغلاف الجوي.", + "render.volume_single_stratum_required": "استخدم عينة نفاذ واحدة لتصيير الغلاف الجوي." + }, + "de": { + "render.cpu_volume_enable_path": "Indirekte Beleuchtung einschalten", + "render.cpu_volume_enable_path_plan": "CPU-Raytracing · Pfadtiefe {depth} · {spp} Samples/Pixel · Seed {seed} · Raytracing-Schatten. Atmosphäre und Bildbudget bleiben erhalten.", + "render.cpu_volume_help": "CPU-Atmosphäre nutzt indirekte Beleuchtung. Bei Extinktion null bleibt die gespeicherte Box ohne Nebel erhalten.", + "render.cpu_volume_method_adopt": "CPU-Raytracing mit indirekter Beleuchtung", + "render.cpu_volume_method_incompatible": "Diese Licht-, Sampling- oder Atmosphäreinstellungen lassen sich nicht auf diese Methode übertragen. Die Einstellungen bleiben erhalten.", + "render.cpu_volume_path_required": "Indirekte Beleuchtung einschalten, um CPU-Atmosphäre zu nutzen.", + "render.volume_denoise_required": "Für Atmosphäre die Rauschreduzierung ausschalten.", + "render.volume_glass_required": "Atmosphäre und Glas können in dieser Einstellung nicht kombiniert werden.", + "render.volume_lighting_required": "Für Atmosphäre eine Umgebung oder ein eigenes Lichtrig wählen.", + "render.volume_single_stratum_required": "Für Atmosphäre ein Transmissionssample verwenden." + }, + "en": { + "render.cpu_volume_enable_path": "Enable Indirect lighting", + "render.cpu_volume_enable_path_plan": "CPU ray tracing · path depth {depth} · {spp} samples/pixel · seed {seed} · traced shadows. Keeps the authored atmosphere and image budget.", + "render.cpu_volume_help": "CPU Atmosphere uses Indirect lighting. Zero extinction keeps the saved box without fog.", + "render.cpu_volume_method_adopt": "CPU ray tracing with indirect lighting", + "render.cpu_volume_method_incompatible": "These light, sampling or atmosphere settings cannot be transferred to this method. Your settings are kept.", + "render.cpu_volume_path_required": "Enable Indirect lighting to use CPU Atmosphere.", + "render.volume_denoise_required": "Turn off noise reduction to use Atmosphere.", + "render.volume_glass_required": "Atmosphere cannot be combined with Glass in this setup.", + "render.volume_lighting_required": "Choose an environment or an explicit light rig to render Atmosphere.", + "render.volume_single_stratum_required": "Use one transmission sample to render Atmosphere." + }, + "he": { + "render.cpu_volume_enable_path": "הפעלת תאורה עקיפה", + "render.cpu_volume_enable_path_plan": "מעקב קרניים ב־CPU · עומק מסלול {depth} · {spp} דגימות לפיקסל · זרע {seed} · צללים במעקב קרניים. האטמוספרה ותקציב התמונה שנקבעו נשמרים.", + "render.cpu_volume_help": "אטמוספרה ב־CPU משתמשת בתאורה עקיפה. הכחדה אפסית שומרת את התיבה ללא ערפל.", + "render.cpu_volume_method_adopt": "מעקב קרניים ב־CPU עם תאורה עקיפה", + "render.cpu_volume_method_incompatible": "לא ניתן להעביר הגדרות תאורה, דגימה או אטמוספרה אלה לשיטה זו. ההגדרות שלך נשמרות.", + "render.cpu_volume_path_required": "יש להפעיל תאורה עקיפה כדי להשתמש באטמוספרה ב־CPU.", + "render.volume_denoise_required": "יש לכבות הפחתת רעש כדי להשתמש באטמוספרה.", + "render.volume_glass_required": "לא ניתן לשלב אטמוספרה וזכוכית בהגדרה זו.", + "render.volume_lighting_required": "יש לבחור סביבה או מערך תאורה מפורש כדי לרנדר אטמוספרה.", + "render.volume_single_stratum_required": "יש להשתמש בדגימת מעבר אחת כדי לרנדר אטמוספרה." + }, + "ja": { + "render.cpu_volume_enable_path": "間接照明を有効にする", + "render.cpu_volume_enable_path_plan": "CPUレイトレーシング · パス深度{depth} · {spp}サンプル/ピクセル · シード{seed} · レイトレースシャドウ。大気と画像予算の設定を保持します。", + "render.cpu_volume_help": "CPUの大気は間接照明を使用します。消散係数がゼロでも、霧のないボックスとして設定は保存されます。", + "render.cpu_volume_method_adopt": "間接照明を使うCPUレイトレーシング", + "render.cpu_volume_method_incompatible": "この照明、サンプリング、大気の設定はこの方式に引き継げません。設定は保持されます。", + "render.cpu_volume_path_required": "CPUの大気を使うには間接照明を有効にしてください。", + "render.volume_denoise_required": "大気を使うにはノイズ低減をオフにしてください。", + "render.volume_glass_required": "この設定では大気とガラスを併用できません。", + "render.volume_lighting_required": "大気を描画するには環境または明示的なライト構成を選んでください。", + "render.volume_single_stratum_required": "大気を描画するには透過サンプル数を1にしてください。" + }, + "ko": { + "render.cpu_volume_enable_path": "간접 조명 켜기", + "render.cpu_volume_enable_path_plan": "CPU 레이 트레이싱 · 경로 깊이 {depth} · 픽셀당 {spp}샘플 · 시드 {seed} · 레이 트레이싱 그림자. 작성한 대기와 이미지 예산을 유지합니다.", + "render.cpu_volume_help": "CPU 대기는 간접 조명을 사용합니다. 소광 계수가 0이면 저장된 상자는 안개 없이 유지됩니다.", + "render.cpu_volume_method_adopt": "간접 조명을 사용하는 CPU 레이 트레이싱", + "render.cpu_volume_method_incompatible": "이 조명, 샘플링 또는 대기 설정을 이 방식으로 옮길 수 없습니다. 설정은 유지됩니다.", + "render.cpu_volume_path_required": "CPU 대기를 사용하려면 간접 조명을 켜세요.", + "render.volume_denoise_required": "대기를 사용하려면 노이즈 감소를 끄세요.", + "render.volume_glass_required": "이 설정에서는 대기와 유리를 함께 사용할 수 없습니다.", + "render.volume_lighting_required": "대기를 렌더링하려면 환경 또는 명시적인 조명 구성을 선택하세요.", + "render.volume_single_stratum_required": "대기를 렌더링하려면 투과 샘플을 1로 설정하세요." + }, + "vi": { + "render.cpu_volume_enable_path": "Bật chiếu sáng gián tiếp", + "render.cpu_volume_enable_path_plan": "Dò tia CPU · độ sâu đường đi {depth} · {spp} mẫu/pixel · hạt giống {seed} · bóng dò tia. Giữ nguyên khí quyển và ngân sách ảnh đã đặt.", + "render.cpu_volume_help": "Khí quyển trên CPU dùng chiếu sáng gián tiếp. Hệ số suy giảm bằng không vẫn giữ hộp đã lưu mà không tạo sương.", + "render.cpu_volume_method_adopt": "Dò tia CPU với chiếu sáng gián tiếp", + "render.cpu_volume_method_incompatible": "Không thể chuyển các thiết lập đèn, lấy mẫu hoặc khí quyển này sang phương pháp này. Thiết lập của bạn được giữ nguyên.", + "render.cpu_volume_path_required": "Bật chiếu sáng gián tiếp để dùng Khí quyển trên CPU.", + "render.volume_denoise_required": "Tắt giảm nhiễu để dùng Khí quyển.", + "render.volume_glass_required": "Không thể kết hợp Khí quyển và Kính trong thiết lập này.", + "render.volume_lighting_required": "Chọn môi trường hoặc bộ đèn tường minh để kết xuất Khí quyển.", + "render.volume_single_stratum_required": "Dùng một mẫu truyền sáng để kết xuất Khí quyển." + }, + "zh": { + "render.cpu_volume_enable_path": "启用间接照明", + "render.cpu_volume_enable_path_plan": "CPU 光线追踪 · 路径深度 {depth} · 每像素 {spp} 个采样 · 种子 {seed} · 追踪阴影。保留已编写的大气和图像预算。", + "render.cpu_volume_help": "CPU 大气使用间接照明。消光系数为零时,已保存的包围盒仍会保留,但不会产生雾。", + "render.cpu_volume_method_adopt": "使用间接照明的 CPU 光线追踪", + "render.cpu_volume_method_incompatible": "这些灯光、采样或大气设置无法转移到此方式。您的设置会保留。", + "render.cpu_volume_path_required": "启用间接照明以使用 CPU 大气。", + "render.volume_denoise_required": "关闭降噪以使用大气。", + "render.volume_glass_required": "此设置无法同时使用大气和玻璃。", + "render.volume_lighting_required": "选择环境或显式灯光配置以渲染大气。", + "render.volume_single_stratum_required": "将透射采样数设为 1 以渲染大气。" + } +} diff --git a/assets/locales/pending/cpu-constant-environment.json b/assets/locales/pending/cpu-constant-environment.json new file mode 100644 index 000000000..4fd5a846c --- /dev/null +++ b/assets/locales/pending/cpu-constant-environment.json @@ -0,0 +1,42 @@ +{ + "ar": { + "render.cpu_constant_direct_help": "بدون الإضاءة غير المباشرة، يمكن أن يظهر هذا المصدر الثابت في الانعكاسات وعبر الزجاج. لكنه لا يضيء الأسطح المعتمة. فعّل الإضاءة غير المباشرة لاستخدامه في إضاءة المشهد.", + "render.cpu_constant_enable_indirect_plan": "عمق المسار {depth}؛ أخذ عينات تدريجي بمعدل {spp} عينة/بكسل (البذرة {seed})؛ شعاع أولي واحد لكل عينة؛ ظلال متتبعة. يحتفظ بحجم الصورة وميزانية CPU والإعدادات الأخرى.", + "render.cpu_indirect_method_required": "اختر تتبع أشعة CPU لتفعيل وضع الإضاءة غير المباشرة هذا." + }, + "de": { + "render.cpu_constant_direct_help": "Ohne indirekte Beleuchtung kann diese konstante Quelle in Reflexionen und durch Glas sichtbar sein. Sie beleuchtet keine undurchsichtigen Flächen. Schalte indirekte Beleuchtung ein, um sie als Szenenlicht zu nutzen.", + "render.cpu_constant_enable_indirect_plan": "Pfadtiefe {depth}; progressives Sampling mit {spp} Samples/Pixel (Seed {seed}); ein Primärstrahl pro Sample; Raytracing-Schatten. Bildgröße, CPU-Budget und andere Einstellungen bleiben erhalten.", + "render.cpu_indirect_method_required": "Wähle CPU-Raytracing, um diesen Modus für indirekte Beleuchtung einzuschalten." + }, + "en": { + "render.cpu_constant_direct_help": "Without Indirect lighting, this constant source can appear in reflections and through Glass. It does not light opaque surfaces. Enable Indirect lighting to use it for scene lighting.", + "render.cpu_constant_enable_indirect_plan": "Path depth {depth}; progressive sampling at {spp} samples/pixel (seed {seed}); one primary ray per sample; traced shadows. Keeps your image size, CPU budget and other settings.", + "render.cpu_indirect_method_required": "Choose CPU ray tracing to enable this Indirect lighting mode." + }, + "he": { + "render.cpu_constant_direct_help": "ללא תאורה עקיפה, מקור קבוע זה עשוי להופיע בהשתקפויות ודרך זכוכית. הוא אינו מאיר משטחים אטומים. יש להפעיל תאורה עקיפה כדי להשתמש בו לתאורת הסצנה.", + "render.cpu_constant_enable_indirect_plan": "עומק מסלול {depth}; דגימה הדרגתית עם {spp} דגימות לפיקסל (זרע {seed}); קרן ראשית אחת לכל דגימה; צללים במעקב קרניים. גודל התמונה, תקציב ה־CPU וההגדרות האחרות נשמרים.", + "render.cpu_indirect_method_required": "יש לבחור מעקב קרניים ב־CPU כדי להפעיל מצב זה של תאורה עקיפה." + }, + "ja": { + "render.cpu_constant_direct_help": "間接照明を使わない場合、この一定の光源は反射やガラス越しに見えることがありますが、不透明な面は照らしません。シーンの照明に使うには、間接照明を有効にしてください。", + "render.cpu_constant_enable_indirect_plan": "パスの深さ {depth}、ピクセルあたり {spp} サンプルのプログレッシブサンプリング(シード {seed})、各サンプルに一次レイ1本、レイトレーシングの影を使用します。画像サイズ、CPU予算、その他の設定は保持します。", + "render.cpu_indirect_method_required": "この間接照明モードを有効にするには、CPUレイトレーシングを選択してください。" + }, + "ko": { + "render.cpu_constant_direct_help": "간접 조명이 꺼져 있으면 이 일정한 광원은 반사나 유리를 통해 보일 수 있지만 불투명한 표면을 밝히지는 않습니다. 장면 조명으로 사용하려면 간접 조명을 켜세요.", + "render.cpu_constant_enable_indirect_plan": "경로 깊이 {depth}, 픽셀당 {spp}개 샘플의 점진적 샘플링(시드 {seed}), 샘플당 기본 광선 1개, 추적된 그림자를 사용합니다. 이미지 크기, CPU 예산 및 다른 설정을 유지합니다.", + "render.cpu_indirect_method_required": "이 간접 조명 모드를 켜려면 CPU 레이 트레이싱을 선택하세요." + }, + "vi": { + "render.cpu_constant_direct_help": "Khi tắt Chiếu sáng gián tiếp, nguồn sáng đồng nhất này có thể xuất hiện trong phản xạ và qua Kính nhưng không chiếu sáng các bề mặt đục. Bật Chiếu sáng gián tiếp để dùng nguồn này chiếu sáng cảnh.", + "render.cpu_constant_enable_indirect_plan": "Độ sâu đường đi {depth}; lấy mẫu tăng dần với {spp} mẫu/pixel (hạt giống {seed}); một tia sơ cấp cho mỗi mẫu; bóng đổ dò tia. Giữ kích thước ảnh, ngân sách CPU và các cài đặt khác.", + "render.cpu_indirect_method_required": "Chọn dò tia CPU để bật chế độ Chiếu sáng gián tiếp này." + }, + "zh": { + "render.cpu_constant_direct_help": "未启用间接照明时,此恒定光源可能出现在反射中或透过玻璃可见,但不会照亮不透明表面。要用它照亮场景,请启用间接照明。", + "render.cpu_constant_enable_indirect_plan": "路径深度 {depth};每像素 {spp} 个样本的渐进采样(种子 {seed});每个样本一条主光线;光线追踪阴影。保留图像尺寸、CPU预算和其他设置。", + "render.cpu_indirect_method_required": "请选择CPU光线追踪以启用此间接照明模式。" + } +} diff --git a/assets/locales/pending/cpu-path-lighting.json b/assets/locales/pending/cpu-path-lighting.json new file mode 100644 index 000000000..f3df12dc2 --- /dev/null +++ b/assets/locales/pending/cpu-path-lighting.json @@ -0,0 +1,58 @@ +{ + "ar": { + "render.cpu_glass_enable_path": "تشغيل الإضاءة غير المباشرة", + "render.cpu_path_depth": "عمق المسار", + "render.cpu_path_help": "تحسب الضوء المرتد بين الأسطح المعتمة والمار عبر أشكال الزجاج المدعومة. تتطلب التصيير التدريجي وظلال تتبع الأشعة. يحسب عمق المسار الأسطح المضاءة وحدود الزجاج وأحداث التشتت بدءاً من أول تقاطع (1–16). يقتصر العمق 1 على الإضاءة المباشرة للأسطح المعتمة؛ وتسمح القيم الأعلى بمزيد من الارتدادات أو عبور الزجاج وقد تستغرق وقتاً أطول. أوقف الإضاءة غير المباشرة لاستخدام الانعكاسات المخصصة أو التباين الاتجاهي.", + "render.cpu_path_lighting": "إضاءة غير مباشرة", + "render.cpu_path_optics_reason": "تبقى إعداداتك كما هي. أوقف الإضاءة غير المباشرة لاستخدام الانعكاسات المخصصة أو التباين الاتجاهي." + }, + "de": { + "render.cpu_glass_enable_path": "Indirekte Beleuchtung einschalten", + "render.cpu_path_depth": "Pfadtiefe", + "render.cpu_path_help": "Berechnet Licht, das zwischen undurchsichtigen Flächen und durch unterstützte Glasformen läuft. Erfordert progressives Rendern und Raytracing-Schatten. Die Pfadtiefe zählt beleuchtete Flächen, Glasgrenzen und Streuereignisse ab dem ersten Treffer (1–16). Tiefe 1 liefert direkte Beleuchtung auf undurchsichtigen Flächen; höhere Werte erlauben mehr Reflexionen oder Glasdurchgänge und können länger dauern. Für eigene Reflexionen oder Anisotropie die indirekte Beleuchtung ausschalten.", + "render.cpu_path_lighting": "Indirekte Beleuchtung", + "render.cpu_path_optics_reason": "Die Einstellungen bleiben erhalten. Für eigene Reflexionen oder Anisotropie die indirekte Beleuchtung ausschalten." + }, + "en": { + "render.cpu_glass_enable_path": "Enable Indirect lighting", + "render.cpu_path_depth": "Path depth", + "render.cpu_path_help": "Adds light bouncing between opaque surfaces and through supported Glass shapes. Requires progressive rendering and traced shadows. Path depth counts shaded surfaces, Glass boundaries and scattering events, starting with the first hit (1–16). Depth 1 gives direct lighting on opaque surfaces; higher values allow more bounces or Glass crossings and may take longer. Turn off Indirect lighting to use custom reflections or anisotropy.", + "render.cpu_path_lighting": "Indirect lighting", + "render.cpu_path_optics_reason": "Your settings are kept. Turn off Indirect lighting to use custom reflections or anisotropy." + }, + "he": { + "render.cpu_glass_enable_path": "הפעלת תאורה עקיפה", + "render.cpu_path_depth": "עומק מסלול", + "render.cpu_path_help": "מחשבת אור שמוחזר בין משטחים אטומים ועובר דרך צורות זכוכית נתמכות. נדרשים רינדור הדרגתי וצללים במעקב קרניים. עומק המסלול סופר משטחים מוצללים, גבולות זכוכית ואירועי פיזור החל מהמפגש הראשון (1–16). עומק 1 נותן תאורה ישירה למשטחים אטומים; ערכים גבוהים מאפשרים יותר החזרות או מעברים בזכוכית ועשויים לדרוש יותר זמן. יש לכבות תאורה עקיפה כדי להשתמש בהשתקפויות מותאמות או באנאיזוטרופיה.", + "render.cpu_path_lighting": "תאורה עקיפה", + "render.cpu_path_optics_reason": "ההגדרות שלך נשמרות. יש לכבות תאורה עקיפה כדי להשתמש בהשתקפויות מותאמות או באנאיזוטרופיה." + }, + "ja": { + "render.cpu_glass_enable_path": "間接照明を有効にする", + "render.cpu_path_depth": "パス深度", + "render.cpu_path_help": "不透明な面の間で反射し、対応するガラス形状を通る光を計算します。プログレッシブ描画とレイトレーシングの影が必要です。パス深度は最初の交点から、照明を計算する面、ガラス境界、散乱イベントを数えます(1~16)。深度1は不透明面の直接照明のみです。値を上げると反射やガラスの通過を増やせますが、時間がかかる場合があります。独自の反射設定や異方性を使うには間接照明をオフにしてください。", + "render.cpu_path_lighting": "間接照明", + "render.cpu_path_optics_reason": "設定は保持されます。独自の反射設定や異方性を使うには間接照明をオフにしてください。" + }, + "ko": { + "render.cpu_glass_enable_path": "간접 조명 켜기", + "render.cpu_path_depth": "경로 깊이", + "render.cpu_path_help": "불투명 표면 사이에서 반사되고 지원되는 유리 형상을 통과하는 빛을 계산합니다. 점진적 렌더링과 레이 추적 그림자가 필요합니다. 경로 깊이는 첫 교점부터 조명이 계산되는 표면, 유리 경계 및 산란 이벤트를 셉니다(1–16). 깊이 1은 불투명 표면의 직접 조명만 계산합니다. 값을 높이면 반사나 유리 통과가 늘어나며 시간이 더 걸릴 수 있습니다. 사용자 반사 설정이나 이방성을 사용하려면 간접 조명을 끄세요.", + "render.cpu_path_lighting": "간접 조명", + "render.cpu_path_optics_reason": "설정은 유지됩니다. 사용자 반사 설정이나 이방성을 사용하려면 간접 조명을 끄세요." + }, + "vi": { + "render.cpu_glass_enable_path": "Bật Chiếu sáng gián tiếp", + "render.cpu_path_depth": "Độ sâu đường truyền", + "render.cpu_path_help": "Tính ánh sáng phản xạ giữa các bề mặt đục và truyền qua các hình kính được hỗ trợ. Cần kết xuất lũy tiến và bóng dò tia. Độ sâu đường đi đếm các bề mặt được chiếu sáng, ranh giới kính và các sự kiện tán xạ từ giao điểm đầu tiên (1–16). Độ sâu 1 chỉ chiếu sáng trực tiếp bề mặt đục; giá trị cao hơn cho phép thêm lần phản xạ hoặc xuyên kính và có thể lâu hơn. Tắt Chiếu sáng gián tiếp để dùng phản xạ tùy chỉnh hoặc dị hướng.", + "render.cpu_path_lighting": "Chiếu sáng gián tiếp", + "render.cpu_path_optics_reason": "Các thiết lập được giữ nguyên. Tắt Chiếu sáng gián tiếp để dùng phản xạ tùy chỉnh hoặc dị hướng." + }, + "zh": { + "render.cpu_glass_enable_path": "启用间接照明", + "render.cpu_path_depth": "路径深度", + "render.cpu_path_help": "计算在不透明表面之间反射并穿过受支持玻璃形状的光。需要渐进渲染和光线追踪阴影。路径深度从首次相交开始计算着色表面、玻璃边界和散射事件(1–16)。深度 1 只计算不透明表面的直接照明;更高的值允许更多反射或玻璃穿越,也可能耗时更长。使用自定义反射或各向异性时,请关闭间接照明。", + "render.cpu_path_lighting": "间接照明", + "render.cpu_path_optics_reason": "设置会保留。使用自定义反射或各向异性时,请关闭间接照明。" + } +} diff --git a/assets/locales/pending/cpu-quality-budgets.json b/assets/locales/pending/cpu-quality-budgets.json new file mode 100644 index 000000000..d6af93f2a --- /dev/null +++ b/assets/locales/pending/cpu-quality-budgets.json @@ -0,0 +1,42 @@ +{ + "en": { + "render.cpu_quality_budget_help": "Changes size, production sample cap, seed and CPU resource profile. Camera, lens, lighting, GI depth and effects are kept.", + "render.cpu_quality_progressive_required": "Enable progressive sampling below before choosing a CPU budget.", + "render.cpu_quality_summary": "{width} × {height} · {samples} sample cap · seed {seed} · {profile}" + }, + "ar": { + "render.cpu_quality_budget_help": "يغير الحجم وحد عينات الإنتاج والبذرة وملف موارد CPU. تُحفظ الكاميرا والعدسة والإضاءة وعمق GI والتأثيرات.", + "render.cpu_quality_progressive_required": "فعّل أخذ العينات التدريجي أدناه قبل اختيار ميزانية CPU.", + "render.cpu_quality_summary": "{width} × {height} · حد العينات {samples} · البذرة {seed} · {profile}" + }, + "de": { + "render.cpu_quality_budget_help": "Ändert Größe, Obergrenze der Produktionssamples, Startwert und CPU-Ressourcenprofil. Kamera, Objektiv, Beleuchtung, GI-Tiefe und Effekte bleiben erhalten.", + "render.cpu_quality_progressive_required": "Aktiviere unten progressive Samples, bevor du ein CPU-Budget auswählst.", + "render.cpu_quality_summary": "{width} × {height} · Sample-Grenze {samples} · Startwert {seed} · {profile}" + }, + "he": { + "render.cpu_quality_budget_help": "משנה גודל, תקרת דגימות הפקה, זרע ופרופיל משאבי CPU. המצלמה, העדשה, התאורה, עומק GI והאפקטים נשמרים.", + "render.cpu_quality_progressive_required": "יש להפעיל דגימה מתקדמת למטה לפני בחירת תקציב CPU.", + "render.cpu_quality_summary": "{width} × {height} · תקרת דגימות {samples} · זרע {seed} · {profile}" + }, + "ja": { + "render.cpu_quality_budget_help": "サイズ、本番サンプル数の上限、シード、CPUリソースプロファイルを変更します。カメラ、レンズ、照明、GI深度、エフェクトは維持されます。", + "render.cpu_quality_progressive_required": "CPU予算を選ぶ前に、下でプログレッシブサンプリングを有効にしてください。", + "render.cpu_quality_summary": "{width} × {height} · サンプル上限 {samples} · シード {seed} · {profile}" + }, + "ko": { + "render.cpu_quality_budget_help": "크기, 제작 샘플 상한, 시드와 CPU 리소스 프로필을 변경합니다. 카메라, 렌즈, 조명, GI 깊이와 효과는 유지됩니다.", + "render.cpu_quality_progressive_required": "CPU 예산을 선택하기 전에 아래에서 점진적 샘플링을 활성화하세요.", + "render.cpu_quality_summary": "{width} × {height} · 샘플 상한 {samples} · 시드 {seed} · {profile}" + }, + "vi": { + "render.cpu_quality_budget_help": "Thay đổi kích thước, trần mẫu sản xuất, hạt giống và cấu hình tài nguyên CPU. Giữ nguyên máy ảnh, ống kính, ánh sáng, độ sâu GI và hiệu ứng.", + "render.cpu_quality_progressive_required": "Bật lấy mẫu tiến dần bên dưới trước khi chọn ngân sách CPU.", + "render.cpu_quality_summary": "{width} × {height} · trần mẫu {samples} · hạt giống {seed} · {profile}" + }, + "zh": { + "render.cpu_quality_budget_help": "更改尺寸、正式样本上限、种子和CPU资源配置。保留相机、镜头、照明、GI深度和效果。", + "render.cpu_quality_progressive_required": "选择CPU预算前,请先在下方启用渐进采样。", + "render.cpu_quality_summary": "{width} × {height} · 样本上限 {samples} · 种子 {seed} · {profile}" + } +} diff --git a/assets/locales/pending/cpu-saved-optics.json b/assets/locales/pending/cpu-saved-optics.json new file mode 100644 index 000000000..8d50aeeda --- /dev/null +++ b/assets/locales/pending/cpu-saved-optics.json @@ -0,0 +1,82 @@ +{ + "ar": { + "render.appearance_editor.discard_saved_edit": "تجاهل التعديلات البصرية غير المحفوظة", + "render.cpu_subsurface_denoise_reason": "يتطلب التشتت داخل الزجاج على CPU إيقاف إزالة الضجيج. تبقى إعداداتك محفوظة.", + "render.cpu_subsurface_help": "يغيّر التشتت اتجاه الضوء داخل الزجاج المغلق. تتطلب المعدلات الموجبة إضاءة غير مباشرة مع إيقاف إزالة الضجيج. المعدل هو عدد التصادمات لكل مم؛ لا يضيف الصفر أي تشتت. يفضّل انحياز الاتجاه الموجب الأمام، والسالب الخلف.", + "render.material_cpu_glass_only": "تتطلب خرائط ملفات الصور المؤقتة GPU. يمكن لـCPU استخدام خرائط الأسطح المضمنة المحفوظة.", + "render.material_cpu_optics_limits": "شغّل الإضاءة غير المباشرة لأشكال الزجاج المغلقة المدعومة والتداخل المتحقق منه والتشتت داخل الزجاج. يمكن للصفائح الرقيقة تمرير الضوء للظلال. وإلا فاستخدم صفيحة مستوية أو صندوقًا محاذيًا للمحاور. تظل الأشكال المتلامسة والظلال النافذة عبر الزجاج المغلق غير مدعومة. تبقى قيمك محفوظة.", + "render.material_cpu_saved_runtime_conflict": "لا يمكن الجمع بين البصريات المحفوظة على CPU والارتباطات البصرية المؤقتة السابقة. احفظ البصريات التي راجعتها أو أزل الارتباط المؤقت المتعارض.", + "render.material_raytrace_required": "يتطلب الزجاج الفيزيائي تتبع الأشعة على CPU أو تتبع المسارات على GPU.", + "render.material_saved_edit_pending": "هذه التعديلات البصرية غير محفوظة. احفظ القيم التي راجعتها، أو أزل التعيين المحفوظ، أو تجاهل التعديلات. لا يمكن للارتباطات المؤقتة السابقة والمؤثرات غير المدعومة تجاوز الهدف المحفوظ." + }, + "de": { + "render.appearance_editor.discard_saved_edit": "Ungespeicherte Optikänderungen verwerfen", + "render.cpu_subsurface_denoise_reason": "Streuung im Glas auf der CPU benötigt ausgeschaltete Rauschreduzierung. Die Einstellungen bleiben erhalten.", + "render.cpu_subsurface_help": "Streuung lenkt Licht im Inneren geschlossenen Glases um. Positive Raten benötigen indirekte Beleuchtung ohne Rauschreduzierung. Die Rate zählt Kollisionen pro mm; 0 fügt keine Streuung hinzu. Positive Richtungswerte bevorzugen vorwärts, negative rückwärts.", + "render.material_cpu_glass_only": "Temporäre Bilddatei-Karten benötigen die GPU. Die CPU kann gespeicherte integrierte Oberflächenkarten verwenden.", + "render.material_cpu_optics_limits": "Indirekte Beleuchtung für unterstützte geschlossene Glasformen, geprüfte Verschachtelung und Streuung im Inneren einschalten. Dünne Scheiben können Licht für Schatten durchlassen. Sonst eine ebene Scheibe oder achsenparallele Box verwenden. Berührende Formen und durch geschlossenes Glas übertragene Schatten werden weiterhin nicht unterstützt. Die Werte bleiben erhalten.", + "render.material_cpu_saved_runtime_conflict": "Gespeicherte CPU-Optik kann nicht mit temporären optischen Bindungen kombiniert werden. Geprüfte Optik speichern oder die temporäre Bindung entfernen.", + "render.material_raytrace_required": "Physikalisches Glas benötigt CPU-Raytracing oder GPU-Pathtracing.", + "render.material_saved_edit_pending": "Diese Optikänderungen sind ungespeichert. Geprüfte Werte speichern, die gespeicherte Zuordnung entfernen oder Änderungen verwerfen. Temporäre Bindungen und nicht unterstützte Effekte können das gespeicherte Ziel nicht überschreiben." + }, + "en": { + "render.appearance_editor.discard_saved_edit": "Discard unsaved optical edits", + "render.cpu_subsurface_denoise_reason": "CPU subsurface scattering needs Denoise off. Your settings are kept.", + "render.cpu_subsurface_help": "Scattering redirects light inside closed Glass. Positive rates need Indirect lighting with Denoise off. The rate is collisions per mm; 0 adds no scattering. Positive phase bias favors forward directions; negative favors backward.", + "render.material_cpu_glass_only": "Temporary image-file maps require GPU. CPU can use saved built-in surface maps.", + "render.material_cpu_optics_limits": "Turn on Indirect lighting for supported closed Glass shapes, certified nesting and subsurface scattering. Thin sheets can pass shadows. Otherwise use a planar sheet or axis-aligned box. Touching shapes and transmitted shadows through closed Glass remain unsupported. Your values are kept.", + "render.material_cpu_saved_runtime_conflict": "Saved CPU optics cannot combine with legacy temporary optical bindings. Save the reviewed optics or remove the conflicting temporary binding.", + "render.material_raytrace_required": "Physical Glass requires CPU ray tracing or GPU path tracing.", + "render.material_saved_edit_pending": "These optical edits are unsaved. Save reviewed values, remove the saved assignment, or discard the edits. Legacy temporary bindings and unsupported effects cannot override the saved target." + }, + "he": { + "render.appearance_editor.discard_saved_edit": "ביטול שינויים אופטיים שלא נשמרו", + "render.cpu_subsurface_denoise_reason": "פיזור בתוך זכוכית ב־CPU דורש הסרת רעש כבויה. ההגדרות נשמרות.", + "render.cpu_subsurface_help": "פיזור משנה את כיוון האור בתוך זכוכית סגורה. קצב חיובי דורש תאורה עקיפה והסרת רעש כבויה. הקצב הוא מספר התנגשויות למ״מ; 0 אינו מוסיף פיזור. הטיית כיוון חיובית מעדיפה קדימה, ושלילית אחורה.", + "render.material_cpu_glass_only": "מפות זמניות מקובצי תמונה דורשות GPU. ב־CPU אפשר להשתמש במפות משטח מובנות שנשמרו.", + "render.material_cpu_optics_limits": "יש להפעיל תאורה עקיפה לצורות זכוכית סגורות נתמכות, לקינון שנבדק ולפיזור בתוך הזכוכית. יריעות דקות יכולות להעביר אור לצללים. אחרת יש להשתמש ביריעה מישורית או בתיבה מקבילה לצירים. צורות נוגעות וצללים העוברים בזכוכית סגורה עדיין אינם נתמכים. הערכים נשמרים.", + "render.material_cpu_saved_runtime_conflict": "אי אפשר לשלב הגדרות אופטיות שמורות ב־CPU עם הקישורים האופטיים הזמניים הישנים. יש לשמור את ההגדרות שנבדקו או להסיר את הקישור הזמני המתנגש.", + "render.material_raytrace_required": "זכוכית פיזיקלית דורשת עקיבת קרניים ב־CPU או עקיבת נתיבים ב־GPU.", + "render.material_saved_edit_pending": "השינויים האופטיים האלה לא נשמרו. יש לשמור את הערכים שנבדקו, להסיר את ההקצאה השמורה או לבטל את השינויים. קישורים זמניים ישנים ואפקטים שאינם נתמכים אינם יכולים לעקוף את היעד השמור." + }, + "ja": { + "render.appearance_editor.discard_saved_edit": "未保存の光学設定の変更を破棄", + "render.cpu_subsurface_denoise_reason": "CPUの内部散乱ではノイズ除去をオフにしてください。設定値は保持されます。", + "render.cpu_subsurface_help": "散乱は閉じたガラスの内部で光の方向を変えます。正の値には間接照明を使い、ノイズ除去をオフにします。率は1mmあたりの衝突回数です。0では散乱を加えません。方向の偏りが正なら前方、負なら後方を優先します。", + "render.material_cpu_glass_only": "一時画像ファイルのマップにはGPUが必要です。CPUでは保存済みの組み込み表面マップを使用できます。", + "render.material_cpu_optics_limits": "対応する閉じたガラス形状、検証済みの入れ子形状、内部散乱には間接照明をオンにしてください。薄いシートは影に光を透過できます。それ以外は平面シートか軸平行の箱を使います。接触する形状と閉じたガラスを通る透過影には未対応です。値は保持されます。", + "render.material_cpu_saved_runtime_conflict": "保存済みCPU光学設定と一時的な光学割り当ては併用できません。確認した設定を保存するか、競合する一時割り当てを削除してください。", + "render.material_raytrace_required": "物理ガラスにはCPUレイトレーシングまたはGPUパストレーシングが必要です。", + "render.material_saved_edit_pending": "光学設定の変更は未保存です。確認した値を保存するか、保存済み割り当てを削除するか、変更を破棄してください。一時割り当てや未対応の効果で保存済み対象を上書きできません。" + }, + "ko": { + "render.appearance_editor.discard_saved_edit": "저장하지 않은 광학 편집 버리기", + "render.cpu_subsurface_denoise_reason": "CPU 내부 산란을 사용하려면 노이즈 제거를 끄세요. 설정은 유지됩니다.", + "render.cpu_subsurface_help": "산란은 닫힌 유리 내부에서 빛의 방향을 바꿉니다. 양수 비율에는 간접광을 사용하고 노이즈 제거를 끄세요. 비율은 mm당 충돌 횟수이며, 0은 산란을 추가하지 않습니다. 방향 편향이 양수이면 전방, 음수이면 후방을 선호합니다.", + "render.material_cpu_glass_only": "임시 이미지 파일 맵에는 GPU가 필요합니다. CPU는 저장된 내장 표면 맵을 사용할 수 있습니다.", + "render.material_cpu_optics_limits": "지원되는 닫힌 유리 형상, 검증된 중첩 및 내부 산란에는 간접 조명을 켜세요. 얇은 시트는 그림자에 빛을 통과시킬 수 있습니다. 그 외에는 평면 시트나 축 정렬 상자를 사용하세요. 서로 닿는 형상과 닫힌 유리를 통과하는 투과 그림자는 아직 지원하지 않습니다. 값은 유지됩니다.", + "render.material_cpu_saved_runtime_conflict": "저장된 CPU 광학 설정은 임시 광학 바인딩과 함께 사용할 수 없습니다. 검토한 설정을 저장하거나 충돌하는 임시 바인딩을 제거하세요.", + "render.material_raytrace_required": "물리 유리에는 CPU 레이 트레이싱이나 GPU 패스 트레이싱이 필요합니다.", + "render.material_saved_edit_pending": "광학 편집을 아직 저장하지 않았습니다. 검토한 값을 저장하거나 저장된 할당을 제거하거나 편집을 버리세요. 임시 바인딩과 지원하지 않는 효과는 저장된 대상을 덮어쓸 수 없습니다." + }, + "vi": { + "render.appearance_editor.discard_saved_edit": "Hủy chỉnh sửa quang học chưa lưu", + "render.cpu_subsurface_denoise_reason": "Tán xạ bên trong kính trên CPU cần tắt Khử nhiễu. Các cài đặt được giữ nguyên.", + "render.cpu_subsurface_help": "Tán xạ đổi hướng ánh sáng bên trong kính kín. Tốc độ dương cần Chiếu sáng gián tiếp và tắt Khử nhiễu. Tốc độ là số va chạm mỗi mm; 0 không thêm tán xạ. Độ lệch hướng dương ưu tiên phía trước, âm ưu tiên phía sau.", + "render.material_cpu_glass_only": "Bản đồ từ tệp ảnh tạm thời yêu cầu GPU. CPU có thể dùng bản đồ bề mặt tích hợp đã lưu.", + "render.material_cpu_optics_limits": "Bật Chiếu sáng gián tiếp cho hình kính kín được hỗ trợ, cấu trúc lồng nhau đã kiểm chứng và tán xạ bên trong kính. Tấm mỏng có thể truyền ánh sáng cho bóng. Nếu không, dùng tấm phẳng hoặc hộp thẳng theo trục. Chưa hỗ trợ hình chạm nhau và bóng truyền qua kính kín. Các giá trị được giữ nguyên.", + "render.material_cpu_saved_runtime_conflict": "Không thể kết hợp quang học CPU đã lưu với các liên kết quang học tạm thời kiểu cũ. Hãy lưu quang học đã xem xét hoặc xóa liên kết tạm thời xung đột.", + "render.material_raytrace_required": "Kính vật lý yêu cầu dò tia trên CPU hoặc dò đường đi trên GPU.", + "render.material_saved_edit_pending": "Các chỉnh sửa quang học này chưa được lưu. Hãy lưu các giá trị đã xem xét, xóa phép gán đã lưu hoặc hủy chỉnh sửa. Liên kết tạm thời kiểu cũ và hiệu ứng chưa được hỗ trợ không thể ghi đè đích đã lưu." + }, + "zh": { + "render.appearance_editor.discard_saved_edit": "放弃未保存的光学编辑", + "render.cpu_subsurface_denoise_reason": "CPU 内部散射需要关闭降噪。设置会保留。", + "render.cpu_subsurface_help": "散射会改变闭合玻璃内部的光线方向。正散射率需要开启间接光照并关闭降噪。散射率表示每毫米的碰撞次数;0 不增加散射。方向偏置为正时偏向前方,为负时偏向后方。", + "render.material_cpu_glass_only": "临时图像文件贴图需要GPU。CPU可以使用已保存的内置表面贴图。", + "render.material_cpu_optics_limits": "启用间接光照可使用受支持的闭合玻璃形状、经验证的嵌套结构及内部散射。薄片可以透射阴影。否则请使用平面薄片或轴对齐盒体。仍不支持相互接触的形状及穿过闭合玻璃的透射阴影。设置值会保留。", + "render.material_cpu_saved_runtime_conflict": "已保存的CPU光学设置不能与临时光学绑定组合。请保存已审阅的设置或移除冲突的临时绑定。", + "render.material_raytrace_required": "物理玻璃需要CPU光线追踪或GPU路径追踪。", + "render.material_saved_edit_pending": "这些光学编辑尚未保存。请保存已审阅的值、移除已保存的分配或放弃编辑。临时绑定和不支持的效果不能覆盖已保存的目标。" + } +} diff --git a/assets/locales/pending/cpu-saved-surface-maps.json b/assets/locales/pending/cpu-saved-surface-maps.json new file mode 100644 index 000000000..d9c1e1d6a --- /dev/null +++ b/assets/locales/pending/cpu-saved-surface-maps.json @@ -0,0 +1,32 @@ +{ + "ar": { + "render.cpu_maps_saved_help": "يمكن لتصيير CPU استخدام خرائط الأسطح المعتمة المحفوظة: اختر سطحًا هنا ثم احفظ خرائطه في اللقطة. مع الإضاءة غير المباشرة، يمكن استخدام الزجاج في جسم آخر؛ لا يمكن استخدام الزجاج في الجسم ذي الخرائط. يجب إيقاف الانعكاسات المختارة والتباين الاتجاهي والتأثيرات الإجرائية. تتطلب مسارات ملفات الخرائط المؤقتة GPU." + }, + "de": { + "render.cpu_maps_saved_help": "CPU-Renderings können gespeicherte Karten undurchsichtiger Flächen verwenden: Oberfläche wählen und die Karten in der Aufnahme speichern. Mit indirekter Beleuchtung darf ein anderer Körper Glas verwenden; der Körper mit Karten darf kein Glas sein. Ausgewählte Reflexionen, Anisotropie und prozedurale Effekte ausschalten. Temporäre Kartendateipfade verwenden die GPU." + }, + "en": { + "render.cpu_maps_saved_help": "CPU renders can use saved opaque maps: choose a surface here, then Save maps to shot. With Indirect lighting, Glass can be on another body; a mapped body cannot use Glass. Selected reflections, anisotropy and procedural surface effects must be off. Temporary map file paths use GPU." + }, + "es": { + "render.cpu_maps_saved_help": "Los renders CPU pueden usar mapas opacos guardados: elige una superficie y guarda sus mapas en la toma. Con Iluminación indirecta, otro cuerpo puede usar Vidrio; el cuerpo con mapas no puede usar Vidrio. Desactiva los reflejos seleccionados, la anisotropía y los efectos procedurales. Las rutas temporales de archivos de mapas usan GPU." + }, + "fr": { + "render.cpu_maps_saved_help": "Le rendu CPU accepte les cartes opaques enregistrées : choisissez une surface, puis enregistrez ses cartes dans la vue. Avec l’éclairage indirect, un autre corps peut utiliser Verre ; le corps avec les cartes ne le peut pas. Désactivez les réflexions sélectionnées, l’anisotropie et les effets procéduraux. Les fichiers temporaires de cartes utilisent le GPU." + }, + "he": { + "render.cpu_maps_saved_help": "רינדור CPU יכול להשתמש במפות אטומות שמורות: בחרו כאן משטח ושמרו את המפות בתצלום. עם תאורה עקיפה, גוף אחר יכול להשתמש בזכוכית; הגוף בעל המפות אינו יכול להשתמש בזכוכית. יש לכבות החזרות שנבחרו, אנאיזוטרופיה ואפקטים פרוצדורליים. נתיבים זמניים לקובצי מפות משתמשים ב־GPU." + }, + "ja": { + "render.cpu_maps_saved_help": "CPUレンダリングは保存された不透明サーフェスマップを使えます。サーフェスを選び、ショットにマップを保存してください。間接光を使う場合、別のボディにはガラスを使えますが、マップを持つボディには使えません。選択した反射、異方性、プロシージャル効果はオフにします。一時的なマップファイルにはGPUを使います。" + }, + "ko": { + "render.cpu_maps_saved_help": "CPU 렌더링은 저장한 불투명 표면 맵을 사용할 수 있습니다. 표면을 선택하고 샷에 맵을 저장하세요. 간접광을 사용하면 다른 바디에 유리를 사용할 수 있지만, 맵이 있는 바디에는 유리를 사용할 수 없습니다. 선택 반사, 비등방성 및 절차적 효과는 끄세요. 임시 맵 파일 경로는 GPU를 사용합니다." + }, + "vi": { + "render.cpu_maps_saved_help": "Kết xuất CPU hỗ trợ bản đồ bề mặt đục đã lưu: chọn bề mặt rồi lưu bản đồ vào ảnh chụp. Với chiếu sáng gián tiếp, thân khác có thể dùng kính; thân có bản đồ không thể dùng kính. Tắt phản xạ được chọn, dị hướng và hiệu ứng thủ tục. Đường dẫn tạm tới tệp bản đồ dùng GPU." + }, + "zh": { + "render.cpu_maps_saved_help": "CPU 渲染可使用已保存的不透明表面贴图:在此选择表面,再将贴图保存到镜头。使用间接光照时,其他实体可以使用玻璃;带有贴图的实体不能使用玻璃。请关闭选定的反射、各向异性和程序化表面效果。临时贴图文件路径使用 GPU。" + } +} diff --git a/assets/locales/pending/cpu-spatial-denoise.json b/assets/locales/pending/cpu-spatial-denoise.json new file mode 100644 index 000000000..eb76aaf24 --- /dev/null +++ b/assets/locales/pending/cpu-spatial-denoise.json @@ -0,0 +1,26 @@ +{ + "ar": { + "render.cpu_denoise_help": "يقلل التشويش في كل تحديث للصورة. قد ينعّم التفاصيل الدقيقة وحواف عمق المجال. يبقى EXR الخام دون تغيير. تستخدم تعديلات الصورة المكتملة صورتها الخام ولا تطبّق تقليل التشويش مرة أخرى." + }, + "de": { + "render.cpu_denoise_help": "Verringert das Rauschen bei jeder Bildaktualisierung. Feine Details und Übergänge der Tiefenschärfe können weicher werden. Die EXR-Rohdaten bleiben unverändert. Nachträgliche Anpassungen eines fertigen Bildes verwenden dessen Rohbild und wenden die Rauschreduzierung nicht erneut an." + }, + "en": { + "render.cpu_denoise_help": "Reduces noise in every image update. It may soften fine detail and depth-of-field edges. Raw EXR is unchanged. Adjusting a completed image uses its raw image and does not apply noise reduction again." + }, + "he": { + "render.cpu_denoise_help": "מפחיתה רעש בכל עדכון תמונה. היא עלולה לרכך פרטים עדינים וקצוות של עומק שדה. קובץ EXR הגולמי אינו משתנה. התאמות של תמונה שהושלמה משתמשות בתמונה הגולמית שלה ואינן מחילות שוב הפחתת רעש." + }, + "ja": { + "render.cpu_denoise_help": "画像が更新されるたびにノイズを減らします。細部や被写界深度によるぼけの境界が柔らかくなる場合があります。RAW EXRは変更されません。完成画像の調整にはそのRAW画像を使用し、ノイズ低減は再適用しません。" + }, + "ko": { + "render.cpu_denoise_help": "이미지가 갱신될 때마다 노이즈를 줄입니다. 미세한 디테일과 피사계 심도 경계가 부드러워질 수 있습니다. 원본 EXR은 바뀌지 않습니다. 완성된 이미지를 조정할 때는 해당 원본 이미지를 사용하며 노이즈 감소를 다시 적용하지 않습니다." + }, + "vi": { + "render.cpu_denoise_help": "Giảm nhiễu mỗi khi ảnh được cập nhật. Có thể làm mềm chi tiết nhỏ và biên vùng mờ do độ sâu trường ảnh. EXR thô không thay đổi. Khi điều chỉnh ảnh đã hoàn tất, hệ thống dùng ảnh thô của ảnh đó và không áp dụng giảm nhiễu lần nữa." + }, + "zh": { + "render.cpu_denoise_help": "每次图像更新时减少噪点,可能使细节和景深模糊边缘变柔。原始EXR保持不变。调整已完成的图像时使用其原始图像,不会再次降噪。" + } +} diff --git a/assets/locales/pending/cpu-studio-authoring.json b/assets/locales/pending/cpu-studio-authoring.json new file mode 100644 index 000000000..36105ec0c --- /dev/null +++ b/assets/locales/pending/cpu-studio-authoring.json @@ -0,0 +1,50 @@ +{ + "ar": { + "render.cpu_studio_enable": "تفعيل الإضاءة غير المباشرة لهذا التوزيع", + "render.cpu_studio_enable_apply": "تفعيل الإضاءة غير المباشرة وتطبيقها", + "render.cpu_studio_indirect_help": "يحتاج توزيع الشمس هذا إلى إضاءة غير مباشرة بعمق 8 وظلال متتبعة وعينة كاميرا واحدة لكل مرور. إذا كان التصيير التدريجي معطلاً، يبدأ بـ 16 عينة لكل بكسل وبذرة 0. تُحفظ الإعدادات التدريجية الحالية وملف الموارد. تمنع الإعدادات غير المتوافقة التطبيق دون تغييرها.", + "render.cpu_studio_radiance_limit": "سطوع المصدر المساحي في هذا التوزيع هو {radiance}، ويتجاوز حد CPU البالغ 64. تُحفظ الإضاءة المؤلَّفة؛ اختر توزيعاً آخر أو GPU." + }, + "de": { + "render.cpu_studio_enable": "Indirekte Beleuchtung für dieses Lichtset aktivieren", + "render.cpu_studio_enable_apply": "Indirekte Beleuchtung aktivieren und anwenden", + "render.cpu_studio_indirect_help": "Dieses Sonnen-Lichtset benötigt indirekte Beleuchtung mit Tiefe 8, verfolgte Schatten und eine Kamerastichprobe pro Durchlauf. Ist progressives Rendern ausgeschaltet, beginnt es mit 16 Stichproben pro Pixel und Startwert 0. Vorhandene progressive Einstellungen und das Ressourcenprofil bleiben erhalten. Unvereinbare Einstellungen verhindern die Anwendung, ohne sie zu ändern.", + "render.cpu_studio_radiance_limit": "Dieses Lichtset hat eine Flächenstrahldichte von {radiance}, über der CPU-Grenze von 64. Die vorgegebene Beleuchtung bleibt erhalten; wählen Sie ein anderes Lichtset oder GPU." + }, + "en": { + "render.cpu_studio_enable": "Enable indirect lighting for this rig", + "render.cpu_studio_enable_apply": "Enable indirect lighting and apply", + "render.cpu_studio_indirect_help": "This Sun rig needs indirect lighting at depth 8, traced shadows and one camera sample per pass. If progressive rendering is off, it starts at 16 samples per pixel with seed 0. Existing progressive settings and the resource profile are kept. Incompatible settings stop the apply without changing them.", + "render.cpu_studio_radiance_limit": "This rig has area radiance {radiance}, above the CPU limit of 64. Its authored lighting is kept; choose another rig or GPU." + }, + "he": { + "render.cpu_studio_enable": "הפעלת תאורה עקיפה עבור מערך זה", + "render.cpu_studio_enable_apply": "הפעלת תאורה עקיפה והחלה", + "render.cpu_studio_indirect_help": "מערך השמש הזה דורש תאורה עקיפה בעומק 8, צללים מחושבים ודגימת מצלמה אחת בכל מעבר. אם רינדור הדרגתי כבוי, הוא מתחיל ב־16 דגימות לפיקסל עם זרע 0. הגדרות הדרגתיות קיימות ופרופיל המשאבים נשמרים. הגדרות שאינן תואמות עוצרות את ההחלה בלי לשנותן.", + "render.cpu_studio_radiance_limit": "עוצמת מקור השטח במערך זה היא {radiance}, מעל מגבלת CPU של 64. התאורה המקורית נשמרת; בחרו מערך אחר או GPU." + }, + "ja": { + "render.cpu_studio_enable": "このリグで間接照明を有効にする", + "render.cpu_studio_enable_apply": "間接照明を有効にして適用", + "render.cpu_studio_indirect_help": "この太陽リグには深度8の間接照明、追跡した影、パスごとに1つのカメラサンプルが必要です。プログレッシブ描画がオフなら、ピクセルごと16サンプル、シード0で開始します。既存のプログレッシブ設定とリソースプロファイルは維持します。非対応の設定がある場合は変更せず適用を中止します。", + "render.cpu_studio_radiance_limit": "このリグの面光源の放射輝度は{radiance}で、CPU上限64を超えます。作成された照明は維持します。別のリグかGPUを選んでください。" + }, + "ko": { + "render.cpu_studio_enable": "이 리그의 간접 조명 켜기", + "render.cpu_studio_enable_apply": "간접 조명을 켜고 적용", + "render.cpu_studio_indirect_help": "이 태양 리그에는 깊이 8의 간접 조명, 추적된 그림자, 패스당 카메라 샘플 1개가 필요합니다. 점진적 렌더링이 꺼져 있으면 픽셀당 샘플 16개와 시드 0으로 시작합니다. 기존 점진적 설정과 리소스 프로필은 유지됩니다. 호환되지 않는 설정은 변경하지 않고 적용을 중단합니다.", + "render.cpu_studio_radiance_limit": "이 리그의 면 광원 방사 휘도 {radiance}은(는) CPU 한도 64를 넘습니다. 작성된 조명은 유지됩니다. 다른 리그나 GPU를 선택하세요." + }, + "vi": { + "render.cpu_studio_enable": "Bật chiếu sáng gián tiếp cho bộ đèn này", + "render.cpu_studio_enable_apply": "Bật chiếu sáng gián tiếp và áp dụng", + "render.cpu_studio_indirect_help": "Bộ đèn Mặt Trời này cần chiếu sáng gián tiếp với độ sâu 8, bóng được truy vết và một mẫu máy ảnh mỗi lượt. Nếu kết xuất tăng dần đang tắt, bắt đầu với 16 mẫu mỗi điểm ảnh và hạt giống 0. Giữ nguyên thiết lập tăng dần và hồ sơ tài nguyên hiện có. Thiết lập không tương thích sẽ ngăn áp dụng mà không thay đổi chúng.", + "render.cpu_studio_radiance_limit": "Độ chói bức xạ đèn diện tích của bộ này là {radiance}, vượt giới hạn CPU 64. Giữ nguyên ánh sáng đã tạo; hãy chọn bộ đèn khác hoặc GPU." + }, + "zh": { + "render.cpu_studio_enable": "为此灯组启用间接光照", + "render.cpu_studio_enable_apply": "启用间接光照并应用", + "render.cpu_studio_indirect_help": "此太阳灯组需要深度为8的间接光照、追踪阴影,以及每轮一个相机采样。如果渐进渲染关闭,则以每像素16个采样和种子0开始。保留现有渐进设置和资源配置。不兼容的设置会阻止应用,且不会被更改。", + "render.cpu_studio_radiance_limit": "此灯组的面光源辐射亮度为{radiance},超过CPU上限64。保留原有灯光,请选择其他灯组或GPU。" + } +} diff --git a/assets/locales/pending/cpu-sun-sky.json b/assets/locales/pending/cpu-sun-sky.json new file mode 100644 index 000000000..8fa52facb --- /dev/null +++ b/assets/locales/pending/cpu-sun-sky.json @@ -0,0 +1,66 @@ +{ + "ar": { + "render.cpu_celestial_adopt": "تتبع الأشعة على المعالج مع إضاءة غير مباشرة · عمق المسار {depth} · {spp} عينة لكل بكسل · ظلال متتبعة · بذرة {seed} · عينة أولية واحدة", + "render.cpu_celestial_adopt_label": "تتبع الأشعة على المعالج مع إضاءة غير مباشرة", + "render.cpu_celestial_path_required": "تستخدم الشمس المحدودة والسماء المتدرجة الإضاءة غير المباشرة على المعالج.", + "render.cpu_celestial_switch": "اختر تتبع الأشعة على المعالج مع الإضاءة غير المباشرة للاحتفاظ بهذه الشمس أو السماء.", + "render.cpu_celestial_unportable": "أبقِ تتبع المسارات على المعالج الرسومي لإعدادات عينات النفاذ الحالية.", + "render.cpu_sky_bounds": "يجب أن يكون دوران السماء محدودًا ضمن ±1,000,000 راديان، وأن تكون الشدة بين 0 و100." + }, + "de": { + "render.cpu_celestial_adopt": "CPU-Raytracing mit indirekter Beleuchtung · Pfadtiefe {depth} · {spp} SPP · verfolgte Schatten · Seed {seed} · 1 Primärsample", + "render.cpu_celestial_adopt_label": "CPU-Raytracing mit indirekter Beleuchtung", + "render.cpu_celestial_path_required": "Endliche Sonne und Verlaufshimmel verwenden indirekte CPU-Beleuchtung.", + "render.cpu_celestial_switch": "Wähle CPU-Raytracing mit indirekter Beleuchtung, um diese Sonne oder diesen Himmel beizubehalten.", + "render.cpu_celestial_unportable": "Behalte GPU-Pathtracing für die aktuellen Transmissions-Sample-Einstellungen bei.", + "render.cpu_sky_bounds": "Die Himmelsrotation muss endlich innerhalb ±1.000.000 Radiant liegen; die Intensität muss 0–100 sein." + }, + "en": { + "render.cpu_celestial_adopt": "CPU ray tracing with indirect lighting · path depth {depth} · {spp} SPP · traced shadows · seed {seed} · 1 primary sample", + "render.cpu_celestial_adopt_label": "CPU ray tracing with indirect lighting", + "render.cpu_celestial_path_required": "Finite Sun and gradient Sky use CPU indirect lighting.", + "render.cpu_celestial_switch": "Choose CPU ray tracing with indirect lighting to keep this Sun or Sky.", + "render.cpu_celestial_unportable": "Keep GPU path tracing for the current transmission sample settings.", + "render.cpu_sky_bounds": "Sky rotation must be finite within ±1,000,000 radians; intensity must be 0–100." + }, + "he": { + "render.cpu_celestial_adopt": "מעקב קרניים במעבד עם תאורה עקיפה · עומק מסלול {depth} · {spp} דגימות לפיקסל · צללים במעקב · זרע {seed} · דגימה ראשית אחת", + "render.cpu_celestial_adopt_label": "מעקב קרניים במעבד עם תאורה עקיפה", + "render.cpu_celestial_path_required": "שמש בעלת גודל סופי ושמיים מדורגים משתמשים בתאורה עקיפה במעבד.", + "render.cpu_celestial_switch": "כדי לשמור על השמש או השמיים האלה, יש לבחור מעקב קרניים במעבד עם תאורה עקיפה.", + "render.cpu_celestial_unportable": "יש לשמור על מעקב מסלולים במעבד הגרפי עבור הגדרות דגימות ההעברה הנוכחיות.", + "render.cpu_sky_bounds": "סיבוב השמיים חייב להיות סופי בטווח ±1,000,000 רדיאנים, והעוצמה חייבת להיות בטווח 0–100." + }, + "ja": { + "render.cpu_celestial_adopt": "間接照明付き CPU レイトレーシング · パス深度 {depth} · {spp} SPP · 追跡シャドウ · シード {seed} · プライマリサンプル1個", + "render.cpu_celestial_adopt_label": "間接照明付き CPU レイトレーシング", + "render.cpu_celestial_path_required": "有限の太陽とグラデーション空は CPU の間接照明を使用します。", + "render.cpu_celestial_switch": "この太陽や空を維持するには、間接照明を使用する CPU レイトレーシングを選択してください。", + "render.cpu_celestial_unportable": "現在の透過サンプル設定には GPU パストレーシングを使用してください。", + "render.cpu_sky_bounds": "空の回転は ±1,000,000 ラジアン以内の有限値、強度は 0~100 にしてください。" + }, + "ko": { + "render.cpu_celestial_adopt": "간접 조명을 사용하는 CPU 레이 트레이싱 · 경로 깊이 {depth} · {spp} SPP · 추적 그림자 · 시드 {seed} · 기본 샘플1개", + "render.cpu_celestial_adopt_label": "간접 조명을 사용하는 CPU 레이 트레이싱", + "render.cpu_celestial_path_required": "유한 태양과 그라데이션 하늘은 CPU 간접 조명을 사용합니다.", + "render.cpu_celestial_switch": "이 태양 또는 하늘을 유지하려면 간접 조명을 사용하는 CPU 레이 트레이싱을 선택하세요.", + "render.cpu_celestial_unportable": "현재 투과 샘플 설정에는 GPU 경로 추적을 유지하세요.", + "render.cpu_sky_bounds": "하늘 회전은 ±1,000,000 라디안 이내의 유한 값이어야 하며 강도는 0~100이어야 합니다." + }, + "vi": { + "render.cpu_celestial_adopt": "Dò tia CPU với chiếu sáng gián tiếp · độ sâu đường đi {depth} · {spp} SPP · bóng đổ dò tia · seed {seed} · 1 mẫu chính", + "render.cpu_celestial_adopt_label": "Dò tia CPU với chiếu sáng gián tiếp", + "render.cpu_celestial_path_required": "Mặt Trời hữu hạn và bầu trời chuyển sắc dùng chiếu sáng gián tiếp CPU.", + "render.cpu_celestial_switch": "Chọn dò tia CPU với chiếu sáng gián tiếp để giữ Mặt Trời hoặc bầu trời này.", + "render.cpu_celestial_unportable": "Giữ dò đường đi GPU cho cài đặt mẫu truyền sáng hiện tại.", + "render.cpu_sky_bounds": "Góc xoay bầu trời phải hữu hạn trong ±1.000.000 radian; cường độ phải từ 0–100." + }, + "zh": { + "render.cpu_celestial_adopt": "CPU 光线追踪与间接照明 · 路径深度 {depth} · {spp} SPP · 追踪阴影 · 种子 {seed} · 1 个主样本", + "render.cpu_celestial_adopt_label": "CPU 光线追踪与间接照明", + "render.cpu_celestial_path_required": "有限太阳和渐变天空使用 CPU 间接照明。", + "render.cpu_celestial_switch": "选择带间接照明的 CPU 光线追踪,以保留此太阳或天空。", + "render.cpu_celestial_unportable": "当前透射采样设置请继续使用 GPU 路径追踪。", + "render.cpu_sky_bounds": "天空旋转必须为 ±1,000,000 弧度内的有限值;强度必须为 0–100。" + } +} diff --git a/assets/locales/pending/cpu-thin-lens.json b/assets/locales/pending/cpu-thin-lens.json new file mode 100644 index 000000000..bf04e50fa --- /dev/null +++ b/assets/locales/pending/cpu-thin-lens.json @@ -0,0 +1,34 @@ +{ + "ar": { + "render.shot_lens_cpu_progressive_reason": "فعّل أخذ العينات التدريجي في قسم «أخذ العينات» قبل تمكين عمق المجال على CPU.", + "render.shot_lens_raytrace_reason": "يتوفر عمق المجال مع تتبع الأشعة على CPU وتتبع المسارات على GPU." + }, + "de": { + "render.shot_lens_cpu_progressive_reason": "Vor der CPU-Schärfentiefe unter Sampling die progressive Abtastung übernehmen.", + "render.shot_lens_raytrace_reason": "Schärfentiefe ist für CPU-Raytracing und GPU-Pathtracing verfügbar." + }, + "en": { + "render.shot_lens_cpu_progressive_reason": "Adopt progressive sampling in Sampling before enabling CPU depth of field.", + "render.shot_lens_raytrace_reason": "Depth of field is available for CPU ray tracing and GPU path tracing." + }, + "he": { + "render.shot_lens_cpu_progressive_reason": "יש להפעיל דגימה הדרגתית בחלונית הדגימה לפני הפעלת עומק שדה ב־CPU.", + "render.shot_lens_raytrace_reason": "עומק שדה זמין בעקיבת קרניים ב־CPU ובעקיבת נתיבים ב־GPU." + }, + "ja": { + "render.shot_lens_cpu_progressive_reason": "CPUの被写界深度を有効にするには、サンプリングでプログレッシブ方式を適用してください。", + "render.shot_lens_raytrace_reason": "被写界深度はCPUレイトレーシングとGPUパストレーシングで利用できます。" + }, + "ko": { + "render.shot_lens_cpu_progressive_reason": "CPU 피사계 심도를 켜기 전에 샘플링에서 점진적 샘플링을 적용하세요.", + "render.shot_lens_raytrace_reason": "피사계 심도는 CPU 레이 트레이싱과 GPU 패스 트레이싱에서 사용할 수 있습니다." + }, + "vi": { + "render.shot_lens_cpu_progressive_reason": "Bật lấy mẫu lũy tiến trong mục Lấy mẫu trước khi bật độ sâu trường ảnh trên CPU.", + "render.shot_lens_raytrace_reason": "Độ sâu trường ảnh khả dụng với dò tia trên CPU và dò đường đi trên GPU." + }, + "zh": { + "render.shot_lens_cpu_progressive_reason": "启用CPU景深前,请在采样中应用渐进式采样。", + "render.shot_lens_raytrace_reason": "CPU光线追踪和GPU路径追踪均支持景深。" + } +} diff --git a/assets/locales/pending/cpu-transparent-png.json b/assets/locales/pending/cpu-transparent-png.json new file mode 100644 index 000000000..dc67f8db8 --- /dev/null +++ b/assets/locales/pending/cpu-transparent-png.json @@ -0,0 +1,26 @@ +{ + "ar": { + "render.cpu_transparent_help": "يزيل PNG الشفاف الخلفية ويحافظ على تغطية الحواف. يجب أن تبقى عتامة الأجسام والأوجه عند 100%." + }, + "de": { + "render.cpu_transparent_help": "Transparentes PNG entfernt den Hintergrund und erhält die Kantenabdeckung. Körper- und Flächendeckkraft müssen 100 % bleiben." + }, + "en": { + "render.cpu_transparent_help": "Transparent PNG removes the background and keeps edge coverage. Body and face opacity must stay at 100%." + }, + "he": { + "render.cpu_transparent_help": "PNG שקוף מסיר את הרקע ושומר על כיסוי הקצוות. אטימות הגופים והפאות חייבת להישאר 100%." + }, + "ja": { + "render.cpu_transparent_help": "透明PNGは背景を除き、輪郭の被覆率を保持します。ボディと面の不透明度は100%にしてください。" + }, + "ko": { + "render.cpu_transparent_help": "투명 PNG는 배경을 제거하고 가장자리 커버리지를 유지합니다. 바디와 면의 불투명도는 100%여야 합니다." + }, + "vi": { + "render.cpu_transparent_help": "PNG trong suốt loại bỏ nền và giữ độ phủ ở biên. Độ đục của thân và mặt phải giữ ở 100%." + }, + "zh": { + "render.cpu_transparent_help": "透明PNG移除背景并保留边缘覆盖率。实体和面的不透明度必须保持100%。" + } +} diff --git a/assets/locales/pending/gpu-directional-lights.json b/assets/locales/pending/gpu-directional-lights.json new file mode 100644 index 000000000..47b98a880 --- /dev/null +++ b/assets/locales/pending/gpu-directional-lights.json @@ -0,0 +1,26 @@ +{ + "ar": { + "render.directional_sun_limit": "تدعم إضاءة GPU ثمانية مصادر ضوء اتجاهية إجمالاً، من بينها شمس واحدة بظلال ناعمة كحد أقصى. انسخ ضوءاً اتجاهياً بظلال حادة لإضافة مصدر بعيد آخر." + }, + "de": { + "render.directional_sun_limit": "Die GPU unterstützt insgesamt acht gerichtete Lichtquellen, darunter höchstens eine weiche Sonne. Dupliziere ein hartes gerichtetes Licht für eine weitere entfernte Quelle." + }, + "en": { + "render.directional_sun_limit": "GPU lighting supports eight directional sources in total, including at most one soft Sun. Duplicate a hard directional light to add another distant source." + }, + "he": { + "render.directional_sun_limit": "תאורת GPU תומכת בשמונה מקורות אור כיווניים בסך הכול, ובהם לכל היותר שמש אחת בעלת צללים רכים. שכפלו אור כיווני בעל צללים חדים כדי להוסיף מקור מרוחק נוסף." + }, + "ja": { + "render.directional_sun_limit": "GPUでは指向性光源を合計8個まで使用でき、柔らかい影の太陽は1個までです。遠方の光源を追加するには、硬い影の指向性ライトを複製してください。" + }, + "ko": { + "render.directional_sun_limit": "GPU는 부드러운 태양 하나를 포함해 방향성 광원을 총 8개까지 지원합니다. 원거리 광원을 추가하려면 선명한 그림자의 방향성 조명을 복제하세요." + }, + "vi": { + "render.directional_sun_limit": "GPU hỗ trợ tổng cộng tám nguồn sáng định hướng, trong đó có tối đa một Mặt trời với bóng mềm. Nhân đôi đèn định hướng có bóng sắc để thêm nguồn sáng ở xa." + }, + "zh": { + "render.directional_sun_limit": "GPU 总共支持八个平行光源,其中最多一个为柔和太阳光。复制硬阴影平行光可添加另一个远处光源。" + } +} diff --git a/assets/locales/pending/gpu-path-setup-status.json b/assets/locales/pending/gpu-path-setup-status.json new file mode 100644 index 000000000..e60ff1986 --- /dev/null +++ b/assets/locales/pending/gpu-path-setup-status.json @@ -0,0 +1,26 @@ +{ + "ar": { + "render.gpu_path_not_started": "لم يبدأ إعداد متتبع المسارات على المعالج الرسومي بعد." + }, + "de": { + "render.gpu_path_not_started": "Die Einrichtung des GPU-Pfadtracers wurde noch nicht gestartet." + }, + "en": { + "render.gpu_path_not_started": "GPU path tracer setup has not started." + }, + "he": { + "render.gpu_path_not_started": "הגדרת מעקב המסלולים ב-GPU טרם התחילה." + }, + "ja": { + "render.gpu_path_not_started": "GPUパストレーサーのセットアップはまだ開始されていません。" + }, + "ko": { + "render.gpu_path_not_started": "GPU 경로 추적기 설정이 아직 시작되지 않았습니다." + }, + "vi": { + "render.gpu_path_not_started": "Quá trình thiết lập bộ dò đường đi GPU chưa bắt đầu." + }, + "zh": { + "render.gpu_path_not_started": "GPU路径追踪器的设置尚未开始。" + } +} diff --git a/assets/locales/pending/gpu-punctual-lights.json b/assets/locales/pending/gpu-punctual-lights.json new file mode 100644 index 000000000..8d76ce51a --- /dev/null +++ b/assets/locales/pending/gpu-punctual-lights.json @@ -0,0 +1,58 @@ +{ + "ar": { + "render.spot_axis": "اتجاه انبعاث الضوء", + "render.spot_gpu_help": "تُقاس الزوايا من اتجاه انبعاث الضوء. يتلاشى الضوء بين الزاويتين الداخلية والخارجية. تتطلب نطاقات التلاشي الضيقة جداً التصيير باستخدام CPU.", + "render.spot_help": "تُقاس الزوايا من اتجاه انبعاث الضوء. يتلاشى الضوء بين الزاويتين الداخلية والخارجية.", + "render.spot_inner": "نصف الزاوية الداخلية", + "render.spot_outer": "نصف الزاوية الخارجية" + }, + "de": { + "render.spot_axis": "Abstrahlrichtung", + "render.spot_gpu_help": "Die Winkel werden von der Abstrahlrichtung aus gemessen. Zwischen innerem und äußerem Winkel wird das Licht schwächer. Sehr schmale Übergänge erfordern CPU-Rendering.", + "render.spot_help": "Die Winkel werden von der Abstrahlrichtung aus gemessen. Zwischen innerem und äußerem Winkel wird das Licht schwächer.", + "render.spot_inner": "Innerer Halbwinkel", + "render.spot_outer": "Äußerer Halbwinkel" + }, + "en": { + "render.spot_axis": "Emission direction", + "render.spot_gpu_help": "Angles are measured from the emission direction. Light fades between the inner and outer angles. Very narrow fade ranges require CPU rendering.", + "render.spot_help": "Angles are measured from the emission direction. Light fades between the inner and outer angles.", + "render.spot_inner": "Inner half-angle", + "render.spot_outer": "Outer half-angle" + }, + "he": { + "render.spot_axis": "כיוון פליטת האור", + "render.spot_gpu_help": "הזוויות נמדדות מכיוון פליטת האור. האור דועך בין הזווית הפנימית לחיצונית. טווחי דעיכה צרים מאוד דורשים רינדור באמצעות CPU.", + "render.spot_help": "הזוויות נמדדות מכיוון פליטת האור. האור דועך בין הזווית הפנימית לחיצונית.", + "render.spot_inner": "חצי זווית פנימית", + "render.spot_outer": "חצי זווית חיצונית" + }, + "ja": { + "render.spot_axis": "光の照射方向", + "render.spot_gpu_help": "角度は光の照射方向から測ります。内側の角度から外側の角度にかけて光が弱まります。減衰範囲が非常に狭い場合はCPUレンダリングが必要です。", + "render.spot_help": "角度は光の照射方向から測ります。内側の角度から外側の角度にかけて光が弱まります。", + "render.spot_inner": "内側の半角", + "render.spot_outer": "外側の半角" + }, + "ko": { + "render.spot_axis": "빛의 방출 방향", + "render.spot_gpu_help": "각도는 빛의 방출 방향을 기준으로 측정합니다. 안쪽 각도와 바깥쪽 각도 사이에서 빛이 약해집니다. 감쇠 범위가 매우 좁으면 CPU 렌더링이 필요합니다.", + "render.spot_help": "각도는 빛의 방출 방향을 기준으로 측정합니다. 안쪽 각도와 바깥쪽 각도 사이에서 빛이 약해집니다.", + "render.spot_inner": "안쪽 반각", + "render.spot_outer": "바깥쪽 반각" + }, + "vi": { + "render.spot_axis": "Hướng phát sáng", + "render.spot_gpu_help": "Các góc được đo từ hướng phát sáng. Ánh sáng yếu dần giữa góc trong và góc ngoài. Dải chuyển tiếp rất hẹp cần kết xuất bằng CPU.", + "render.spot_help": "Các góc được đo từ hướng phát sáng. Ánh sáng yếu dần giữa góc trong và góc ngoài.", + "render.spot_inner": "Nửa góc trong", + "render.spot_outer": "Nửa góc ngoài" + }, + "zh": { + "render.spot_axis": "光线发射方向", + "render.spot_gpu_help": "角度以光线发射方向为基准测量。光线在内角和外角之间逐渐减弱。极窄的衰减范围需要使用CPU渲染。", + "render.spot_help": "角度以光线发射方向为基准测量。光线在内角和外角之间逐渐减弱。", + "render.spot_inner": "内半角", + "render.spot_outer": "外半角" + } +} diff --git a/assets/locales/pending/render-adaptive-feedback.json b/assets/locales/pending/render-adaptive-feedback.json new file mode 100644 index 000000000..f82cde225 --- /dev/null +++ b/assets/locales/pending/render-adaptive-feedback.json @@ -0,0 +1,50 @@ +{ + "ar": { + "render.adaptive.pilot_progress": "تمريرات تمهيدية تكيفية · {current}/{target}", + "render.adaptive.preview_help": "توجّه الصور التمهيدية توزيع العينات ولا تدخل في الصورة النهائية. تستخدم تكرارات التصيير ميزانية منفصلة لكل بكسل؛ ولا يمثّل عدد التكرارات عددًا موحدًا من العينات لكل بكسل.", + "render.adaptive.production_progress": "التصيير التكيفي · {current}/{target} تكرارات", + "render.live.adaptive": "مباشر · {width} × {height} · {progress}" + }, + "de": { + "render.adaptive.pilot_progress": "Adaptive Pilotphase · {current}/{target} Durchgänge", + "render.adaptive.preview_help": "Pilotbilder bestimmen die Verteilung und sind vom Endbild ausgeschlossen. Produktionsiterationen nutzen ein eigenes Budget pro Pixel; die Iterationszahl ist keine einheitliche Samplezahl pro Pixel.", + "render.adaptive.production_progress": "Adaptive Produktion · {current}/{target} Iterationen", + "render.live.adaptive": "Live · {width} × {height} · {progress}" + }, + "en": { + "render.adaptive.pilot_progress": "Adaptive pilots · {current}/{target} passes", + "render.adaptive.preview_help": "Pilot images guide allocation and are excluded from the final image. Production iterations use a separate budget for each pixel; the iteration count is not uniform samples per pixel.", + "render.adaptive.production_progress": "Adaptive production · {current}/{target} iterations", + "render.live.adaptive": "Live · {width} × {height} · {progress}" + }, + "he": { + "render.adaptive.pilot_progress": "מעברים מקדימים אדפטיביים · {current}/{target}", + "render.adaptive.preview_help": "התמונות המקדימות מנחות את הקצאת הדגימות ואינן נכללות בתמונה הסופית. איטרציות ההדמיה משתמשות בתקציב נפרד לכל פיקסל; מספר האיטרציות אינו מספר דגימות אחיד לכל פיקסל.", + "render.adaptive.production_progress": "הדמיה אדפטיבית · {current}/{target} איטרציות", + "render.live.adaptive": "חי · {width} × {height} · {progress}" + }, + "ja": { + "render.adaptive.pilot_progress": "適応パイロット · {current}/{target} パス", + "render.adaptive.preview_help": "パイロット画像は配分の決定に使われ、最終画像には含まれません。本処理はピクセルごとに別の予算を使うため、反復回数は全ピクセル共通のサンプル数ではありません。", + "render.adaptive.production_progress": "適応本処理 · {current}/{target} 回", + "render.live.adaptive": "ライブ · {width} × {height} · {progress}" + }, + "ko": { + "render.adaptive.pilot_progress": "적응형 파일럿 · {current}/{target} 패스", + "render.adaptive.preview_help": "파일럿 이미지는 예산 배분에 사용되며 최종 이미지에서 제외됩니다. 본 처리는 픽셀마다 별도의 예산을 사용하므로 반복 횟수는 모든 픽셀의 동일한 샘플 수를 뜻하지 않습니다.", + "render.adaptive.production_progress": "적응형 본 처리 · {current}/{target} 회", + "render.live.adaptive": "라이브 · {width} × {height} · {progress}" + }, + "vi": { + "render.adaptive.pilot_progress": "Các lượt thăm dò thích ứng · {current}/{target}", + "render.adaptive.preview_help": "Ảnh thăm dò định hướng việc phân bổ mẫu và không được đưa vào ảnh cuối cùng. Các vòng kết xuất sử dụng ngân sách riêng cho từng pixel; số vòng không phải số mẫu đồng đều trên mỗi pixel.", + "render.adaptive.production_progress": "Kết xuất thích ứng · {current}/{target} vòng lặp", + "render.live.adaptive": "Trực tiếp · {width} × {height} · {progress}" + }, + "zh": { + "render.adaptive.pilot_progress": "自适应预采样 · {current}/{target} 轮", + "render.adaptive.preview_help": "预采样图像用于分配预算,不计入最终图像。正式采样为每个像素使用独立预算;迭代次数不表示所有像素具有相同的采样数。", + "render.adaptive.production_progress": "自适应正式采样 · {current}/{target} 轮迭代", + "render.live.adaptive": "实时 · {width} × {height} · {progress}" + } +} diff --git a/assets/locales/pending/render-all-shots-controls.json b/assets/locales/pending/render-all-shots-controls.json new file mode 100644 index 000000000..8760c4eee --- /dev/null +++ b/assets/locales/pending/render-all-shots-controls.json @@ -0,0 +1,26 @@ +{ + "ar": { + "render.batch_current_settings_help": "يستخدم إعدادات الصورة الحالية مع كاميرا كل لقطة محفوظة، لقطة واحدة في كل مرة." + }, + "de": { + "render.batch_current_settings_help": "Verwendet die aktuellen Bildeinstellungen mit jeder gespeicherten Aufnahmekamera, eine Aufnahme nach der anderen." + }, + "en": { + "render.batch_current_settings_help": "Uses the current image settings with each saved shot camera, one shot at a time." + }, + "he": { + "render.batch_current_settings_help": "משתמש בהגדרות התמונה הנוכחיות עם המצלמה של כל שוט שמור, שוט אחד בכל פעם." + }, + "ja": { + "render.batch_current_settings_help": "現在の画像設定と各保存済みショットのカメラで、1ショットずつレンダリングします。" + }, + "ko": { + "render.batch_current_settings_help": "현재 이미지 설정과 저장된 각 샷의 카메라를 사용해 한 번에 한 샷씩 렌더링합니다." + }, + "vi": { + "render.batch_current_settings_help": "Dùng thiết lập ảnh hiện tại với máy ảnh của từng góc chụp đã lưu, lần lượt từng góc chụp." + }, + "zh": { + "render.batch_current_settings_help": "使用当前图像设置和各个已保存镜头的相机,逐个渲染镜头。" + } +} diff --git a/assets/locales/pending/render-clear-coat-saved.json b/assets/locales/pending/render-clear-coat-saved.json new file mode 100644 index 000000000..894b5c834 --- /dev/null +++ b/assets/locales/pending/render-clear-coat-saved.json @@ -0,0 +1,98 @@ +{ + "ar": { + "cmd.render.coat.bind": "حفظ الطلاء الشفاف", + "cmd.render.coat.unbind": "إزالة الطلاء الشفاف", + "render.coat_discard": "تجاهل تعديل الطلاء", + "render.coat_pending_edit": "لم يُحفظ تعديل الطلاء هذا. احفظه مع اللقطة أو تجاهل التعديل.", + "render.coat_remove": "إزالة الطلاء المحفوظ", + "render.coat_remove_note": "يزيل طلاء هذا الهدف من اللقطة. تبقى الهندسة والمظاهر والمواد الفيزيائية دون تغيير.", + "render.coat_remove_title": "إزالة الطلاء الشفاف المحفوظ؟", + "render.coat_revalidate_saved": "تغيّر الطلاء المحفوظ. تجاهل هذا التعديل وأعد فتح الهدف قبل تعديله مجددًا.", + "render.coat_save": "حفظ الطلاء مع اللقطة", + "render.coat_saved_help": "يضيف الطلاء الشفاف طبقة لامعة إلى الأسطح المعتمة. احفظه مع اللقطة. لا يمكن استخدام الزجاج على الهدف نفسه، ولا تجاوزات الانعكاس المخصص والتباين الاتجاهي على CPU." + }, + "de": { + "cmd.render.coat.bind": "Klarlack speichern", + "cmd.render.coat.unbind": "Klarlack entfernen", + "render.coat_discard": "Klarlackänderung verwerfen", + "render.coat_pending_edit": "Diese Klarlackänderung ist ungespeichert. Mit der Aufnahme speichern oder verwerfen.", + "render.coat_remove": "Gespeicherten Klarlack entfernen", + "render.coat_remove_note": "Entfernt den Klarlack dieses Ziels aus der Aufnahme. Geometrie, Aussehen und physikalische Materialien bleiben unverändert.", + "render.coat_remove_title": "Gespeicherten Klarlack entfernen?", + "render.coat_revalidate_saved": "Der gespeicherte Klarlack wurde geändert. Diese Änderung verwerfen und das Ziel vor der nächsten Bearbeitung erneut öffnen.", + "render.coat_save": "Klarlack in Aufnahme speichern", + "render.coat_saved_help": "Klarlack fügt undurchsichtigen Flächen eine glänzende Schicht hinzu. Mit der Aufnahme speichern. Glas kann nicht dasselbe Ziel verwenden. Auf der CPU dürfen auch benutzerdefinierte Reflexions- und Anisotropieüberschreibungen dieses Ziel nicht verwenden." + }, + "en": { + "cmd.render.coat.bind": "Save Clear Coat", + "cmd.render.coat.unbind": "Remove Clear Coat", + "render.coat_discard": "Discard coat edit", + "render.coat_pending_edit": "This coat edit is unsaved. Save it with the shot or discard it.", + "render.coat_remove": "Remove saved coat", + "render.coat_remove_note": "Removes this target’s coat from the shot. Geometry, appearances and physical materials stay unchanged.", + "render.coat_remove_title": "Remove saved clear coat?", + "render.coat_revalidate_saved": "The saved coat changed. Discard this edit and reopen the target before editing it again.", + "render.coat_save": "Save coat to shot", + "render.coat_saved_help": "Clear coat adds a glossy layer to opaque surfaces. Save it with the shot. Glass cannot share this target. CPU custom reflection and anisotropy overrides cannot share it either." + }, + "he": { + "cmd.render.coat.bind": "שמירת ציפוי שקוף", + "cmd.render.coat.unbind": "הסרת ציפוי שקוף", + "render.coat_discard": "ביטול עריכת הציפוי", + "render.coat_pending_edit": "שינוי הציפוי הזה לא נשמר. יש לשמור אותו עם התצלום או לבטל את השינוי.", + "render.coat_remove": "הסרת ציפוי שמור", + "render.coat_remove_note": "מסיר את הציפוי של היעד הזה מהתצלום. הגאומטריה, המראה והחומרים הפיזיקליים אינם משתנים.", + "render.coat_remove_title": "להסיר את הציפוי השקוף השמור?", + "render.coat_revalidate_saved": "הציפוי השמור השתנה. יש לבטל את העריכה הזו ולפתוח מחדש את היעד לפני עריכה נוספת.", + "render.coat_save": "שמירת הציפוי בתצלום", + "render.coat_saved_help": "ציפוי שקוף מוסיף שכבה מבריקה למשטחים אטומים. יש לשמור אותו עם התצלום. זכוכית אינה יכולה להשתמש באותו יעד, וגם לא דריסות של השתקפות מותאמת אישית ואנאיזוטרופיה ב־CPU." + }, + "ja": { + "cmd.render.coat.bind": "クリアコートを保存", + "cmd.render.coat.unbind": "クリアコートを削除", + "render.coat_discard": "コートの編集を破棄", + "render.coat_pending_edit": "クリアコートの変更は未保存です。ショットに保存するか破棄してください。", + "render.coat_remove": "保存済みコートを削除", + "render.coat_remove_note": "この対象のコートをショットから削除します。形状、外観、物理材料は変更されません。", + "render.coat_remove_title": "保存済みクリアコートを削除しますか?", + "render.coat_revalidate_saved": "保存済みコートが変更されています。この編集を破棄し、対象を開き直してから編集してください。", + "render.coat_save": "コートをショットに保存", + "render.coat_saved_help": "クリアコートは不透明な表面に光沢のある層を追加します。ショットに保存してください。同じ対象にガラスは使用できません。CPUのカスタム反射や異方性の上書きも、この対象と併用できません。" + }, + "ko": { + "cmd.render.coat.bind": "클리어 코트 저장", + "cmd.render.coat.unbind": "클리어 코트 제거", + "render.coat_discard": "코트 편집 버리기", + "render.coat_pending_edit": "이 코트 편집은 저장되지 않았습니다. 샷에 저장하거나 편집을 버리세요.", + "render.coat_remove": "저장된 코트 제거", + "render.coat_remove_note": "이 대상의 코트를 샷에서 제거합니다. 형상, 외관 및 물리 재료는 변경되지 않습니다.", + "render.coat_remove_title": "저장된 클리어 코트를 제거할까요?", + "render.coat_revalidate_saved": "저장된 코트가 변경되었습니다. 이 편집을 버리고 대상을 다시 연 뒤 편집하세요.", + "render.coat_save": "샷에 코트 저장", + "render.coat_saved_help": "클리어 코트는 불투명 표면에 광택 층을 추가합니다. 샷에 저장하세요. 같은 대상에 유리를 사용할 수 없습니다. CPU 사용자 지정 반사 또는 이방성 재정의도 이 대상을 함께 사용할 수 없습니다." + }, + "vi": { + "cmd.render.coat.bind": "Lưu lớp phủ bóng", + "cmd.render.coat.unbind": "Xóa lớp phủ bóng", + "render.coat_discard": "Hủy chỉnh sửa lớp phủ", + "render.coat_pending_edit": "Chỉnh sửa lớp phủ này chưa được lưu. Hãy lưu cùng cảnh chụp hoặc hủy chỉnh sửa.", + "render.coat_remove": "Xóa lớp phủ đã lưu", + "render.coat_remove_note": "Xóa lớp phủ của đích này khỏi cảnh chụp. Hình học, diện mạo và vật liệu vật lý không thay đổi.", + "render.coat_remove_title": "Xóa lớp phủ bóng đã lưu?", + "render.coat_revalidate_saved": "Lớp phủ đã lưu đã thay đổi. Hãy hủy chỉnh sửa này và mở lại đích trước khi sửa tiếp.", + "render.coat_save": "Lưu lớp phủ vào cảnh chụp", + "render.coat_saved_help": "Lớp phủ bóng thêm một lớp sáng bóng lên bề mặt đục. Hãy lưu cùng cảnh chụp. Kính không thể dùng chung đích này. Ghi đè phản xạ tùy chỉnh và tính dị hướng CPU cũng không thể dùng chung đích." + }, + "zh": { + "cmd.render.coat.bind": "保存清漆", + "cmd.render.coat.unbind": "移除清漆", + "render.coat_discard": "放弃清漆编辑", + "render.coat_pending_edit": "清漆编辑尚未保存。请保存到镜头或放弃编辑。", + "render.coat_remove": "移除已保存清漆", + "render.coat_remove_note": "从镜头中移除此目标的清漆。几何、外观和物理材料保持不变。", + "render.coat_remove_title": "移除已保存的清漆?", + "render.coat_revalidate_saved": "已保存的清漆发生了变化。请放弃此编辑,重新打开目标后再编辑。", + "render.coat_save": "将清漆保存到镜头", + "render.coat_saved_help": "清漆为不透明表面添加光泽层。请随镜头保存。同一目标不能使用玻璃,也不能使用CPU自定义反射或各向异性覆盖。" + } +} diff --git a/assets/locales/pending/render-cpu-glass-certification.json b/assets/locales/pending/render-cpu-glass-certification.json new file mode 100644 index 000000000..526baf799 --- /dev/null +++ b/assets/locales/pending/render-cpu-glass-certification.json @@ -0,0 +1,64 @@ +{ + "ar": { + "render.check_glass_cpu": "يدعم CPU صفائح زجاج مستوية وصناديق محاذية للمحاور بعد التحقق منها. تتطلب الشبكات المغلقة العامة والتعشيق والتشتت الداخلي إضاءة غير مباشرة. لا تزال الظلال النافذة عبر الزجاج المغلق غير مدعومة.", + "render.check_glass_gpu": "يدعم GPU أوساط زجاج منفصلة متحققًا منها، أو تعشيقًا متحققًا منه عند تفعيله صراحةً. يتطلب التعشيق أغلفة خارجية محدبة وأجسامًا داخلية محتواة بالكامل وحدودًا غير متلامسة.", + "render.check_media_remaining": "لا تزال تأثيرات الزجاج الخشن وشبكات الكثافة والإزاحة والنقل الطيفي غير متاحة.", + "render.check_media_scope": "يتطلب التشتت الداخلي النشط وسطًا زجاجيًا مغلقًا مع إيقاف نفاذ أشعة الظل المستقيمة وإزالة الضجيج. ويتطلب GPU أيضًا طبقة عينات فرينل واحدة. لا يمكن جمع الغلاف الجوي الخارجي النشط مع الزجاج أو إزالة ضجيج الأسطح.", + "render.cpu_material_certification": "يتحقق فحص CPU من هندسة الزجاج المدعومة قبل التصيير. يستخدم الزجاج المغلق المسافة الهندسية." + }, + "de": { + "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_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.cpu_material_certification": "Die CPU-Prüfung validiert unterstützte Glasgeometrie vor dem Rendern. Geschlossenes Glas verwendet geometrische Abstände." + }, + "en": { + "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_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.cpu_material_certification": "CPU Check validates supported Glass geometry before rendering. Closed Glass uses geometric distance." + }, + "es": { + "render.cpu_material_certification": "La comprobación de CPU valida la geometría de vidrio admitida antes de renderizar. El vidrio cerrado usa la distancia geométrica." + }, + "fr": { + "render.cpu_material_certification": "La vérification CPU valide la géométrie de verre prise en charge avant le rendu. Le verre fermé utilise la distance géométrique." + }, + "he": { + "render.check_glass_cpu": "ה־CPU תומך בלוחות זכוכית מישוריים ובתיבות מקבילות לצירים שעברו אימות. רשתות סגורות כלליות, קינון ופיזור פנימי דורשים תאורה עקיפה. העברת צל דרך זכוכית סגורה עדיין אינה נתמכת.", + "render.check_glass_gpu": "ה־GPU תומך בנפחי זכוכית נפרדים שעברו אימות או בקינון מאומת שמופעל במפורש. קינון דורש גופים חיצוניים קמורים, גופים פנימיים המוכלים בתוכם ממש וגבולות שאינם נוגעים זה בזה.", + "render.check_media_remaining": "זכוכית מחוספסת, רשתות צפיפות, הסטת משטח והעברת אור ספקטרלית עדיין אינן זמינות.", + "render.check_media_scope": "פיזור פנימי פעיל דורש נפח זכוכית סגור, העברת קרני צל ישרות כבויה והסרת רעש כבויה. ה־GPU דורש גם שכבת פרנל אחת. אי אפשר לשלב אטמוספירה חיצונית פעילה עם זכוכית או עם הסרת רעש משטחית.", + "render.cpu_material_certification": "בדיקת CPU מאמתת את גאומטריית הזכוכית הנתמכת לפני הרינדור. זכוכית סגורה משתמשת במרחק גאומטרי." + }, + "ja": { + "render.check_glass_cpu": "CPUは検証済みの平面ガラス薄板と軸に平行な箱に対応します。一般の閉じたメッシュ、入れ子、内部散乱には間接照明が必要です。閉じたガラスを通る透過影には未対応です。", + "render.check_glass_gpu": "GPUは検証済みの分離したガラス、または明示的に有効にした検証済みの入れ子に対応します。入れ子には凸形状の親、厳密に内包された子、接触しない境界が必要です。", + "render.check_media_remaining": "粗いガラス、密度グリッド、ディスプレイスメント、分光輸送には未対応です。", + "render.check_media_scope": "有効な内部散乱には閉じたガラス媒質を使い、直線の影透過とノイズ除去をオフにします。GPUではフレネル層を1つにします。有効な外部の大気はガラスや表面ノイズ除去と併用できません。", + "render.cpu_material_certification": "CPUの確認では、レンダリング前に対応するガラス形状を検証します。閉じたガラスには形状から得られる距離を使います。" + }, + "ko": { + "render.check_glass_cpu": "CPU는 검증된 평면 유리판과 축 정렬 상자를 지원합니다. 일반적인 닫힌 메시, 중첩 및 내부 산란에는 간접광이 필요합니다. 닫힌 유리를 통과하는 투과 그림자는 아직 지원하지 않습니다.", + "render.check_glass_gpu": "GPU는 검증된 분리 유리 또는 명시적으로 활성화한 검증된 중첩을 지원합니다. 중첩에는 볼록한 바깥 형상, 완전히 내부에 포함된 안쪽 형상 및 서로 닿지 않는 경계가 필요합니다.", + "render.check_media_remaining": "거친 유리, 밀도 격자, 디스플레이스먼트 및 분광 광전달은 아직 지원하지 않습니다.", + "render.check_media_scope": "활성 내부 산란에는 닫힌 유리 매질이 필요하며 직선 그림자 투과와 노이즈 제거를 꺼야 합니다. GPU에는 프레넬 계층도 하나만 필요합니다. 활성 외부 대기는 유리 또는 표면 노이즈 제거와 함께 사용할 수 없습니다.", + "render.cpu_material_certification": "CPU 검사는 렌더링 전에 지원되는 유리 형상을 검증합니다. 닫힌 유리는 기하학적 거리를 사용합니다." + }, + "vi": { + "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_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.cpu_material_certification": "Kiểm tra trên CPU xác thực hình học thủy tinh được hỗ trợ trước khi kết xuất. Thủy tinh kín sử dụng khoảng cách hình học." + }, + "zh": { + "render.check_glass_cpu": "CPU 支持经验证的平面玻璃薄片和轴对齐盒体。一般闭合网格、嵌套和内部散射需要间接光照。仍不支持穿过闭合玻璃的透射阴影。", + "render.check_glass_gpu": "GPU 支持经验证的互不相交玻璃介质,或明确启用的经验证嵌套。嵌套要求外层物体为凸体、内层物体严格包含于其中,且边界互不接触。", + "render.check_media_remaining": "仍不支持粗糙玻璃、密度网格、位移和光谱传输。", + "render.check_media_scope": "启用内部散射需要闭合玻璃介质,并关闭直线阴影透射和降噪。GPU 还需要只使用一个菲涅耳分层。启用的外部大气不能与玻璃或表面降噪同时使用。", + "render.cpu_material_certification": "CPU 检查会在渲染前验证所支持的玻璃几何体。封闭玻璃使用几何距离。" + } +} diff --git a/assets/locales/pending/render-cpu-output.json b/assets/locales/pending/render-cpu-output.json new file mode 100644 index 000000000..2baab36ae --- /dev/null +++ b/assets/locales/pending/render-cpu-output.json @@ -0,0 +1,58 @@ +{ + "ar": { + "render.cpu_opaque_hint": "يستخدم تتبع الأشعة على CPU خلفية معتمة.", + "render.output_master_unavailable": "لتصدير EXR، اختر صورة مكتملة تحتوي على بيانات EXR خام. فعّل EXR الخام قبل تصيير صور جديدة.", + "render.output_presentation_limits": "تدعم مؤثرات الصور على CPU وإخراج EXR صوراً بعرض وارتفاع لا يتجاوزان 8192 بكسل، وبإجمالي لا يتجاوز 16,777,216 بكسل.", + "render.output_raytrace_only": "تتطلب مؤثرات الصور تتبع الأشعة على CPU أو تتبع المسارات على GPU.", + "render.presentation_banner": "تعمل مؤثرات إخراج الصورة مع تتبع الأشعة على CPU وGPU. فتح هذه الصفحة لا يغيّر الطريقة مطلقًا." + }, + "de": { + "render.cpu_opaque_hint": "CPU-Raytracing verwendet einen undurchsichtigen Hintergrund.", + "render.output_master_unavailable": "Zum EXR-Export ein fertiges Bild mit EXR-Rohdaten auswählen. EXR-Rohdaten vor dem Rendern neuer Bilder aktivieren.", + "render.output_presentation_limits": "CPU-Bildeffekte und EXR-Ausgabe unterstützen Bilder mit bis zu 8192 Pixeln Breite oder Höhe und insgesamt höchstens 16.777.216 Pixeln.", + "render.output_raytrace_only": "Bildeffekte erfordern CPU-Raytracing oder GPU-Pathtracing.", + "render.presentation_banner": "Bildeffekte funktionieren mit CPU- und GPU-Raytracing. Das Öffnen dieser Seite ändert die Methode nicht." + }, + "en": { + "render.cpu_opaque_hint": "CPU ray tracing uses an opaque background.", + "render.output_master_unavailable": "Select a completed image with raw EXR data to export EXR. Enable raw EXR before rendering new images.", + "render.output_presentation_limits": "CPU image effects and EXR output support images up to 8192 pixels wide or high, with at most 16,777,216 pixels in total.", + "render.output_raytrace_only": "Image effects require CPU ray tracing or GPU path tracing.", + "render.presentation_banner": "Presentation effects work with CPU and GPU ray tracing. Opening this page never changes the method." + }, + "he": { + "render.cpu_opaque_hint": "עקיבת קרניים ב־CPU משתמשת ברקע אטום.", + "render.output_master_unavailable": "כדי לייצא EXR, יש לבחור תמונה שהושלמה ומכילה נתוני EXR גולמיים. יש להפעיל EXR גולמי לפני רינדור תמונות חדשות.", + "render.output_presentation_limits": "אפקטים של תמונה ב־CPU ופלט EXR תומכים בתמונות ברוחב ובגובה של עד 8192 פיקסלים, ועד 16,777,216 פיקסלים בסך הכול.", + "render.output_raytrace_only": "אפקטים של תמונה דורשים עקיבת קרניים ב־CPU או עקיבת נתיבים ב־GPU.", + "render.presentation_banner": "אפקטים של תצוגת התמונה פועלים בעקיבת קרניים ב־CPU וב־GPU. פתיחת דף זה לעולם אינה משנה את השיטה." + }, + "ja": { + "render.cpu_opaque_hint": "CPUレイトレーシングでは不透明な背景を使用します。", + "render.output_master_unavailable": "EXRを書き出すには、RAW EXRデータを持つ完成画像を選択してください。新しい画像は、レンダリング前にRAW EXRを有効にしてください。", + "render.output_presentation_limits": "CPUの画像効果とEXR出力は、幅・高さとも8192ピクセル以下、合計16,777,216ピクセル以下の画像に対応します。", + "render.output_raytrace_only": "画像効果にはCPUレイトレーシングまたはGPUパストレーシングが必要です。", + "render.presentation_banner": "画像効果はCPUとGPUのレイトレーシングで使用できます。このページを開いても方式は変わりません。" + }, + "ko": { + "render.cpu_opaque_hint": "CPU 레이 트레이싱은 불투명한 배경을 사용합니다.", + "render.output_master_unavailable": "EXR을 내보내려면 원본 EXR 데이터가 있는 완성 이미지를 선택하세요. 새 이미지를 렌더링하기 전에 원본 EXR을 활성화하세요.", + "render.output_presentation_limits": "CPU 이미지 효과와 EXR 출력은 너비와 높이가 각각 최대 8192픽셀이고 총 16,777,216픽셀 이하인 이미지를 지원합니다.", + "render.output_raytrace_only": "이미지 효과에는 CPU 레이 트레이싱 또는 GPU 패스 트레이싱이 필요합니다.", + "render.presentation_banner": "이미지 효과는 CPU 및 GPU 레이 트레이싱에서 사용할 수 있습니다. 이 페이지를 열어도 방식이 바뀌지 않습니다." + }, + "vi": { + "render.cpu_opaque_hint": "Dò tia trên CPU sử dụng nền không trong suốt.", + "render.output_master_unavailable": "Để xuất EXR, hãy chọn ảnh đã hoàn tất có dữ liệu EXR thô. Bật EXR thô trước khi kết xuất ảnh mới.", + "render.output_presentation_limits": "Hiệu ứng ảnh trên CPU và đầu ra EXR hỗ trợ ảnh có chiều rộng và chiều cao tối đa 8192 pixel, với tổng cộng không quá 16.777.216 pixel.", + "render.output_raytrace_only": "Hiệu ứng ảnh yêu cầu dò tia trên CPU hoặc dò đường đi trên GPU.", + "render.presentation_banner": "Các hiệu ứng hình ảnh hoạt động với dò tia trên CPU và GPU. Mở trang này không bao giờ thay đổi phương pháp." + }, + "zh": { + "render.cpu_opaque_hint": "CPU光线追踪使用不透明背景。", + "render.output_master_unavailable": "要导出EXR,请选择包含原始EXR数据的已完成图像。渲染新图像前请先启用原始EXR。", + "render.output_presentation_limits": "CPU图像效果和EXR输出支持宽度、高度均不超过8192像素且总像素数不超过16,777,216的图像。", + "render.output_raytrace_only": "图像效果需要CPU光线追踪或GPU路径追踪。", + "render.presentation_banner": "图像效果支持CPU和GPU光线追踪。打开此页面不会更改渲染方式。" + } +} diff --git a/assets/locales/pending/render-image-defaults.json b/assets/locales/pending/render-image-defaults.json new file mode 100644 index 000000000..3b41f5c01 --- /dev/null +++ b/assets/locales/pending/render-image-defaults.json @@ -0,0 +1,36 @@ +{ + "ar": { + "prefs.render_legacy_image_defaults": "استخدام الإعدادات الافتراضية السابقة لصور التصيير", + "prefs.render_legacy_image_defaults_help": "الاحتفاظ بسير العمل اليدوي السابق: إعدادات جديدة بالتصيير النقطي على CPU، وأخذ العينات الثابت لتتبع الأشعة على CPU، وفتح النتائج يدويًا. إعادة ملاءمة العرض عند دخول التصيير، وتبديل اللقطات دون استعادة كاميراتها، واستخدام التأطير والتنقل السابقين. تعطيل التحديث التلقائي للصورة المباشرة. لا تتغير الإعدادات المحفوظة." + }, + "de": { + "prefs.render_legacy_image_defaults": "Bisherige Render-Bildvorgaben verwenden", + "prefs.render_legacy_image_defaults_help": "Den bisherigen manuellen Ablauf beibehalten: neue Setups mit CPU-Raster, feste Abtastung beim CPU-Raytracing und manuell geöffnete Ergebnisse. Beim Wechsel zu Render die Ansicht neu einpassen, Aufnahmen ohne Wiederherstellung ihrer Kamera wechseln und die bisherige Bildausrichtung und Navigation verwenden. Automatische Live-Bildrückmeldungen deaktivieren. Gespeicherte Setups bleiben unverändert." + }, + "en": { + "prefs.render_legacy_image_defaults": "Use previous Render image defaults", + "prefs.render_legacy_image_defaults_help": "Keep the previous manual workflow: new setups use CPU raster, CPU ray tracing keeps fixed sampling, and you open rendered results manually. Refit on Render entry, switch shots without restoring their cameras, and use the previous framing and navigation. Disable automatic live image feedback. Saved setups are unchanged." + }, + "he": { + "prefs.render_legacy_image_defaults": "שימוש בברירות המחדל הקודמות לתמונות הדמיה", + "prefs.render_legacy_image_defaults_help": "שמירה על תהליך העבודה הידני הקודם: הגדרות חדשות ברסטר CPU, דגימה קבועה בעקיבת קרניים ב־CPU ופתיחת התוצאות ידנית. התאמת התצוגה מחדש בכניסה להדמיה, מעבר בין צילומים בלי לשחזר את המצלמות שלהם ושימוש במסגור ובניווט הקודמים. עדכון אוטומטי של התמונה החיה מושבת. הגדרות שמורות אינן משתנות." + }, + "ja": { + "prefs.render_legacy_image_defaults": "以前のレンダー画像の既定値を使用", + "prefs.render_legacy_image_defaults_help": "以前の手動の画像ワークフローを使用します。新しいセットアップはCPUラスタ、CPUレイトレーシングは固定サンプリングとし、結果は手動で開きます。レンダーに入るたびにビューをフィットし、ショットを切り替えても保存カメラを復元せず、以前のフレーミングとナビゲーションを使用します。自動のライブ画像更新は無効にします。保存済みのセットアップは変更しません。" + }, + "ko": { + "prefs.render_legacy_image_defaults": "이전 렌더 이미지 기본값 사용", + "prefs.render_legacy_image_defaults_help": "이전의 수동 이미지 작업 방식을 유지합니다. 새 설정은 CPU 래스터를 사용하고 CPU 광선 추적은 고정 샘플링을 사용하며 결과는 직접 엽니다. 렌더에 들어갈 때 뷰를 다시 맞추고, 샷을 전환해도 저장된 카메라를 복원하지 않으며, 이전의 프레이밍과 탐색 방식을 사용합니다. 자동 실시간 이미지 피드백을 끕니다. 저장된 설정은 변경하지 않습니다.", + "render.method_raster": "CPU 래스터 (도식)", + "render.result_provisional": "임시 이미지" + }, + "vi": { + "prefs.render_legacy_image_defaults": "Dùng mặc định ảnh Kết xuất trước đây", + "prefs.render_legacy_image_defaults_help": "Giữ quy trình hình ảnh thủ công trước đây: thiết lập mới dùng raster CPU, dò tia CPU dùng lấy mẫu cố định và mở kết quả thủ công. Căn vừa lại khung nhìn khi vào Kết xuất, chuyển góc chụp mà không khôi phục camera đã lưu, đồng thời dùng cách lấy khung hình và điều hướng trước đây. Tắt phản hồi ảnh trực tiếp tự động. Các thiết lập đã lưu không thay đổi." + }, + "zh": { + "prefs.render_legacy_image_defaults": "使用以前的渲染图像默认值", + "prefs.render_legacy_image_defaults_help": "保留以前的手动图像流程:新设置使用 CPU 光栅渲染,CPU 光线追踪使用固定采样,并手动打开结果。进入渲染时重新适配视图,切换镜头时不恢复其保存的相机,并使用以前的取景和导航方式。禁用自动实时图像反馈。已保存的设置保持不变。" + } +} diff --git a/assets/locales/pending/render-light-space.json b/assets/locales/pending/render-light-space.json new file mode 100644 index 000000000..4ebcdac64 --- /dev/null +++ b/assets/locales/pending/render-light-space.json @@ -0,0 +1,34 @@ +{ + "ar": { + "render.light_space_world": "أضواء بإحداثيات العالم", + "render.light_space_world_help": "تستخدم مواضع الأضواء واتجاهاتها إحداثيات العالم. لا يؤدي تدوير الكاميرا حول النموذج إلى تحريك الأضواء." + }, + "de": { + "render.light_space_world": "Lichter in Weltkoordinaten", + "render.light_space_world_help": "Lichtpositionen und -richtungen verwenden Weltkoordinaten. Beim Umkreisen mit der Kamera bleiben die Lichter an ihrer Position." + }, + "en": { + "render.light_space_world": "World-space lights", + "render.light_space_world_help": "Light positions and directions use world coordinates. Orbiting the camera does not move them." + }, + "he": { + "render.light_space_world": "אורות בקואורדינטות העולם", + "render.light_space_world_help": "מיקומי האורות וכיווניהם משתמשים בקואורדינטות העולם. סיבוב המצלמה סביב המודל אינו מזיז את האורות." + }, + "ja": { + "render.light_space_world": "ワールド座標のライト", + "render.light_space_world_help": "ライトの位置と方向はワールド座標を使用します。カメラを周回させてもライトは移動しません。" + }, + "ko": { + "render.light_space_world": "월드 좌표의 조명", + "render.light_space_world_help": "조명의 위치와 방향은 월드 좌표를 사용합니다. 카메라를 회전해도 조명은 움직이지 않습니다." + }, + "vi": { + "render.light_space_world": "Đèn trong hệ tọa độ thế giới", + "render.light_space_world_help": "Vị trí và hướng của đèn dùng hệ tọa độ thế giới. Xoay camera quanh mô hình không làm đèn di chuyển." + }, + "zh": { + "render.light_space_world": "世界坐标光源", + "render.light_space_world_help": "光源的位置和方向使用世界坐标。环绕旋转相机不会移动光源。" + } +} diff --git a/assets/locales/pending/render-live-command.json b/assets/locales/pending/render-live-command.json new file mode 100644 index 000000000..6fb4724df --- /dev/null +++ b/assets/locales/pending/render-live-command.json @@ -0,0 +1,26 @@ +{ + "ar": { + "cmd.view.render_live": "إيقاف التصيير المباشر مؤقتًا أو استئنافه" + }, + "de": { + "cmd.view.render_live": "Live-Rendering pausieren oder fortsetzen" + }, + "en": { + "cmd.view.render_live": "Pause or Resume Live Render" + }, + "he": { + "cmd.view.render_live": "השהיה או חידוש של הדמיה חיה" + }, + "ja": { + "cmd.view.render_live": "ライブレンダーを一時停止・再開" + }, + "ko": { + "cmd.view.render_live": "실시간 렌더링 일시 중지 또는 재개" + }, + "vi": { + "cmd.view.render_live": "Tạm dừng hoặc tiếp tục kết xuất trực tiếp" + }, + "zh": { + "cmd.view.render_live": "暂停或继续实时渲染" + } +} diff --git a/assets/locales/pending/render-live-feedback.json b/assets/locales/pending/render-live-feedback.json new file mode 100644 index 000000000..58f2c9cc6 --- /dev/null +++ b/assets/locales/pending/render-live-feedback.json @@ -0,0 +1,130 @@ +{ + "ar": { + "render.live.final_changed": "تغيّر طلب التصيير أثناء إيقاف التصيير المباشر. ابدأ الصورة النهائية من جديد.", + "render.live.final_waiting": "جارٍ تحضير الصورة النهائية · تحرير موارد التصيير المباشر", + "render.live.invalid_size": "يتطلب التصيير المباشر عرضًا وارتفاعًا موجبين للإخراج.", + "render.live.pause": "إيقاف المباشر مؤقتًا", + "render.live.paused": "مباشر · متوقف مؤقتًا", + "render.live.paused_outdated": "مباشر · متوقف مؤقتًا · غير محدّث", + "render.live.quality_help": "جودة تفاعلية: بحد أقصى 512 بكسل للضلع الأطول. تستخدم المصيّر المحدد ومؤثراته المدعومة. تبقى دقة الصورة النهائية وإعداداتها وتصديرها مستقلة.", + "render.live.refused": "التصيير المباشر غير متاح: {reason}", + "render.live.resume": "استئناف المباشر", + "render.live.samples": "مباشر · {width} × {height} · {current}/{target} عينة", + "render.live.stopped": "توقف التصيير المباشر", + "render.live.updating": "مباشر · جودة تفاعلية (حتى 512 بكسل) · جارٍ التحديث", + "render.live.waiting_canvas": "في انتظار لوحة التصيير", + "render.live.worker_stopped": "توقفت مهمة التقاط التصيير المباشر قبل إرجاع نتيجة" + }, + "de": { + "render.live.final_changed": "Die Render-Anfrage hat sich beim Anhalten des Live-Renderings geändert. Starten Sie das finale Bild erneut.", + "render.live.final_waiting": "Finales Bild vorbereiten · Live-Render-Ressourcen freigeben", + "render.live.invalid_size": "Live-Rendering benötigt eine positive Ausgabebreite und -höhe.", + "render.live.pause": "Live pausieren", + "render.live.paused": "Live · Pausiert", + "render.live.paused_outdated": "Live · Pausiert · Veraltet", + "render.live.quality_help": "Interaktive Qualität: höchstens 512 Pixel an der längsten Kante. Verwendet den gewählten Renderer und seine unterstützten Effekte. Endauflösung, Einstellungen und Export bleiben getrennt.", + "render.live.refused": "Live nicht verfügbar: {reason}", + "render.live.resume": "Live fortsetzen", + "render.live.samples": "Live · {width} × {height} · {current}/{target} Samples", + "render.live.stopped": "Live-Rendering angehalten", + "render.live.updating": "Live · Interaktive Qualität (bis 512 px) · Aktualisierung", + "render.live.waiting_canvas": "Warten auf die Render-Ansicht", + "render.live.worker_stopped": "Der Aufnahmeprozess für das Live-Rendering wurde vor der Rückgabe eines Ergebnisses beendet" + }, + "en": { + "render.live.final_changed": "The render request changed while live rendering was stopping. Start the final image again.", + "render.live.final_waiting": "Preparing final image · releasing live-render resources", + "render.live.invalid_size": "Live rendering needs a positive output width and height.", + "render.live.pause": "Pause live", + "render.live.paused": "Live · Paused", + "render.live.paused_outdated": "Live · Paused · Out of date", + "render.live.quality_help": "Interactive quality: at most 512 pixels on the longest edge. Uses the selected renderer and its supported effects. Final resolution, settings and export remain separate.", + "render.live.refused": "Live unavailable: {reason}", + "render.live.resume": "Resume live", + "render.live.samples": "Live · {width} × {height} · {current}/{target} samples", + "render.live.stopped": "Live rendering stopped", + "render.live.updating": "Live · Interactive quality (up to 512 px) · Updating", + "render.live.waiting_canvas": "Waiting for the Render canvas", + "render.live.worker_stopped": "The live-render capture worker stopped before returning a result" + }, + "he": { + "render.live.final_changed": "בקשת ההדמיה השתנתה בזמן עצירת ההדמיה החיה. יש להתחיל את התמונה הסופית מחדש.", + "render.live.final_waiting": "מכין תמונה סופית · משחרר משאבי הדמיה חיה", + "render.live.invalid_size": "הדמיה חיה דורשת רוחב וגובה פלט גדולים מאפס.", + "render.live.pause": "השהיית הדמיה חיה", + "render.live.paused": "חי · מושהה", + "render.live.paused_outdated": "חי · מושהה · לא מעודכן", + "render.live.quality_help": "איכות אינטראקטיבית: לכל היותר 512 פיקסלים בצד הארוך. משתמשת במנוע ההדמיה שנבחר ובאפקטים הנתמכים בו. רזולוציית התמונה הסופית, ההגדרות והייצוא נשארים נפרדים.", + "render.live.refused": "הדמיה חיה אינה זמינה: {reason}", + "render.live.resume": "חידוש הדמיה חיה", + "render.live.samples": "חי · {width} × {height} · {current}/{target} דגימות", + "render.live.stopped": "ההדמיה החיה נעצרה", + "render.live.updating": "חי · איכות אינטראקטיבית (עד 512 פיקסלים) · מתעדכן", + "render.live.waiting_canvas": "ממתין למשטח ההדמיה", + "render.live.worker_stopped": "תהליך הלכידה של ההדמיה החיה נעצר לפני שהחזיר תוצאה" + }, + "ja": { + "render.live.final_changed": "ライブレンダリングの停止中にリクエストが変更されました。最終画像をもう一度開始してください。", + "render.live.final_waiting": "最終画像を準備中 · ライブレンダーのリソースを解放中", + "render.live.invalid_size": "ライブレンダリングには正の出力幅と高さが必要です。", + "render.live.pause": "ライブを一時停止", + "render.live.paused": "ライブ · 一時停止中", + "render.live.paused_outdated": "ライブ · 一時停止中 · 更新が必要", + "render.live.quality_help": "インタラクティブ品質: 長辺は最大512ピクセルです。選択したレンダラーと対応する効果を使用します。最終解像度、設定、書き出しは別に保持します。", + "render.live.refused": "ライブを利用できません: {reason}", + "render.live.resume": "ライブを再開", + "render.live.samples": "ライブ · {width} × {height} · {current}/{target} サンプル", + "render.live.stopped": "ライブレンダリングを停止しました", + "render.live.updating": "ライブ · インタラクティブ品質(最大512 px)· 更新中", + "render.live.waiting_canvas": "レンダーキャンバスを待機中", + "render.live.worker_stopped": "ライブレンダリングのキャプチャーワーカーが結果を返す前に停止しました" + }, + "ko": { + "render.live.final_changed": "라이브 렌더링을 중지하는 동안 렌더 요청이 변경되었습니다. 최종 이미지를 다시 시작하세요.", + "render.live.final_waiting": "최종 이미지 준비 중 · 라이브 렌더 리소스 해제 중", + "render.live.invalid_size": "라이브 렌더링에는 양수의 출력 너비와 높이가 필요합니다.", + "render.live.pause": "라이브 일시 중지", + "render.live.paused": "라이브 · 일시 중지됨", + "render.live.paused_outdated": "라이브 · 일시 중지됨 · 업데이트 필요", + "render.live.quality_help": "대화형 품질: 가장 긴 변은 최대 512픽셀입니다. 선택한 렌더러와 지원하는 효과를 사용합니다. 최종 해상도, 설정 및 내보내기는 별도로 유지됩니다.", + "render.live.refused": "라이브 사용 불가: {reason}", + "render.live.resume": "라이브 재개", + "render.live.samples": "라이브 · {width} × {height} · {current}/{target} 샘플", + "render.live.stopped": "라이브 렌더링 중지됨", + "render.live.updating": "라이브 · 대화형 품질(최대 512 px) · 업데이트 중", + "render.live.waiting_canvas": "렌더 캔버스 대기 중", + "render.live.worker_stopped": "라이브 렌더 캡처 작업이 결과를 반환하기 전에 중지되었습니다" + }, + "vi": { + "render.live.final_changed": "Yêu cầu kết xuất đã thay đổi trong lúc dừng kết xuất trực tiếp. Hãy bắt đầu lại ảnh cuối cùng.", + "render.live.final_waiting": "Đang chuẩn bị ảnh cuối · Giải phóng tài nguyên kết xuất trực tiếp", + "render.live.invalid_size": "Kết xuất trực tiếp yêu cầu chiều rộng và chiều cao đầu ra lớn hơn không.", + "render.live.pause": "Tạm dừng trực tiếp", + "render.live.paused": "Trực tiếp · Tạm dừng", + "render.live.paused_outdated": "Trực tiếp · Tạm dừng · Chưa cập nhật", + "render.live.quality_help": "Chất lượng tương tác: tối đa 512 pixel ở cạnh dài nhất. Sử dụng bộ kết xuất đã chọn và các hiệu ứng được bộ đó hỗ trợ. Độ phân giải cuối, thiết lập và thao tác xuất vẫn độc lập.", + "render.live.refused": "Kết xuất trực tiếp không khả dụng: {reason}", + "render.live.resume": "Tiếp tục trực tiếp", + "render.live.samples": "Trực tiếp · {width} × {height} · {current}/{target} mẫu", + "render.live.stopped": "Kết xuất trực tiếp đã dừng", + "render.live.updating": "Trực tiếp · Chất lượng tương tác (tối đa 512 px) · Đang cập nhật", + "render.live.waiting_canvas": "Đang chờ khung vẽ Kết xuất", + "render.live.worker_stopped": "Luồng thu nhận dữ liệu cho kết xuất trực tiếp đã dừng trước khi trả về kết quả" + }, + "zh": { + "render.live.final_changed": "停止实时渲染时渲染请求已更改。请重新开始最终图像渲染。", + "render.live.final_waiting": "正在准备最终图像 · 释放实时渲染资源", + "render.live.invalid_size": "实时渲染需要正的输出宽度和高度。", + "render.live.pause": "暂停实时渲染", + "render.live.paused": "实时 · 已暂停", + "render.live.paused_outdated": "实时 · 已暂停 · 已过时", + "render.live.quality_help": "交互质量:最长边最多为 512 像素。使用所选渲染器及其支持的效果。最终分辨率、设置和导出保持独立。", + "render.live.refused": "实时渲染不可用:{reason}", + "render.live.resume": "恢复实时渲染", + "render.live.samples": "实时 · {width} × {height} · {current}/{target} 次采样", + "render.live.stopped": "实时渲染已停止", + "render.live.updating": "实时 · 交互质量(最多 512 px)· 正在更新", + "render.live.waiting_canvas": "正在等待渲染画布", + "render.live.worker_stopped": "实时渲染捕获工作线程在返回结果之前已停止" + } +} diff --git a/assets/locales/pending/render-native-preparation.json b/assets/locales/pending/render-native-preparation.json new file mode 100644 index 000000000..1c72b1945 --- /dev/null +++ b/assets/locales/pending/render-native-preparation.json @@ -0,0 +1,82 @@ +{ + "en": { + "render.batch_owner_limit": "At most 32 document shot queues can be retained. Finish or cancel an existing queue first.", + "render.batch_preparing": "Preparing next shot", + "render.batch_waiting_worker": "Waiting for render preparation", + "render.preparation_cancelled": "Render preparation cancelled", + "render.preparation_checking": "Checking render", + "render.preparation_retirement_failed": "Render preparation cleanup failed. This window cannot prepare another image.", + "render.preparation_retiring": "Finishing render preparation", + "render.preparation_unavailable": "Render preparation unavailable" + }, + "de": { + "render.batch_owner_limit": "Es können höchstens 32 Dokument-Bildfolgen vorgehalten werden. Schließen Sie zuerst eine vorhandene Folge ab oder brechen Sie sie ab.", + "render.batch_preparing": "Nächste Aufnahme wird vorbereitet", + "render.batch_waiting_worker": "Warten auf die Rendering-Vorbereitung", + "render.preparation_cancelled": "Rendering-Vorbereitung abgebrochen", + "render.preparation_checking": "Rendering wird geprüft", + "render.preparation_retirement_failed": "Die Bereinigung der Rendering-Vorbereitung ist fehlgeschlagen. Dieses Fenster kann kein weiteres Bild vorbereiten.", + "render.preparation_retiring": "Rendering-Vorbereitung wird abgeschlossen", + "render.preparation_unavailable": "Rendering-Vorbereitung nicht verfügbar" + }, + "ja": { + "render.batch_owner_limit": "保持できるドキュメントのショットキューは最大32個です。既存のキューを完了するかキャンセルしてください。", + "render.batch_preparing": "次のショットを準備中", + "render.batch_waiting_worker": "レンダリングの準備待ち", + "render.preparation_cancelled": "レンダリングの準備をキャンセルしました", + "render.preparation_checking": "レンダリングを確認中", + "render.preparation_retirement_failed": "レンダリング準備の後処理に失敗しました。このウィンドウでは別の画像を準備できません。", + "render.preparation_retiring": "レンダリングの準備を終了中", + "render.preparation_unavailable": "レンダリングの準備を利用できません" + }, + "ko": { + "render.batch_owner_limit": "문서 샷 대기열은 최대 32개까지 유지할 수 있습니다. 기존 대기열을 완료하거나 취소하세요.", + "render.batch_preparing": "다음 샷 준비 중", + "render.batch_waiting_worker": "렌더링 준비 대기 중", + "render.preparation_cancelled": "렌더링 준비가 취소되었습니다", + "render.preparation_checking": "렌더링 확인 중", + "render.preparation_retirement_failed": "렌더링 준비 정리에 실패했습니다. 이 창에서는 다른 이미지를 준비할 수 없습니다.", + "render.preparation_retiring": "렌더링 준비 마무리 중", + "render.preparation_unavailable": "렌더링 준비를 사용할 수 없음" + }, + "zh": { + "render.batch_owner_limit": "最多可保留32个文档的镜头队列。请先完成或取消现有队列。", + "render.batch_preparing": "正在准备下一个镜头", + "render.batch_waiting_worker": "等待渲染准备", + "render.preparation_cancelled": "渲染准备已取消", + "render.preparation_checking": "正在检查渲染", + "render.preparation_retirement_failed": "渲染准备清理失败。此窗口无法再准备其他图像。", + "render.preparation_retiring": "正在完成渲染准备", + "render.preparation_unavailable": "渲染准备不可用" + }, + "ar": { + "render.batch_owner_limit": "يمكن الاحتفاظ بقوائم لقطات 32 مستندًا كحد أقصى. أكمل قائمة موجودة أو ألغها أولًا.", + "render.batch_preparing": "جارٍ إعداد اللقطة التالية", + "render.batch_waiting_worker": "في انتظار إعداد التصيير", + "render.preparation_cancelled": "أُلغي إعداد التصيير", + "render.preparation_checking": "جارٍ التحقق من التصيير", + "render.preparation_retirement_failed": "تعذّر تنظيف موارد إعداد التصيير. لا يمكن لهذه النافذة إعداد صورة أخرى.", + "render.preparation_retiring": "جارٍ إنهاء إعداد التصيير", + "render.preparation_unavailable": "إعداد التصيير غير متاح" + }, + "he": { + "render.batch_owner_limit": "ניתן לשמור תורי צילומים של 32 מסמכים לכל היותר. יש להשלים או לבטל תור קיים תחילה.", + "render.batch_preparing": "מכין את הצילום הבא", + "render.batch_waiting_worker": "ממתין להכנת הרינדור", + "render.preparation_cancelled": "הכנת הרינדור בוטלה", + "render.preparation_checking": "בודק רינדור", + "render.preparation_retirement_failed": "ניקוי משאבי הכנת הרינדור נכשל. לא ניתן להכין תמונה נוספת בחלון זה.", + "render.preparation_retiring": "מסיים את הכנת הרינדור", + "render.preparation_unavailable": "הכנת הרינדור אינה זמינה" + }, + "vi": { + "render.batch_owner_limit": "Chỉ có thể giữ hàng đợi cảnh của tối đa 32 tài liệu. Hãy hoàn tất hoặc hủy một hàng đợi hiện có trước.", + "render.batch_preparing": "Đang chuẩn bị cảnh tiếp theo", + "render.batch_waiting_worker": "Đang chờ chuẩn bị kết xuất", + "render.preparation_cancelled": "Đã hủy chuẩn bị kết xuất", + "render.preparation_checking": "Đang kiểm tra kết xuất", + "render.preparation_retirement_failed": "Không thể giải phóng tài nguyên chuẩn bị kết xuất. Cửa sổ này không thể chuẩn bị ảnh khác.", + "render.preparation_retiring": "Đang hoàn tất chuẩn bị kết xuất", + "render.preparation_unavailable": "Không thể chuẩn bị kết xuất" + } +} diff --git a/assets/locales/pending/render-progressive-always-on.json b/assets/locales/pending/render-progressive-always-on.json new file mode 100644 index 000000000..8041b4a71 --- /dev/null +++ b/assets/locales/pending/render-progressive-always-on.json @@ -0,0 +1,58 @@ +{ + "ar": { + "render.cpu_fixed_retained": "تم الاحتفاظ بأخذ العينات الثابت", + "render.cpu_progressive_adopt": "استخدام أخذ العينات التدريجي", + "render.cpu_progressive_adopt_help": "يستخدم أخذ العينات التدريجي عينة كاميرا واحدة لكل تمريرة. يبقى حجم الصورة والأضواء وإعدادات الانعكاس دون تغيير.", + "render.cpu_progressive_always": "أخذ العينات التدريجي مفعّل دائمًا", + "render.cpu_progressive_reflection_adopt": "اضبط محاولات الانعكاس المحددة على 1 قبل تفعيل أخذ العينات التدريجي." + }, + "de": { + "render.cpu_fixed_retained": "Feste Abtastung beibehalten", + "render.cpu_progressive_adopt": "Progressive Abtastung verwenden", + "render.cpu_progressive_adopt_help": "Die progressive Abtastung verwendet ein Kamerasample pro Durchlauf. Bildgröße, Lichtquellen und Reflexionseinstellungen bleiben unverändert.", + "render.cpu_progressive_always": "Progressive Abtastung ist immer aktiv", + "render.cpu_progressive_reflection_adopt": "Setzen Sie die Reflexionsversuche ausgewählter Körper auf 1, bevor Sie die progressive Abtastung übernehmen." + }, + "en": { + "render.cpu_fixed_retained": "Fixed sampling retained", + "render.cpu_progressive_adopt": "Use progressive sampling", + "render.cpu_progressive_adopt_help": "Adopting progressive uses one camera sample per pass. Image size, lights and reflection settings stay unchanged.", + "render.cpu_progressive_always": "Progressive sampling is always on", + "render.cpu_progressive_reflection_adopt": "Set selected reflection attempts to 1 before adopting progressive sampling." + }, + "he": { + "render.cpu_fixed_retained": "הדגימה הקבועה נשמרה", + "render.cpu_progressive_adopt": "שימוש בדגימה הדרגתית", + "render.cpu_progressive_adopt_help": "מעבר לדגימה הדרגתית משתמש בדגימת מצלמה אחת לכל מעבר. גודל התמונה, האורות והגדרות ההחזר נשארים ללא שינוי.", + "render.cpu_progressive_always": "דגימה הדרגתית פעילה תמיד", + "render.cpu_progressive_reflection_adopt": "יש לקבוע את מספר ניסיונות ההחזר שנבחרו ל־1 לפני המעבר לדגימה הדרגתית." + }, + "ja": { + "render.cpu_fixed_retained": "固定サンプリングを維持", + "render.cpu_progressive_adopt": "プログレッシブサンプリングを使用", + "render.cpu_progressive_adopt_help": "切り替えると各パスで1つのカメラサンプルを使用します。画像サイズ、照明、反射設定は変わりません。", + "render.cpu_progressive_always": "プログレッシブサンプリングは常に有効です", + "render.cpu_progressive_reflection_adopt": "切り替える前に、選択した反射の試行回数を1に設定してください。" + }, + "ko": { + "render.cpu_fixed_retained": "고정 샘플링 유지", + "render.cpu_progressive_adopt": "점진적 샘플링 사용", + "render.cpu_progressive_adopt_help": "전환하면 패스마다 카메라 샘플 하나를 사용합니다. 이미지 크기, 조명 및 반사 설정은 유지됩니다.", + "render.cpu_progressive_always": "점진적 샘플링은 항상 켜져 있습니다", + "render.cpu_progressive_reflection_adopt": "전환하기 전에 선택한 반사의 시도 횟수를 1로 설정하세요." + }, + "vi": { + "render.cpu_fixed_retained": "Đã giữ lấy mẫu cố định", + "render.cpu_progressive_adopt": "Dùng lấy mẫu lũy tiến", + "render.cpu_progressive_adopt_help": "Lấy mẫu lũy tiến sử dụng một mẫu máy ảnh cho mỗi lượt. Kích thước ảnh, nguồn sáng và thiết lập phản xạ không thay đổi.", + "render.cpu_progressive_always": "Lấy mẫu lũy tiến luôn bật", + "render.cpu_progressive_reflection_adopt": "Đặt số lần thử phản xạ đã chọn thành 1 trước khi chuyển sang lấy mẫu lũy tiến." + }, + "zh": { + "render.cpu_fixed_retained": "保留固定采样", + "render.cpu_progressive_adopt": "使用渐进采样", + "render.cpu_progressive_adopt_help": "启用后每轮使用一个相机样本。图像大小、灯光和反射设置保持不变。", + "render.cpu_progressive_always": "渐进采样始终开启", + "render.cpu_progressive_reflection_adopt": "启用渐进采样前,请将所选反射的尝试次数设为1。" + } +} diff --git a/assets/locales/pending/render-quality-budget.json b/assets/locales/pending/render-quality-budget.json new file mode 100644 index 000000000..7c317254b --- /dev/null +++ b/assets/locales/pending/render-quality-budget.json @@ -0,0 +1,42 @@ +{ + "ar": { + "render.quality_budget_help": "يضبط الحجم والعينات والعمق والبذرة وتقليل التشويش. تُحفظ إعدادات الصورة الأخرى.", + "render.quality_denoise_off": "تقليل التشويش: متوقف", + "render.quality_denoise_on": "تقليل التشويش: مفعّل" + }, + "de": { + "render.quality_budget_help": "Legt Größe, Samples, Tiefe, Startwert und Rauschreduzierung fest. Andere Bildeinstellungen bleiben erhalten.", + "render.quality_denoise_off": "Rauschreduzierung: Aus", + "render.quality_denoise_on": "Rauschreduzierung: Ein" + }, + "en": { + "render.quality_budget_help": "Sets size, samples, depth, seed and noise reduction. Other image settings are kept.", + "render.quality_denoise_off": "Noise reduction: Off", + "render.quality_denoise_on": "Noise reduction: On" + }, + "he": { + "render.quality_budget_help": "קובע גודל, דגימות, עומק, זרע והפחתת רעש. הגדרות התמונה האחרות נשמרות.", + "render.quality_denoise_off": "הפחתת רעש: כבויה", + "render.quality_denoise_on": "הפחתת רעש: פעילה" + }, + "ja": { + "render.quality_budget_help": "サイズ、サンプル数、深度、シード、ノイズ低減を設定します。他の画像設定は維持されます。", + "render.quality_denoise_off": "ノイズ低減:オフ", + "render.quality_denoise_on": "ノイズ低減:オン" + }, + "ko": { + "render.quality_budget_help": "크기, 샘플 수, 깊이, 시드 및 노이즈 제거를 설정합니다. 다른 이미지 설정은 유지됩니다.", + "render.quality_denoise_off": "노이즈 제거: 꺼짐", + "render.quality_denoise_on": "노이즈 제거: 켜짐" + }, + "vi": { + "render.quality_budget_help": "Đặt kích thước, số mẫu, độ sâu, hạt giống và giảm nhiễu. Giữ nguyên các thiết lập ảnh khác.", + "render.quality_denoise_off": "Giảm nhiễu: Tắt", + "render.quality_denoise_on": "Giảm nhiễu: Bật" + }, + "zh": { + "render.quality_budget_help": "设置尺寸、采样数、深度、种子和降噪。其他图像设置保持不变。", + "render.quality_denoise_off": "降噪:关闭", + "render.quality_denoise_on": "降噪:开启" + } +} diff --git a/assets/locales/pending/render-quality-summary.json b/assets/locales/pending/render-quality-summary.json new file mode 100644 index 000000000..49f5d0061 --- /dev/null +++ b/assets/locales/pending/render-quality-summary.json @@ -0,0 +1,26 @@ +{ + "ar": { + "render.quality_summary": "{width} × {height} · {samples} عينة · العمق {depth} · البذرة {seed} · {denoise}" + }, + "de": { + "render.quality_summary": "{width} × {height} · {samples} Samples · Tiefe {depth} · Startwert {seed} · {denoise}" + }, + "en": { + "render.quality_summary": "{width} × {height} · {samples} samples · depth {depth} · seed {seed} · {denoise}" + }, + "he": { + "render.quality_summary": "{width} × {height} · {samples} דגימות · עומק {depth} · זרע {seed} · {denoise}" + }, + "ja": { + "render.quality_summary": "{width} × {height} · {samples} サンプル · 深度 {depth} · シード {seed} · {denoise}" + }, + "ko": { + "render.quality_summary": "{width} × {height} · 샘플 {samples}개 · 깊이 {depth} · 시드 {seed} · {denoise}" + }, + "vi": { + "render.quality_summary": "{width} × {height} · {samples} mẫu · độ sâu {depth} · hạt giống {seed} · {denoise}" + }, + "zh": { + "render.quality_summary": "{width} × {height} · {samples} 次采样 · 深度 {depth} · 种子 {seed} · {denoise}" + } +} diff --git a/assets/locales/pending/render-source-badge.json b/assets/locales/pending/render-source-badge.json new file mode 100644 index 000000000..c50d04593 --- /dev/null +++ b/assets/locales/pending/render-source-badge.json @@ -0,0 +1,50 @@ +{ + "ar": { + "render.live.source_current": "{method} · مباشر", + "render.live.source_outdated": "{method} · الصورة السابقة", + "render.live.source_outdated_help": "يعرض آخر صورة ملتقطة أثناء تحديث التصيير المباشر أو عند عدم توفره. قد تختلف عن المشهد أو إعدادات الصورة الحالية.", + "render.live.source_settings_help": "افتح «الإخراج» لتعديل المصيّر وإعدادات الصورة." + }, + "de": { + "render.live.source_current": "{method} · Live", + "render.live.source_outdated": "{method} · Vorheriges Bild", + "render.live.source_outdated_help": "Zeigt das zuletzt aufgenommene Bild, während das Live-Rendering aktualisiert wird oder nicht verfügbar ist. Es kann von der aktuellen Szene oder den Bildeinstellungen abweichen.", + "render.live.source_settings_help": "Ausgabe öffnen, um Renderer und Bildeinstellungen zu bearbeiten." + }, + "en": { + "render.live.source_current": "{method} · Live", + "render.live.source_outdated": "{method} · Previous image", + "render.live.source_outdated_help": "Shows the last captured image while live rendering updates or is unavailable. It may differ from the current scene or image settings.", + "render.live.source_settings_help": "Open Output to edit the renderer and image settings." + }, + "he": { + "render.live.source_current": "{method} · חי", + "render.live.source_outdated": "{method} · תמונה קודמת", + "render.live.source_outdated_help": "מציג את התמונה האחרונה שנלכדה בזמן שההדמיה החיה מתעדכנת או אינה זמינה. היא עשויה להיות שונה מהסצנה או מהגדרות התמונה הנוכחיות.", + "render.live.source_settings_help": "יש לפתוח את חלונית הפלט כדי לערוך את מנוע ההדמיה ואת הגדרות התמונה." + }, + "ja": { + "render.live.source_current": "{method} · ライブ", + "render.live.source_outdated": "{method} · 前の画像", + "render.live.source_outdated_help": "ライブレンダリングの更新中や利用できない間は、最後に取得した画像を表示します。現在のシーンや画像設定とは異なる場合があります。", + "render.live.source_settings_help": "出力を開いてレンダラーと画像設定を編集します。" + }, + "ko": { + "render.live.source_current": "{method} · 라이브", + "render.live.source_outdated": "{method} · 이전 이미지", + "render.live.source_outdated_help": "라이브 렌더링이 업데이트 중이거나 사용할 수 없는 동안 마지막으로 캡처한 이미지를 표시합니다. 현재 장면 또는 이미지 설정과 다를 수 있습니다.", + "render.live.source_settings_help": "출력을 열어 렌더러와 이미지 설정을 편집합니다." + }, + "vi": { + "render.live.source_current": "{method} · Trực tiếp", + "render.live.source_outdated": "{method} · Ảnh trước", + "render.live.source_outdated_help": "Hiển thị ảnh đã chụp gần nhất trong khi kết xuất trực tiếp đang cập nhật hoặc không khả dụng. Ảnh có thể khác cảnh hoặc thiết lập ảnh hiện tại.", + "render.live.source_settings_help": "Mở mục Đầu ra để sửa bộ kết xuất và thiết lập ảnh." + }, + "zh": { + "render.live.source_current": "{method} · 实时", + "render.live.source_outdated": "{method} · 上一幅图像", + "render.live.source_outdated_help": "实时渲染更新或不可用时显示上次捕获的图像。它可能与当前场景或图像设置不同。", + "render.live.source_settings_help": "打开输出以编辑渲染器和图像设置。" + } +} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 40c9623f7..31a327149 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -3020,9 +3020,9 @@ "render.adaptive_absolute": "Ngưỡng lỗi RGB tuyệt đối", "render.adaptive_coverage": "Mục tiêu lỗi độ phủ (Coverage error)", "render.adaptive_enable": "Phân bổ mẫu bằng các mẫu thử độc lập", - "render.adaptive_help": "Chỉ dành cho GPU. Các mẫu thử độc lập sẽ bị loại bỏ, sau đó phân bổ tối thiểu 16 mẫu chính thức trên mỗi pixel cho đến khi đạt giới hạn mẫu. Phương sai RGB và độ phủ chỉ dùng để định hướng phân bổ; các đường truyền tia hiếm có thể bị bỏ sót và pixel đạt giới hạn vẫn có thể còn nhiễu. Báo cáo cuối cùng ghi nhận khối lượng tính toán thực tế. Không đảm bảo tuyệt đối về độ nhiễu hay thời gian.", + "render.adaptive_help": "Các mẫu thăm dò độc lập được loại bỏ, sau đó chọn ít nhất 16 mẫu sản xuất cho mỗi điểm ảnh, tối đa bằng Số mẫu mỗi điểm ảnh. Giới hạn tài nguyên CPU bao gồm cả hai giai đoạn. Phương sai RGB và độ phủ hướng dẫn phân bổ; điểm ảnh đạt trần vẫn có thể nhiễu. Báo cáo cuối đếm số mẫu thực tế.", "render.adaptive_minimum": "Số mẫu chính thức tối thiểu", - "render.adaptive_pending": "GPU hỗ trợ phân bổ thích ứng qua mẫu thử độc lập và phân tầng Fresnel có điều kiện. Chưa hỗ trợ kiểm định hội tụ, đảm bảo sự kiện hiếm và truyền dẫn thích ứng trên CPU.", + "render.adaptive_pending": "Phân bổ thích ứng bằng mẫu thăm dò độc lập có trên CPU và GPU. Các tầng Fresnel có điều kiện cần GPU. Phân bổ thống kê không chứng nhận sự hội tụ.", "render.adaptive_pilots": "Số mẫu thử trên mỗi pixel", "render.adaptive_relative": "Mục tiêu lỗi RGB tương đối", "render.add_ground": "Thêm mặt sàn khớp vào thiết lập", @@ -3083,7 +3083,7 @@ "render.appearance_editor.replace": "Thay thuộc tính quang học đã lưu của thân này", "render.appearance_editor.revalidate": "Kiểm tra lại thân này", "render.appearance_editor.save": "Lưu các thuộc tính quang học này", - "render.appearance_editor.save_reason": "Lưu các thuộc tính quang học này cần kính vật lý trên một thân GPU hiện hành. Lớp phủ và bản đồ ảnh cục bộ vẫn tạm thời.", + "render.appearance_editor.save_reason": "Để lưu Kính, hãy bật nó trên thân CPU hoặc GPU hiện hành. Với lớp phủ bóng, dùng Lưu lớp phủ vào cảnh chụp. Các tệp ảnh cục bộ vẫn tạm thời.", "render.appearance_editor.saved": "Lưu cùng cảnh chụp này", "render.appearance_editor.saved_state": "Các thuộc tính quang học này được lưu cùng cảnh chụp này.", "render.appearance_editor.scatter_reason": "Tán xạ bên trong cần biên là khối đặc kín.", @@ -3179,7 +3179,7 @@ "render.children.copy_request": "Sao chép JSON yêu cầu", "render.children.coverage_error": "Sai số độ phủ", "render.children.cpu": "Dò tia bằng CPU", - "render.children.denoise": "Giảm nhiễu trong ảnh hoàn chỉnh", + "render.children.denoise": "Giảm nhiễu ảnh", "render.children.depth": "Độ sâu đường đi", "render.children.distortion": "Méo", "render.children.edge_samples": "Mẫu cạnh", @@ -3311,7 +3311,7 @@ "render.cpu_point_help": "Tối đa tám nguồn sáng điểm, được bổ sung vào ánh sáng định hướng đã chọn. Khoảng cách tính bằng mm; khoảng cách tối thiểu không được vượt quá khoảng cách tham chiếu.", "render.cpu_primary_samples": "Số mẫu cạnh trên mỗi pixel", "render.cpu_progressive": "Kết xuất lũy tiến trên CPU", - "render.cpu_progressive_help": "Tích lũy bộ tích phân CPU hiện có theo từng lượt một mẫu chính. Các phản xạ đã chọn yêu cầu một mẫu; nguồn sáng vùng, chất điện môi và bất đẳng hướng yêu cầu chế độ 'Hình ảnh đơn'.", + "render.cpu_progressive_help": "Tích lũy các mẫu máy ảnh CPU mới và hiển thị từng lượt hoàn chỉnh. Phản xạ được chọn dùng một lần thử cho mỗi mẫu máy ảnh; kính được chứng nhận và dị hướng phẳng giữ các giới hạn hiện có. Mẫu thăm dò và mẫu sản xuất thích ứng dùng chung ngân sách cấu hình CPU.", "render.cpu_progressive_limits": "Tối đa 1.048.576 pixel và tổng số tính toán (pixel × mẫu) không quá 16.777.216. Thay đổi số mẫu không bao giờ tự động đổi kích thước ảnh.", "render.cpu_progressive_seed": "Hạt giống lấy mẫu CPU", "render.cpu_progressive_spp": "Mẫu trên mỗi pixel", @@ -3487,7 +3487,7 @@ "render.export_display": "Xuất: ảnh PNG hiển thị", "render.export_image_label": "Xuất ảnh", "render.export_linear": "Xuất: ảnh EXR tuyến tính thô", - "render.exr_pending": "GPU có thể giữ lại tệp EXR tuyến tính thô. Tính năng nén, ảnh nhiều lớp và các kênh kết xuất phụ trợ vẫn chưa được triển khai.", + "render.exr_pending": "Dò tia trên CPU và dò đường đi trên GPU có thể giữ lại EXR tuyến tính thô. Tính năng nén, ảnh nhiều lớp và các lượt kết xuất phụ trợ vẫn chưa khả dụng.", "render.film_grain": "Hạt nhiễu nhiếp ảnh (Film Grain)", "render.fit": "Thu phóng vừa sản phẩm", "render.fixed_camera": "Máy ảnh", @@ -3850,7 +3850,7 @@ "render.method_cpu": "Dò tia trên CPU", "render.method_gpu": "Dò đường truyền tia trên GPU (Path Tracing)", "render.method_limit_raster": "Quét mảng (Raster) dùng bản xem trước studio đục cố định. Chọn phương thức dò tia rõ ràng để dùng các điều khiển quang học được hỗ trợ.", - "render.method_raster": "Quét mảng CPU (Raster)", + "render.method_raster": "Raster trên CPU (dạng sơ đồ)", "render.navigation_help": "Camera di chuyển tương tự như trong Thiết kế (Tùy chọn cài đặt › Điều hướng). Lưu thiết lập sẽ ghi lại camera hiện tại.", "render.nested_enable": "Chất điện môi lồng nhau đã xác thực", "render.nested_help": "Tối đa 16 lớp chứa nhau; mỗi khối cha phải là khối lồi và mọi khối con phải nằm hoàn toàn bên trong. Từ chối giao cắt, bề mặt tiếp xúc, tấm mỏng và bóng đổ thẳng. Trạng thái camera bên trong tuân theo hệ thống phân cấp đã xác thực. Không tạo bề mặt chất lỏng hoặc hợp nhất các ranh giới CAD tiếp xúc.", @@ -3878,7 +3878,7 @@ "render.output_exr_unavailable": "Thiết lập đầu ra EXR không khả dụng ở đây. Xuất EXR tuyến tính cần ảnh GPU đã hoàn tất với bản gốc tuyến tính được giữ lại.", "render.output_fit": "Vừa khít", "render.output_format": "Định dạng", - "render.output_format_status": "PNG là hình ảnh hiển thị hoàn chỉnh chính xác. EXR tùy chọn trên GPU giữ lại suất bức xạ FLOAT32 tuyến tính cảnh thô trước các bộ lọc hiển thị. Xuất không bao giờ thay thế bằng bộ nhớ đệm xem trước hoặc tác vụ khác.", + "render.output_format_status": "PNG là ảnh hiển thị hoàn chỉnh chính xác. EXR tùy chọn trên CPU hoặc GPU giữ lại suất bức xạ FLOAT32 thô trong không gian tuyến tính của cảnh trước các bộ lọc hiển thị. Xuất không bao giờ thay thế ảnh bằng bộ nhớ đệm xem trước hoặc tác vụ khác.", "render.output_grading": "Chỉnh màu", "render.output_image": "Ảnh", "render.output_largest": "Tối đa {width} × {height}", @@ -3963,7 +3963,7 @@ "render.quality_custom": "Tùy chỉnh", "render.quality_draft": "Bản nháp", "render.quality_high": "Cao", - "render.quality_projection_help": "Các thiết lập sẵn Q bao gồm các yêu cầu tương lai. Hành động này chỉ chiếu định mức mẫu PNG cố định được hỗ trợ và lược bỏ rõ ràng việc dừng thích ứng, đầu ra tuyến tính thô và các giới hạn truyền dẫn độc lập.", + "render.quality_projection_help": "Bản xem xét này chỉ thay đổi độ phân giải, ngân sách mẫu, độ sâu đường đi, hạt giống và giảm nhiễu. Các thiết lập khác được giữ nguyên; ngân sách không chứng nhận ảnh đã hội tụ.", "render.quality_review": "Xem xét định mức lấy mẫu", "render.queue_pending": "Không có hàng đợi sản xuất tự động hay bộ kết xuất hoạt hình trong giao diện này. Ảnh tĩnh đã hoàn thành vẫn có thể xuất riêng lẻ.", "render.radial_assign": "Gán diện mạo", @@ -3994,7 +3994,7 @@ "render.result_navigation": "Thu phóng và lia theo tùy chọn Điều hướng. Nhấn phím cách + kéo rê để lia.", "render.result_open": "Mở hình ảnh đã hoàn thành trong khung vẽ chính.", "render.result_preview": "Xem trước trực tiếp", - "render.result_provisional": "Hình ảnh CPU tạm thời", + "render.result_provisional": "Ảnh tạm", "render.result_provisional_help": "Điểm kiểm tra trung gian này không thể xuất. Lệnh xuất giữ lại kết quả hoàn thành gần nhất; hủy bỏ sẽ quay lại kết quả đó.", "render.result_reduced_display": "Bản xem trước hiển thị bị thu nhỏ theo giới hạn bộ nhớ đệm/thiết bị của khung nhìn. Tệp PNG được giữ lại và tệp xuất vẫn giữ nguyên độ phân giải đầy đủ; chế độ kiểm tra gốc 100% không khả dụng cho chế độ xem thu nhỏ này.", "render.result_retained": "Đang hiển thị hình ảnh hoàn thành gần nhất; kết xuất mới hơn chưa thay thế nó.", @@ -4159,7 +4159,7 @@ "render.stage_panels.prepare_plan": "Chuẩn bị kế hoạch tạo", "render.stage_panels.projects": "Chiếu", "render.stage_panels.quality_ack": "Tôi xác nhận ngân sách cố định và các mục bị lược bỏ", - "render.stage_panels.quality_omissions": "Dừng thích ứng và mục tiêu sai số, độ sâu truyền dẫn riêng, quy tắc roulette Nga, đầu ra tuyến tính thô, bản gốc EXR và chứng nhận hội tụ.", + "render.stage_panels.quality_omissions": "Ngân sách này không đặt mục tiêu sai số thích ứng, giới hạn truyền sáng độc lập, quy tắc roulette Nga hay việc lưu giữ bản gốc thô, và không bảo đảm ảnh hội tụ.", "render.stage_panels.reference": "Tham chiếu", "render.stage_panels.references": "Các tham chiếu", "render.stage_panels.remove_optics": "Xóa cài đặt quang học", @@ -4203,7 +4203,7 @@ "render.stage_panels.subtitle_environment": "Môi trường HDR nguyên bản · toàn bộ cảnh", "render.stage_panels.subtitle_maps": "Bản đồ không gian đã tạo · xem trước tạm thời", "render.stage_panels.subtitle_physical": "Kế hoạch chỉ đọc · không tạo hay gán vật liệu", - "render.stage_panels.subtitle_quality": "Ngân sách GPU cố định · lược bỏ các yêu cầu tương lai", + "render.stage_panels.subtitle_quality": "Ngân sách lấy mẫu GPU · chỉ các trường được liệt kê", "render.stage_panels.subtitle_rig": "Bộ đèn chiếu sáng đã thiết kế · bộ phát sáng và tấm thụ động", "render.stage_panels.subtitle_saved_maps": "Bản đồ đã tạo · lưu cùng khung hình này", "render.stage_panels.subtitle_stage": "Mặt sàn và sân khấu vật lý · khớp với sản phẩm", @@ -4228,7 +4228,7 @@ "render.studio_area_help": "Tối đa bốn hình chữ nhật một mặt. Nửa cạnh trực giao U và V xác định kích thước; U × V hướng về phía chiếu sáng. Tọa độ tính theo milimét không gian thế giới.", "render.studio_center": "Tâm X, Y, Z (mm)", "render.studio_denoise": "Giảm nhiễu trong ảnh thành phẩm", - "render.studio_denoise_help": "Bộ lọc cuối cùng bảo toàn cạnh; chi tiết tinh xảo có thể bị làm mềm. Thủy tinh và bề mặt phản xạ gương sắc nét bỏ qua bộ lọc này.", + "render.studio_denoise_help": "Ảnh lũy tiến và ảnh cuối sử dụng bộ lọc bảo toàn biên; chi tiết nhỏ có thể bị làm mềm. Kính và bề mặt phản xạ sắc nét không qua bộ lọc này.", "render.studio_direction": "Hướng về phía mặt trời (X, Y, Z)", "render.studio_environment": "Môi trường", "render.studio_environment_bounds": "Góc xoay môi trường phải hữu hạn trong khoảng ±1.000.000 radian và cường độ từ 0 đến 100.", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index d3c71982d..e3a176288 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -3020,9 +3020,9 @@ "render.adaptive_absolute": "RGB 绝对误差下限", "render.adaptive_coverage": "覆盖率误差目标", "render.adaptive_enable": "使用独立预采样分配样本", - "render.adaptive_help": "仅限 GPU。丢弃独立预采样后,每像素分配至少16个正式样本,最多达到每像素样本数上限。RGB 和覆盖率方差仅用于指导分配;可能遗漏罕见路径,达到上限后仍可能有噪声。最终报告记录实际工作量,不保证噪声或耗时。", + "render.adaptive_help": "独立的先导样本会被丢弃,随后为每个像素分配至少16个、不超过“每像素样本数”的正式样本。CPU资源限制包含两个阶段。RGB与覆盖率方差决定分配,达到上限的像素仍可能有噪点。最终报告记录实际样本数。", "render.adaptive_minimum": "最少正式样本数", - "render.adaptive_pending": "GPU 支持独立预采样自适应分配和条件菲涅耳分层。尚不支持认证收敛、罕见事件保证及 CPU 自适应光传输。", + "render.adaptive_pending": "CPU和GPU均支持独立先导样本的自适应分配。条件菲涅耳分层需要GPU。统计分配不保证收敛。", "render.adaptive_pilots": "每像素预采样数", "render.adaptive_relative": "RGB 相对误差目标", "render.add_ground": "向设置添加适配地面", @@ -3083,7 +3083,7 @@ "render.appearance_editor.replace": "替换此实体已保存的光学设置", "render.appearance_editor.revalidate": "重新验证此实体", "render.appearance_editor.save": "保存这些光学设置", - "render.appearance_editor.save_reason": "保存需要当前 GPU 实体上的物理玻璃。清漆和本地图像贴图仍为临时设置。", + "render.appearance_editor.save_reason": "要保存玻璃,请在当前CPU或GPU实体上启用它。清漆请使用“将清漆保存到镜头”。本地图像文件仍为临时设置。", "render.appearance_editor.saved": "随此镜头保存", "render.appearance_editor.saved_state": "这些光学设置已随此镜头保存。", "render.appearance_editor.scatter_reason": "内部散射需要封闭实体边界。", @@ -3179,7 +3179,7 @@ "render.children.copy_request": "复制请求JSON", "render.children.coverage_error": "覆盖误差", "render.children.cpu": "CPU光线追踪", - "render.children.denoise": "降低成品图像噪点", + "render.children.denoise": "降低图像噪点", "render.children.depth": "路径深度", "render.children.distortion": "畸变", "render.children.edge_samples": "边缘采样", @@ -3311,7 +3311,7 @@ "render.cpu_point_help": "最多可在所选平行光照明基础上添加8个点光源。距离单位为mm,最小距离不得大于参考距离。", "render.cpu_primary_samples": "每像素边缘采样", "render.cpu_progressive": "CPU渐进渲染", - "render.cpu_progressive_help": "使用现有CPU积分器,每轮累积一个主采样。所选反射需要单采样;面光源、电介质和各向异性需要固定图像模式。", + "render.cpu_progressive_help": "累积新的CPU相机样本并显示每个完整的渲染轮次。选定反射在每个相机样本中尝试一次;经认证的玻璃和平面各向异性保留原有限制。自适应先导样本和正式样本共享CPU配置预算。", "render.cpu_progressive_limits": "最多1,048,576像素,像素×采样总数不超过16,777,216。更改采样数不会自动调整图像尺寸。", "render.cpu_progressive_seed": "CPU采样种子", "render.cpu_progressive_spp": "每像素采样数", @@ -3487,7 +3487,7 @@ "render.export_display": "导出:显示 PNG", "render.export_image_label": "导出图像", "render.export_linear": "导出:原始线性 EXR", - "render.exr_pending": "GPU 可保留线性 EXR;压缩、多层和辅助通道仍未实现。", + "render.exr_pending": "CPU 光线追踪和 GPU 路径追踪可保留原始线性 EXR;压缩、多层和辅助通道仍未实现。", "render.film_grain": "摄影颗粒", "render.fit": "适配产品视图", "render.fixed_camera": "相机", @@ -3850,7 +3850,7 @@ "render.method_cpu": "CPU 光线追踪", "render.method_gpu": "GPU 路径追踪", "render.method_limit_raster": "光栅化使用固定的不透明工作室预览;要使用受支持的光学控件,请明确选择光线追踪方式。", - "render.method_raster": "CPU 光栅", + "render.method_raster": "CPU 光栅(示意图)", "render.navigation_help": "相机的操作与设计中相同(首选项 › 导航)。保存设置会记录当前相机。", "render.nested_enable": "经验证的嵌套介质", "render.nested_help": "最多16层包含关系。父体必须凸,子体必须严格位于内部。拒绝相交、接触、薄片和直线透射阴影。内部相机使用经验证的层次结构。不会创建液面或合并接触的CAD边界。", @@ -3878,7 +3878,7 @@ "render.output_exr_unavailable": "此处无法设置 EXR 输出。线性 EXR 导出需要保留线性母版的已完成 GPU 图像。", "render.output_fit": "适合窗口", "render.output_format": "格式", - "render.output_format_status": "PNG 是完成的显示图像。可选 GPU EXR 保留显示滤镜前的原始线性 FLOAT32 辐亮度;导出不会替换成预览缓存或其他任务。", + "render.output_format_status": "PNG 是完成的显示图像。可选 CPU/GPU EXR 保留显示滤镜前的原始线性 FLOAT32 辐亮度;导出不会替换成预览缓存或其他任务。", "render.output_grading": "调色", "render.output_image": "图像", "render.output_largest": "{width} × {height} 最大", @@ -3963,7 +3963,7 @@ "render.quality_custom": "自定义", "render.quality_draft": "草稿", "render.quality_high": "高", - "render.quality_projection_help": "Q 预设包含未来需求。此操作仅映射受支持的固定样本 PNG 预算,明确省略自适应停止、原始线性输出和独立透射限制。", + "render.quality_projection_help": "此检查仅更改分辨率、采样预算、路径深度、种子和降噪。其他设置保持不变,预算不保证收敛。", "render.quality_review": "审阅采样预算", "render.queue_pending": "此界面没有自动生产队列或动画渲染器;已完成的静止图像仍可单独导出。", "render.radial_assign": "指定外观", @@ -3994,7 +3994,7 @@ "render.result_navigation": "平移和缩放遵循导航设置。按住空格键并拖动可平移。", "render.result_open": "在主画布中打开已完成的图像。", "render.result_preview": "实时预览", - "render.result_provisional": "CPU临时图像", + "render.result_provisional": "临时图像", "render.result_provisional_help": "此中间结果无法导出。导出始终使用最后完成的结果;取消后会返回该结果。", "render.result_reduced_display": "显示预览已缩小到视口设备或缓存限制。保留的 PNG 和导出仍为完整分辨率;此缩小视图不能进行原生 100% 检查。", "render.result_retained": "正在显示最后完成的图像;较新的渲染尚未替换它。", @@ -4159,7 +4159,7 @@ "render.stage_panels.prepare_plan": "准备创建计划", "render.stage_panels.projects": "投影", "render.stage_panels.quality_ack": "我确认此固定预算及其省略内容", - "render.stage_panels.quality_omissions": "自适应停止和误差目标、独立透射深度、俄罗斯轮盘规则、原始线性输出、EXR 母版及收敛认证。", + "render.stage_panels.quality_omissions": "此预算不设置自适应误差目标、独立透射限制、俄罗斯轮盘规则或线性母版保留,也不保证收敛。", "render.stage_panels.reference": "参考", "render.stage_panels.references": "参考", "render.stage_panels.remove_optics": "移除光学设置", @@ -4203,7 +4203,7 @@ "render.stage_panels.subtitle_environment": "原创 HDR 环境 · 整个场景", "render.stage_panels.subtitle_maps": "创作的空间贴图 · 临时预览", "render.stage_panels.subtitle_physical": "只读计划 · 未创建或分配材料", - "render.stage_panels.subtitle_quality": "固定 GPU 预算 · 省略未来要求", + "render.stage_panels.subtitle_quality": "GPU 采样预算 · 仅更改列出的设置", "render.stage_panels.subtitle_rig": "创作的灯光装置 · 发光体和被动卡片", "render.stage_panels.subtitle_saved_maps": "创作的贴图 · 保存在此镜头中", "render.stage_panels.subtitle_stage": "物理地面和舞台 · 适配产品", @@ -4228,7 +4228,7 @@ "render.studio_area_help": "最多四个单面矩形。正交半边 U 和 V 定义尺寸;U × V 指向发光侧。坐标采用世界空间毫米。", "render.studio_center": "中心 X, Y, Z(mm)", "render.studio_denoise": "降低最终图像噪点", - "render.studio_denoise_help": "最终滤波保留边缘,但可能柔化细节。玻璃与锐利镜面不参与滤波。", + "render.studio_denoise_help": "渐进图像和最终图像使用保留边缘的滤波,但可能柔化细节。玻璃与锐利镜面不参与滤波。", "render.studio_direction": "朝向太阳的方向 (X, Y, Z)", "render.studio_environment": "环境", "render.studio_environment_bounds": "环境旋转必须为±1,000,000弧度以内的有限值,强度必须在0至100之间。", diff --git a/crates/doc/src/format/pending/cpu-output-presentation.rs b/crates/doc/src/format/pending/cpu-output-presentation.rs new file mode 100644 index 000000000..4500e69df --- /dev/null +++ b/crates/doc/src/format/pending/cpu-output-presentation.rs @@ -0,0 +1,91 @@ +//! CPU render jobs can save optional `options.output` presentation: tone map, finishing, +//! backdrop and raw linear EXR retention. Older designs omit it and retain the exact previous +//! f64 PNG output; exposure remains owned by RenderSetup. Readers missing these changes open +//! the newer design with a warning and preserve saved values they cannot read. +//! CPU jobs also save optional `options.lens` using the shared physical thin-lens +//! aperture radius and axial focus distance. Positive aperture requires perspective +//! plus explicit progressive camera sampling; absent/zero aperture keeps old pixels. +//! CPU raytrace jobs also retain default-false `transparent_background` beside options. +//! It exports straight-alpha primary geometry coverage; absent fields keep opaque PNGs. +//! CPU jobs also save opt-in `options.denoise`; omission/false preserves the prior +//! raw PNG calculation. Every complete published pass is filtered without changing +//! raw film or the final unfiltered EXR. Older files need no rewrite for this flag. +//! CPU jobs also preserve optional `options.path: {max_depth: 1..16}` for explicit +//! progressive diffuse/specular transport and certified Glass boundaries. The depth +//! counts shaded surfaces, optical boundaries and active scattering events. Traced shadows are required; +//! selected reflection/anisotropy overrides and unsupported closed-Glass +//! shadow connections refuse with authored intent retained. Omission keeps the legacy producer. +//! +//! CPU raytrace jobs save optional `options.aging` using the existing ordered +//! SavedAgingStack schema and stable definition/feature/component/occurrence targets. +//! Empty/absent stacks preserve prior saved JSON, CPU pixel arithmetic and work. +//! Check and Start resolve stable targets against the captured scene; stale/hidden +//! targets are refused rather than made global. Captured indices/names remain +//! runtime-only. Aging changes the opaque BRDF before lighting and denoising guides; +//! it does not change geometry, emission, physical materials or mass. Certified +//! glass targets and passive stages remain excluded; independently authored anisotropic axes +//! cannot be replaced by scalar aging roughness and are refused explicitly. +//! +//! Saves up to eight hard GPU directional sources alongside the existing optional +//! finite Sun (eight combined). Older designs omit the new list and retain their +//! exact implicit studio or finite-Sun lighting. Readers missing the new list warn +//! about the newer design and preserve these unread sources. +//! Also saves up to eight GPU point/spot sources with exact world-mm positions, +//! reference/minimum distances and optional world-axis/radian half cones. Missing +//! punctual lists stay empty. CPU cone intent retains its wider f64 domain; GPU +//! cone feathers below the documented precision bound refuse without rewriting. +//! +//! CPU jobs may also consume the existing portable saved `surfaces` bindings for +//! opaque built-in base color, roughness, metallic and normal maps. No new map +//! schema is added; raster and unsupported CPU optical combinations refuse the +//! authored bindings instead of dropping them. Old files without maps keep the +//! old CPU allocation/work/pixel path. +//! CPU jobs also save optional `options.adaptive` using the existing independent-pilot +//! policy. Explicit progressive production sampling is required; the unchanged CPU +//! profile budgets pilots plus the production cap. Exact per-pixel counts and pilot +//! statistics stay runtime-only; final SamplingReport and PreviewInfo.adaptive reuse +//! the existing metadata contract without changing linear-master schema/channels. + +//! CPU `options.path` may consume the existing saved ClosedMesh optical boundary +//! after exact f64 edge, vertex-link, embedding/contact, outward and conservative +//! nested-parent certification. Runtime-only ClosedMesh and thin-shadow lowering +//! preserve stable authored optics. No new saved field or geometry repair is added. +//! Absent-path sheet/box transport and default serialized bytes remain unchanged. +//! Closed-shadow connections, Glass combined with external volume and selected +//! reflection/anisotropy combinations refuse explicitly with authored values retained. +//! Perspective CPU Path captures classify each physical eye/pupil cooperatively +//! against the certified boundaries and initialize the nested Beer medium stack. +//! Exact origin/near-clip boundary contacts refuse without changing saved cameras +//! or optics. This runtime-only extension adds no serialized field. +//! Existing saved OpticalMaterial.subsurface may also lower to optional captured +//! CPU dielectric subsurface parameters with explicit progressive Path. Selected +//! certified closed media use scalar free flight, HG directions and separate Beer +//! absorption, including physical eye/pupil starts and nested current media. No +//! refracting-boundary next-event approximation is added. Active scattering and +//! surface denoising refuse together; unsupported thin/legacy routes retain intent. +//! Some(rate0) remains serialized but adds no collision work/RNG or pixel change. +//! CPU jobs may also preserve optional options.volume using the same bounded +//! HomogeneousVolume world-box/extinction/RGB albedo/HG contract as GPU Atmosphere. +//! Positive extinction requires explicit progressive Path and disables no existing +//! option implicitly: Glass/SSS and surface denoising refuse with intent retained. +//! Absent/zero volume keeps the original transport work/RNG/heap owner count/pixels. +//! Inline intent's actual fixed retained-request size is prepaid even when absent; +//! regrade owns its separate header reservation until its last status handle drops. +//! Physical eye/pupil prefixes and the orthographic signed line/box union do not +//! alter saved camera/framing/model bounds or its model near interval. Existing +//! ray-distance/profile/task/frame/codec/host caps remain unchanged. + +//! CPU jobs also retain optional `sun` and `sky` intent. `sun` reuses the shared +//! finite-cap direction/angular-radius/radiance domain; `sky` reuses the portable +//! gradient/rotation/intensity schema. Both require explicit CPU Path transport. +//! Omitted fields preserve old designs and the absent producer allocation/work/RNG +//! path. Constant, Sky and HDR sources are exclusive; finite Sun is additive. +//! No generated sky image or runtime resource is serialized. +//! +//! CPU and GPU jobs also save `coats`, up to the existing 64 runtime coat target +//! bound, with stable definition/feature/component/occurrence identities and exact +//! weight, roughness and dielectric IOR. Empty/absent lists keep prior JSON and +//! capture behavior. Coats require opaque targets; even a zero-weight authored coat +//! cannot share a target with Glass. Capture resolves targets without changing +//! appearances, engineering materials or geometry. Unsupported CPU selected +//! reflection/anisotropy overrides refuse instead of dropping the coat. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ef1909c2f..3c0ff6a6b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -74,6 +74,7 @@ pub use print_face::PrintFace; pub mod project; mod project3d; pub mod render_aging; +pub mod render_coat; pub mod render_job; pub mod render_optics; pub mod render_resources; diff --git a/crates/doc/src/render_coat.rs b/crates/doc/src/render_coat.rs new file mode 100644 index 000000000..3053194be --- /dev/null +++ b/crates/doc/src/render_coat.rs @@ -0,0 +1,114 @@ +//! Portable opaque clear-coat assignments. Targets are stable definition/feature/ +//! component/occurrence identities; captured mesh ordinals never enter a design. +use crate::{ + DocError, Result, + render_surface::{RenderBodyTarget, bounded_sequence}, +}; +use serde::{Deserialize, Serialize}; +use solidcraft_render::clear_coat::ClearCoat; +use std::collections::BTreeSet; + +/// Matches the existing runtime clear-coat override bound for either executor. +pub const MAX_COAT_BINDINGS: usize = 64; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CoatMaterial { + pub weight: f64, + pub roughness: f64, + pub ior: f64, +} +impl PartialEq for CoatMaterial { + fn eq(&self, other: &Self) -> bool { + self.weight.to_bits() == other.weight.to_bits() + && self.roughness.to_bits() == other.roughness.to_bits() + && self.ior.to_bits() == other.ior.to_bits() + } +} +impl Default for CoatMaterial { + fn default() -> Self { + Self { weight: 1.0, roughness: 0.12, ior: 1.5 } + } +} +impl CoatMaterial { + pub fn validate(self) -> Result<()> { + self.to_runtime().map(|_| ()) + } + pub fn to_runtime(self) -> Result { + ClearCoat::new(self.weight, self.roughness, self.ior).map_err(|e| DocError::Invalid(e.to_string())) + } +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SavedCoat { + pub target: RenderBodyTarget, + pub coat: CoatMaterial, +} +impl SavedCoat { + pub fn validate(&self) -> Result<()> { + self.target.validate()?; + self.coat.validate() + } +} +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(transparent)] +pub struct CoatBindings(Vec); +impl CoatBindings { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn len(&self) -> usize { + self.0.len() + } + pub fn iter(&self) -> impl Iterator { + self.0.iter() + } + pub fn validate(&self) -> Result<()> { + if self.len() > MAX_COAT_BINDINGS || self.0.capacity() > MAX_COAT_BINDINGS { + return Err(DocError::Invalid("at most 64 saved clear-coat targets".into())); + } + let mut seen = BTreeSet::new(); + for binding in self.iter() { + binding.validate()?; + if !seen.insert(&binding.target) { + return Err(DocError::Invalid("duplicate saved clear-coat target".into())); + } + } + Ok(()) + } + /// Validate before mutation; replacement is explicit and stays on the same target. + pub fn set(&mut self, binding: SavedCoat, replace: bool) -> Result<()> { + binding.validate()?; + if let Some(old) = self.0.iter_mut().find(|old| old.target == binding.target) { + if old == &binding { + return Ok(()); + } + if !replace { + return Err(DocError::Invalid("clear-coat target already has a binding; explicit replacement required".into())); + } + *old = binding; + } else { + if self.len() >= MAX_COAT_BINDINGS { + return Err(DocError::Invalid("at most 64 saved clear-coat targets".into())); + } + self.0.try_reserve_exact(1).map_err(|_| DocError::Invalid("could not reserve saved clear-coat binding".into()))?; + if self.0.capacity() > MAX_COAT_BINDINGS { + return Err(DocError::Invalid("saved clear-coat capacity exceeds admission".into())); + } + self.0.push(binding); + } + Ok(()) + } + pub fn remove(&mut self, target: &RenderBodyTarget) -> bool { + let before = self.len(); + self.0.retain(|binding| &binding.target != target); + self.len() != before + } +} +impl<'de> Deserialize<'de> for CoatBindings { + fn deserialize>(d: D) -> std::result::Result { + let result = Self(bounded_sequence::(d)?); + result.validate().map_err(serde::de::Error::custom)?; + Ok(result) + } +} diff --git a/crates/doc/src/render_job.rs b/crates/doc/src/render_job.rs index 479f705bc..bc2345a29 100644 --- a/crates/doc/src/render_job.rs +++ b/crates/doc/src/render_job.rs @@ -7,7 +7,7 @@ use solidcraft_render::{ Camera, job::{ CpuBudget, CpuProgressiveOptions, DirectionalLightOptions, JobOptions, LightingPreset, PunctualLightOptions, RaytraceEnvironmentOptions, - RaytraceOptions, RectangleLightOptions, StudioLighting, ThinLens, ToneMap, + RaytraceOptions, RectangleLightOptions, StudioLighting, Sun, ThinLens, ToneMap, }, lighting::environment::SkyGradient, }; @@ -28,12 +28,15 @@ pub enum RenderJob { }, CpuRaytrace { #[serde(default)] - options: CpuJob, + transparent_background: bool, + // Keep numerical CPU intent out of every raster/GPU enum value too. + #[serde(default)] + options: Box, }, GpuPath { #[serde(default)] transparent_background: bool, - // StudioLighting is a bounded four-light value; boxing keeps the other variants small. + // StudioLighting contains bounded inline area/directional sources; boxing keeps the other variants small. #[serde(default)] options: Box, }, @@ -44,7 +47,19 @@ impl RenderJob { match self { Self::Raster { .. } if exposure_ev != 0.0 => Err(DocError::Invalid("saved raster rendering requires exposure_ev: 0".into())), Self::Raster { .. } => Ok(()), - Self::CpuRaytrace { options } => options.to_runtime(exposure_ev).map(|_| ()), + Self::CpuRaytrace { options, transparent_background } => { + options.validate(exposure_ev)?; + if let Some(output) = &options.output { + output + .presentation(exposure_ev, [0; 3], *transparent_background) + .validate() + .map_err(|error| DocError::Invalid(error.to_string()))?; + } + if let Some(lens) = options.lens { + lens.validate_camera(camera).map_err(|error| DocError::Invalid(error.to_string()))?; + } + Ok(()) + } Self::GpuPath { options, transparent_background } => { if *transparent_background && options.backdrop.is_some() { return Err(DocError::Invalid("choose a camera backdrop or transparent PNG, not both".into())); @@ -67,6 +82,24 @@ impl RenderJob { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct CpuJob { + #[serde(skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sun: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sky: Option, + #[serde(skip_serializing_if = "crate::render_aging::SavedAgingStack::is_empty")] + pub aging: crate::render_aging::SavedAgingStack, + #[serde(skip_serializing_if = "Option::is_none")] + pub adaptive: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub denoise: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub lens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub output: Option>, #[serde(skip_serializing_if = "CpuBudget::is_compact")] pub budget: CpuBudget, #[serde(skip_serializing_if = "Option::is_none")] @@ -94,6 +127,15 @@ pub struct CpuJob { impl Default for CpuJob { fn default() -> Self { Self { + volume: None, + sun: None, + sky: None, + aging: Default::default(), + adaptive: None, + denoise: false, + path: None, + lens: None, + output: None, budget: CpuBudget::Compact, progressive: None, primary_samples: 1, @@ -111,12 +153,28 @@ impl Default for CpuJob { } impl CpuJob { + /// Validate saved parameters without inventing captured targets. + pub fn validate(&self, exposure_ev: f64) -> Result<()> { + self.validated_parameters(exposure_ev).map(|_| ()) + } + /// Validate portable map compatibility without claiming that stable aging + /// identities have been resolved into captured runtime body indices. + pub fn validate_surface_maps(&self, exposure_ev: f64) -> Result<()> { + let options = self.validated_parameters(exposure_ev)?; + solidcraft_render::job::textures::validate_cpu_options(&options).map_err(|e| DocError::Invalid(e.to_string())) + } /// Pure lowering, valid on hosts without a CPU raytracer. Checks bounds before cloning lists. pub fn to_runtime(&self, exposure_ev: f64) -> Result { + if self.aging.iter().any(|layer| layer.target.is_some()) { + return Err(DocError::Invalid("targeted CPU aging requires stable occurrence resolution against the current scene".into())); + } + self.validated_parameters(exposure_ev) + } + fn validated_parameters(&self, exposure_ev: f64) -> Result { if let Some(hdr) = self.hdr { hdr.validate()?; - if self.environment.is_some() { - return Err(DocError::Invalid("choose either saved CPU HDR or constant environment".into())); + if self.environment.is_some() || self.sky.is_some() { + return Err(DocError::Invalid("choose either saved CPU HDR, gradient Sky or constant environment".into())); } } bounded(&self.lights, 8, "directional lights")?; @@ -128,7 +186,26 @@ impl CpuJob { // Preserve hidden editable intent in CpuJob, but do not submit tuning for // a light family that is explicitly absent. This does not rewrite the file. let active_area = self.area_lights.as_ref().is_some_and(|lights| !lights.is_empty()); + let aging = self.aging.parameters_only()?; + let sky = self + .sky + .as_ref() + .map(|sky| -> Result<_> { + sky.validate()?; + let SkyEnvironment::Sky { gradient, rotation_rad, intensity } = *sky; + Ok(Box::new(solidcraft_render::job::CpuSky { gradient, rotation_rad, intensity })) + }) + .transpose()?; let options = RaytraceOptions { + volume: self.volume, + sun: self.sun.map(Box::new), + sky, + aging: (!aging.is_empty()).then(|| Box::new(aging)), + adaptive: self.adaptive.map(Box::new), + denoise: self.denoise, + path: self.path, + lens: self.lens, + output: self.output.clone(), budget: self.budget, progressive: self.progressive, primary_samples: self.primary_samples, @@ -346,3 +423,50 @@ fn punctual_lights<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resul fn area_lights<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>, D::Error> { optional_lights::(d) } + +#[cfg(test)] +mod cpu_volume_portable_tests { + use super::*; + use solidcraft_render::job::{CpuPathOptions, CpuProgressiveOptions, volume::HomogeneousVolume}; + #[test] + fn cpu_volume_saved_parameters_roundtrip_lower_without_default_adoption_or_hidden_repairs() { + let v = HomogeneousVolume { + min_mm: [-2.0, -3.0, -4.0], + max_mm: [5.0, 6.0, 7.0], + extinction_per_mm: 0.3, + scattering_albedo: [0.2, 0.4, 0.6], + anisotropy: -0.37, + }; + let old = serde_json::to_value(CpuJob::default()).unwrap(); + assert!(old.get("volume").is_none()); + let mut job = CpuJob { + volume: Some(v), + path: Some(CpuPathOptions { max_depth: 8 }), + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }), + ..Default::default() + }; + let json = serde_json::to_value(&job).unwrap(); + let reopened: CpuJob = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(reopened, job); + assert_eq!(reopened.to_runtime(0.0).unwrap().volume, Some(v)); + job.denoise = true; + let before = job.clone(); + assert!(job.validate(0.0).is_err()); + assert_eq!(job, before); + job.denoise = false; + job.path = None; + let before = job.clone(); + assert!(job.validate(0.0).is_err()); + assert_eq!(job, before); + job.volume.as_mut().unwrap().extinction_per_mm = 0.0; + job.denoise = true; + job.validate(0.0).unwrap(); + let inactive = serde_json::to_value(&job).unwrap(); + assert_eq!(inactive["volume"]["anisotropy"], -0.37); + assert_eq!(serde_json::from_value::(inactive).unwrap(), job); + job.volume = None; + job.denoise = false; + job.progressive = None; + assert_eq!(serde_json::to_value(job).unwrap(), old); + } +} diff --git a/crates/doc/src/render_optics.rs b/crates/doc/src/render_optics.rs index 2915d9398..a095bb46f 100644 --- a/crates/doc/src/render_optics.rs +++ b/crates/doc/src/render_optics.rs @@ -36,6 +36,55 @@ impl Default for OpticalMaterial { } } impl OpticalMaterial { + /// The CPU consumer is a certified subset of the existing saved optical contract. + /// Keep authored unsupported values intact and refuse them, never drop effects. + pub fn validate_for_cpu(self) -> Result<()> { + self.validate_for_cpu_path(false) + } + /// General closed boundaries require the explicit finite progressive path. + pub fn validate_for_cpu_path(self, path: bool) -> Result<()> { + self.validate()?; + 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(), + )); + } + if self.subsurface.is_some() && !path { + return Err(DocError::Invalid("CPU subsurface scattering requires Indirect lighting and a certified closed medium".into())); + } + if self.absorption_per_mm.into_iter().any(|v| !(0.0..=100.0).contains(&v)) || !(0.0..=10000.0).contains(&self.thickness_mm) { + return Err(DocError::Invalid("CPU glass absorption must be 0..100 per mm and virtual sheet thickness 0..10000 mm".into())); + } + Ok(()) + } + + /// A closed optical boundary is accepted only if the CPU producer subsequently + /// certifies the captured mesh as its exact axis-aligned-box subset. The saved + /// boundary is not rewritten and no arbitrary closed-mesh support is implied. + pub fn to_cpu(self, body_index: usize, body_name: &str) -> Result { + self.to_cpu_for_path(body_index, body_name, false) + } + pub fn to_cpu_for_path(self, body_index: usize, body_name: &str, path: bool) -> Result { + self.validate_for_cpu_path(path)?; + if body_name.is_empty() || body_name.len() > 1024 || body_name.chars().any(char::is_control) { + return Err(DocError::Invalid("CPU optical target requires a bounded captured body name".into())); + } + Ok(solidcraft_render::job::DielectricOptions { + subsurface: self.subsurface, + shadow_transmission: self.shadow_transmission, + body_index, + body_name: body_name.into(), + boundary: match self.boundary { + OpticalBoundary::ThinSheet => solidcraft_render::job::DielectricBoundary::ThinSheet, + OpticalBoundary::ClosedMesh if path => solidcraft_render::job::DielectricBoundary::ClosedMesh, + OpticalBoundary::ClosedBox | OpticalBoundary::ClosedMesh => solidcraft_render::job::DielectricBoundary::ClosedBox, + }, + ior: self.ior, + absorption_per_mm: self.absorption_per_mm, + thickness_mm: self.thickness_mm, + }) + } + pub fn validate(self) -> Result<()> { let error = |message: String| DocError::Invalid(message); OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, self.ior).map_err(|e| error(e.to_string()))?; @@ -90,6 +139,19 @@ impl OpticalBindings { } Ok(()) } + pub fn validate_for_cpu(&self) -> Result<()> { + self.validate_for_cpu_path(false) + } + pub fn validate_for_cpu_path(&self, path: bool) -> Result<()> { + self.validate()?; + if self.len() > 8 { + return Err(DocError::Invalid("CPU supports at most eight certified optical targets".into())); + } + for binding in self.iter() { + binding.optics.validate_for_cpu_path(path)?; + } + Ok(()) + } pub fn set(&mut self, binding: SavedOptics, replace: bool) -> Result<()> { binding.validate()?; if let Some(old) = self.0.iter_mut().find(|old| old.target == binding.target) { @@ -166,4 +228,86 @@ mod tests { .is_err() ); } + + #[test] + fn cpu_optical_consumer_preserves_saved_boundary_and_refuses_unrepresented_effects() { + let closed = OpticalMaterial { ior: 1.51, absorption_per_mm: [0.1, 0.02, 0.0], ..Default::default() }; + let original = serde_json::to_value(closed).unwrap(); + let cpu = closed.to_cpu(3, "Glass@part-2").unwrap(); + assert_eq!(cpu.boundary, solidcraft_render::job::DielectricBoundary::ClosedBox); + assert_eq!((cpu.body_index, cpu.body_name.as_str()), (3, "Glass@part-2")); + assert_eq!((cpu.ior, cpu.absorption_per_mm), (1.51, [0.1, 0.02, 0.0])); + assert_eq!(serde_json::to_value(closed).unwrap(), original, "CPU specialization never rewrites the authored closed boundary"); + let thin = OpticalMaterial { boundary: OpticalBoundary::ThinSheet, thickness_mm: 2.0, ..closed }; + assert_eq!(thin.to_cpu(0, "Sheet").unwrap().boundary, solidcraft_render::job::DielectricBoundary::ThinSheet); + for (value, reason) in [ + (OpticalMaterial { shadow_transmission: true, ..thin }, "transmissive shadows"), + (OpticalMaterial { subsurface: Some(Subsurface { scattering_per_mm: 0.0, anisotropy: 0.0 }), ..closed }, "subsurface"), + (OpticalMaterial { absorption_per_mm: [101.0, 0.0, 0.0], ..closed }, "absorption"), + (OpticalMaterial { thickness_mm: 10001.0, ..thin }, "thickness"), + ] { + let before = serde_json::to_value(value).unwrap(); + assert!(value.to_cpu(0, "Target").unwrap_err().to_string().contains(reason)); + assert_eq!(serde_json::to_value(value).unwrap(), before); + } + let mut optics = OpticalBindings::default(); + for feature in 1..=9 { + optics + .set( + SavedOptics { + target: RenderBodyTarget { definition: format!("Glass{feature}"), feature, component: 0, occurrence_path: vec![] }, + optics: closed, + }, + false, + ) + .unwrap(); + } + optics.validate().unwrap(); + assert!(optics.validate_for_cpu().is_err()); + let target = RenderBodyTarget { definition: "Glass".into(), feature: 1, component: 0, occurrence_path: vec![] }; + let mut setup = crate::render_settings::RenderSetup { + job: Some(crate::render_job::RenderJob::CpuRaytrace { transparent_background: false, options: Default::default() }), + ..Default::default() + }; + setup.optics.set(SavedOptics { target, optics: closed }, false).unwrap(); + setup.validate().unwrap(); + let wire = serde_json::to_value(&setup).unwrap(); + assert_eq!(serde_json::from_value::(wire).unwrap(), setup); + } +} + +#[cfg(test)] +mod cpu_general_glass_contract_tests { + use super::*; + #[test] + fn saved_general_glass_requires_explicit_path_and_preserves_unsupported_choices_and_old_wire() { + let optics = OpticalMaterial { ior: 1.51, absorption_per_mm: [0.1, 0.2, 0.3], boundary: OpticalBoundary::ClosedMesh, ..Default::default() }; + assert_eq!(optics.to_cpu(0, "Glass").unwrap().boundary, solidcraft_render::job::DielectricBoundary::ClosedBox); + let general = optics.to_cpu_for_path(0, "Glass", true).unwrap(); + assert_eq!(general.boundary, solidcraft_render::job::DielectricBoundary::ClosedMesh); + assert_eq!((general.ior, general.absorption_per_mm), (optics.ior, optics.absorption_per_mm)); + let scattering = OpticalMaterial { subsurface: Some(Subsurface { scattering_per_mm: 0.1, anisotropy: 0.3 }), ..optics }; + let before = serde_json::to_value(scattering).unwrap(); + assert!(scattering.to_cpu(0, "Glass").is_err(), "the legacy consumer remains explicit"); + assert_eq!(scattering.to_cpu_for_path(0, "Glass", true).unwrap().subsurface, scattering.subsurface); + assert_eq!(serde_json::to_value(scattering).unwrap(), before); + let encoded = serde_json::to_value(&general).unwrap(); + assert!(encoded.get("shadow_transmission").is_none()); + assert_eq!(serde_json::from_value::(encoded).unwrap(), general); + let thin = OpticalMaterial { boundary: OpticalBoundary::ThinSheet, shadow_transmission: true, ..optics }; + assert!(thin.to_cpu(0, "Glass").is_err()); + assert!(thin.to_cpu_for_path(0, "Glass", true).unwrap().shadow_transmission); + for value in [ + OpticalMaterial { shadow_transmission: true, ..optics }, + OpticalMaterial { + boundary: OpticalBoundary::ThinSheet, + subsurface: Some(Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }), + ..optics + }, + ] { + let before = value; + assert!(value.to_cpu_for_path(0, "Glass", true).is_err()); + assert_eq!(value, before); + } + } } diff --git a/crates/doc/src/render_settings.rs b/crates/doc/src/render_settings.rs index d0c4dc67b..7277542b2 100644 --- a/crates/doc/src/render_settings.rs +++ b/crates/doc/src/render_settings.rs @@ -35,6 +35,8 @@ pub struct RenderSetup { pub surfaces: crate::render_surface::SurfaceBindings, #[serde(skip_serializing_if = "crate::render_optics::OpticalBindings::is_empty")] pub optics: crate::render_optics::OpticalBindings, + #[serde(skip_serializing_if = "crate::render_coat::CoatBindings::is_empty")] + pub coats: crate::render_coat::CoatBindings, #[serde(skip_serializing_if = "solidcraft_render::stage::Stage::is_empty")] pub stage: solidcraft_render::stage::Stage, } @@ -78,6 +80,7 @@ impl Default for RenderSetup { background: [236, 240, 245], job: None, optics: Default::default(), + coats: Default::default(), surfaces: Default::default(), stage: Default::default(), } @@ -87,9 +90,13 @@ impl Default for RenderSetup { impl RenderSetup { pub fn validate(&self) -> Result<()> { let (limits, cpu) = match &self.job { - Some(RenderJob::CpuRaytrace { options }) => { - (options.budget.image_limits(options.progressive.is_some()), Some(CpuSize { progressive: options.progressive })) - } + Some(RenderJob::CpuRaytrace { options, .. }) => ( + options.budget.image_limits(options.progressive.is_some()), + Some(CpuSize { + progressive: solidcraft_render::job::cpu_camera_sampling(options.progressive, options.adaptive, options.budget) + .map_err(|e| DocError::Invalid(e.to_string()))?, + }), + ), Some(RenderJob::GpuPath { .. }) => (solidcraft_render::job::GPU_PATH_LIMITS, None), _ => (RenderLimits::default(), None), }; @@ -111,8 +118,30 @@ impl RenderSetup { fn validate_with_limits(&self, limits: RenderLimits, cpu: Option) -> Result<()> { self.surfaces.validate()?; self.optics.validate()?; - if !self.optics.is_empty() && !matches!(self.job, Some(RenderJob::GpuPath { .. })) { - return Err(DocError::Invalid("saved optics require an explicit GPU job".into())); + self.coats.validate()?; + if !self.coats.is_empty() && !matches!(self.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) { + return Err(DocError::Invalid("saved clear coats require an explicit CPU or GPU raytrace job".into())); + } + if self.coats.iter().any(|coat| self.optics.iter().any(|optics| coat.target == optics.target)) { + return Err(DocError::Invalid("clear coat and Glass cannot share a target, including zero-weight authored coats".into())); + } + match &self.job { + Some(RenderJob::CpuRaytrace { options, .. }) => { + self.optics.validate_for_cpu_path(options.path.is_some())?; + if options.volume.is_some_and(|v| v.active()) && !self.optics.is_empty() { + return Err(DocError::Invalid( + "CPU Atmosphere cannot combine with saved Glass or subsurface scattering; settings are kept".into(), + )); + } + if options.denoise && self.optics.iter().any(|binding| binding.optics.subsurface.is_some_and(|s| s.active())) { + return Err(DocError::Invalid( + "CPU subsurface random walks have no surface-denoiser guides; disable denoising explicitly".into(), + )); + } + } + Some(RenderJob::GpuPath { .. }) => {} + _ if !self.optics.is_empty() => return Err(DocError::Invalid("saved optics require an explicit CPU or GPU raytrace job".into())), + _ => {} } if self.optics.iter().any(|o| self.surfaces.iter().any(|s| s.target == o.target)) { return Err(DocError::Invalid("saved opaque surface maps and optical boundaries cannot share a target".into())); @@ -121,10 +150,23 @@ impl RenderSetup { if !self.stage.is_empty() && matches!(self.job, Some(RenderJob::Raster { .. })) { return Err(DocError::Invalid("passive stage geometry requires raytracing; raster cannot silently discard it".into())); } - if !self.surfaces.is_empty() && !matches!(self.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) { - return Err(DocError::Invalid( - "saved surfaces require an explicit CPU raytrace or GPU path job; unsupported methods cannot discard bindings".into(), - )); + if !self.surfaces.is_empty() { + match &self.job { + Some(RenderJob::GpuPath { .. }) => {} + Some(RenderJob::CpuRaytrace { options, .. }) => { + if !self.optics.is_empty() && options.path.is_none() { + return Err(DocError::Invalid( + "CPU surface maps cannot combine with saved Glass; preserve the bindings and select a compatible method".into(), + )); + } + options.validate_surface_maps(self.exposure_ev)?; + } + _ => { + return Err(DocError::Invalid( + "saved surfaces require an explicit CPU raytrace or GPU path job; unsupported methods cannot discard bindings".into(), + )); + } + } } let (width, height) = (u64::from(self.width), u64::from(self.height)); if width == 0 || height == 0 { @@ -170,10 +212,22 @@ impl RenderSetup { )); } job.validate(&self.camera, self.exposure_ev)?; - if let RenderJob::CpuRaytrace { options } = job - && let Some(progressive) = options.progressive - { - progressive.validate_image_with_budget(self.width, self.height, options.budget).map_err(|e| DocError::Invalid(e.to_string()))?; + if let RenderJob::CpuRaytrace { options, .. } = job { + if options.denoise { + solidcraft_render::job::validate_cpu_denoise_image(self.width, self.height).map_err(|e| DocError::Invalid(e.to_string()))?; + } + options + .budget + .validate_image( + self.width, + self.height, + solidcraft_render::job::cpu_camera_sampling(options.progressive, options.adaptive, options.budget) + .map_err(|e| DocError::Invalid(e.to_string()))?, + ) + .map_err(|e| DocError::Invalid(e.to_string()))?; + if let Some(output) = &options.output { + output.validate_image(self.width, self.height).map_err(|e| DocError::Invalid(e.to_string()))?; + } } } // Desired mode/format/backend may be unavailable on this host. Saving intent is not preflight. @@ -245,7 +299,7 @@ impl RenderSettings { } } match &setup.job { - Some(RenderJob::CpuRaytrace { options }) => { + Some(RenderJob::CpuRaytrace { options, .. }) => { if let Some(hdr) = options.hdr { hdr.validate_resource(&self.resources)?; } @@ -328,11 +382,12 @@ mod tests { RenderSetup { exposure_ev: 1.25, job: Some(RenderJob::CpuRaytrace { - options: CpuJob { + transparent_background: false, + options: Box::new(CpuJob { lights: Some(Vec::new()), hdr: Some(CpuHdrEnvironment { resource: id, rotation_rad: 0.75, intensity: 2.0, samples: 64 }), ..Default::default() - }, + }), }), ..Default::default() }, @@ -580,7 +635,7 @@ mod tests { let cpu = |budget, width, height| RenderSetup { width, height, - job: Some(RenderJob::CpuRaytrace { options: CpuJob { budget, ..Default::default() } }), + job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(CpuJob { budget, ..Default::default() }) }), ..Default::default() }; let compact = cpu(CpuBudget::Compact, 3840, 2160); @@ -588,7 +643,7 @@ mod tests { assert!(message.contains("3840 × 2160 exceeds the image limits (4096 pixels per side, 4194304 pixels in all)"), "{message}"); assert!(message.contains("the largest image at this aspect is 2730 × 1536"), "{message}"); assert!(message.contains("choose the Studio CPU resource profile, or a smaller size"), "{message}"); - assert!(matches!(&compact.job, Some(RenderJob::CpuRaytrace { options }) if options.budget == CpuBudget::Compact)); + assert!(matches!(&compact.job, Some(RenderJob::CpuRaytrace { options, .. }) if options.budget == CpuBudget::Compact)); let message = compact.validate_for_cpu(CpuBudget::Compact).unwrap_err().to_string(); assert!(message.contains("choose the Studio CPU resource profile"), "{message}"); @@ -647,7 +702,7 @@ mod tests { let saved = serde_json::to_value(&reopened.render).unwrap(); assert!(saved["setups"]["Legacy"].get("job").is_none()); assert_eq!(saved["setups"]["Legacy"]["environment_rotation"], 0.75); - let RenderJob::CpuRaytrace { options } = settings.setups["CPU"].job.as_ref().unwrap() else { panic!("CPU intent changed") }; + let RenderJob::CpuRaytrace { options, .. } = settings.setups["CPU"].job.as_ref().unwrap() else { panic!("CPU intent changed") }; let runtime = options.to_runtime(settings.setups["CPU"].exposure_ev).unwrap(); assert_eq!(runtime.exposure_ev, 1.25); assert_eq!(runtime.area_samples, Some(64)); @@ -671,11 +726,11 @@ mod tests { for options in [json!({}), json!({"lights":null,"punctual_lights":null,"area_lights":null,"environment":null})] { let setup: RenderSetup = serde_json::from_value(json!({"job":{"method":"cpu_raytrace","options":options}})).unwrap(); setup.validate().unwrap(); - assert_eq!(setup.job, Some(RenderJob::CpuRaytrace { options: CpuJob::default() })); + assert_eq!(setup.job, Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::default() })); } let empty: RenderSetup = serde_json::from_value(json!({"job":{"method":"cpu_raytrace","options":{"lights":[]}}})).unwrap(); empty.validate().unwrap(); - assert_ne!(empty.job, Some(RenderJob::CpuRaytrace { options: CpuJob::default() })); + assert_ne!(empty.job, Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::default() })); for (lighting, explicit) in [(serde_json::Value::Null, false), (json!({"environment":[0,0,0],"area_lights":[]}), true)] { let setup: RenderSetup = serde_json::from_value(json!({"job":{"method":"gpu_path","options":{"lighting":lighting}}})).unwrap(); setup.validate().unwrap(); @@ -697,7 +752,7 @@ mod tests { let document = Document { render: Arc::new(settings), ..Default::default() }; let reopened = Document::from_json(&document.to_json()).unwrap(); assert_eq!(document, reopened); - let RenderJob::CpuRaytrace { options } = reopened.render.setups["Film"].job.as_ref().unwrap() else { panic!("method changed") }; + let RenderJob::CpuRaytrace { options, .. } = reopened.render.setups["Film"].job.as_ref().unwrap() else { panic!("method changed") }; let runtime = options.to_runtime(1.5).unwrap(); assert_eq!(runtime.progressive.unwrap().seed, u32::MAX); assert_eq!(runtime.exposure_ev, 1.5); @@ -714,6 +769,104 @@ mod tests { assert!(serde_json::from_value::(incompatible).is_err()); } + #[test] + fn cpu_transparent_intent_roundtrips_offline_and_keeps_opaque_defaults() { + use serde_json::json; + let opaque: RenderSetup = serde_json::from_value(json!({"job":{"method":"cpu_raytrace"}})).unwrap(); + assert!(matches!(opaque.job, Some(RenderJob::CpuRaytrace { transparent_background: false, .. }))); + let setup: RenderSetup = + serde_json::from_value(json!({"width":8,"height":8,"job":{"method":"cpu_raytrace","transparent_background":true,"options":{ + "primary_samples":4,"output":{"linear_exr":true}}}})) + .unwrap(); + setup.validate().unwrap(); + let document = Document { + render: Arc::new(RenderSettings { setups: std::collections::BTreeMap::from([("Cutout".into(), setup)]), ..Default::default() }), + ..Default::default() + }; + assert_eq!(document, Document::from_json(&document.to_json()).unwrap()); + for output in [json!({"backdrop":{}}), json!({"finishing":{"bloom":{"strength":1}}}), json!({"finishing":{"photographic":{"grain":0.03}}})] { + let settings = json!({"setups":{"Cutout":{"job":{"method":"cpu_raytrace","transparent_background":true,"options":{"output":output}}}}}); + let error = serde_json::from_value::(settings.clone()).unwrap_err(); + assert!(error.to_string().contains("opaque"), "valid opaque-only effects remain authored and refused"); + let mut saved: serde_json::Value = serde_json::from_str(&Document::default().to_json()).unwrap(); + saved["render"] = settings; + let error = Document::from_json(&saved.to_string()).unwrap_err(); + assert!(error.to_string().contains("opaque"), "the full document loader must enforce the same saved output contract"); + } + assert!( + serde_json::from_value::(json!({"job":{"method":"cpu_raytrace","options":{"transparent_background":true}}})).is_err(), + "one alpha authority beside the numerical job" + ); + } + + #[test] + fn cpu_physical_lens_roundtrips_offline_and_keeps_disabled_legacy_intent() { + use serde_json::json; + let camera = Camera { fov: 0.7, distance: 20.0, ..Default::default() }; + let saved = json!({"setups":{"Focus":{"width":64,"height":32,"camera":camera, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":8,"seed":81}, + "lens":{"aperture_radius_mm":0.5,"focus_distance_mm":20.0}}}}}}); + let settings: RenderSettings = serde_json::from_value(saved.clone()).unwrap(); + let document = Document { render: Arc::new(settings), ..Default::default() }; + assert_eq!(document, Document::from_json(&document.to_json()).unwrap()); + let RenderJob::CpuRaytrace { options, .. } = document.render.setups["Focus"].job.as_ref().unwrap() else { panic!("CPU method changed") }; + assert_eq!(options.to_runtime(1.5).unwrap().lens, options.lens); + let mut fixed = saved.clone(); + fixed["setups"]["Focus"]["job"]["options"].as_object_mut().unwrap().remove("progressive"); + assert!(serde_json::from_value::(fixed.clone()).is_err()); + fixed["setups"]["Focus"]["job"]["options"]["lens"]["aperture_radius_mm"] = json!(0); + fixed["setups"]["Focus"]["camera"]["fov"] = json!(0); + let zero: RenderSettings = serde_json::from_value(fixed).unwrap(); + assert_eq!(serde_json::to_value(&zero).unwrap()["setups"]["Focus"]["job"]["options"]["lens"]["aperture_radius_mm"].as_f64(), Some(0.0)); + for lens in [ + json!({"aperture_radius_mm":-1,"focus_distance_mm":20}), + json!({"aperture_radius_mm":0.5,"focus_distance_mm":0}), + json!({"aperture_radius_mm":0.5,"focus_distance_mm":20,"f_stop":2}), + ] { + let mut invalid = saved.clone(); + invalid["setups"]["Focus"]["job"]["options"]["lens"] = lens; + assert!(serde_json::from_value::(invalid).is_err()); + } + let mut ortho = saved; + ortho["setups"]["Focus"]["camera"]["fov"] = json!(0); + assert!(serde_json::from_value::(ortho).is_err()); + assert!(serde_json::to_value(CpuJob::default()).unwrap().get("lens").is_none()); + } + + #[test] + fn cpu_output_presentation_roundtrips_offline_without_another_exposure_authority() { + use serde_json::json; + assert!(serde_json::to_value(CpuJob::default()).unwrap().get("output").is_none()); + let saved = json!({"setups":{"CPU output":{"width":64,"height":32,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":7,"seed":81}, + "output":{"tone_map":"aces_fitted","finishing":{"rgb_gain":[1.2,0.8,1.1],"photographic":{"grain":0.03,"seed":42}, + "bloom":{"strength":0.2,"threshold":0.5,"radius":2}},"backdrop":{"mode":"radial"},"linear_exr":true}}}}}}); + let settings: RenderSettings = serde_json::from_value(saved).unwrap(); + let setup = &settings.setups["CPU output"]; + let RenderJob::CpuRaytrace { options, .. } = setup.job.as_ref().unwrap() else { panic!("CPU job expected") }; + let runtime = options.to_runtime(setup.exposure_ev).unwrap(); + assert_eq!(runtime.exposure_ev, 1.5); + assert_eq!(runtime.output, options.output); + let encoded = serde_json::to_value(&settings).unwrap(); + assert!(encoded["setups"]["CPU output"]["job"]["options"]["output"].get("exposure_ev").is_none()); + assert_eq!(settings, serde_json::from_value::(encoded.clone()).unwrap()); + for bad in [json!({"exposure_ev":1}), json!({"samples":4}), json!({"linear_exr":"yes"}), json!({"finishing":{"rgb_gain":[-1,1,1]}})] { + let mut invalid = encoded.clone(); + invalid["setups"]["CPU output"]["job"]["options"]["output"] = bad; + assert!(serde_json::from_value::(invalid).is_err()); + } + let wide = json!({"width":16384,"height":1,"job":{"method":"cpu_raytrace","options":{"budget":"workstation"}}}); + serde_json::from_value::(wide.clone()).unwrap().validate().unwrap(); + for output in [json!({"tone_map":"aces_fitted"}), json!({"linear_exr":true})] { + let mut invalid = wide.clone(); + invalid["job"]["options"]["output"] = output; + assert!( + serde_json::from_value::(invalid).unwrap().validate().is_err(), + "active output must respect its existing shared envelope" + ); + } + } + #[test] fn portable_jobs_reject_unbounded_invalid_and_nonportable_inputs() { use serde_json::json; @@ -817,6 +970,7 @@ mod tests { #[cfg(test)] mod cpu_budget_tests { use super::*; + use serde_json::json; use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions}; #[test] @@ -837,11 +991,12 @@ mod cpu_budget_tests { width: 3840, height: 2160, job: Some(RenderJob::CpuRaytrace { - options: CpuJob { + transparent_background: false, + options: Box::new(CpuJob { budget: CpuBudget::Studio, progressive: Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 82 }), ..Default::default() - }, + }), }), ..Default::default() }; @@ -849,7 +1004,7 @@ mod cpu_budget_tests { let text = serde_json::to_string(&setup).unwrap(); let reopened: RenderSetup = serde_json::from_str(&text).unwrap(); assert_eq!(setup, reopened); - let Some(RenderJob::CpuRaytrace { options }) = &mut setup.job else { + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU fixture"); }; options.budget = CpuBudget::Compact; @@ -861,4 +1016,372 @@ mod cpu_budget_tests { let legacy_large = RenderSetup { width: 3840, height: 2160, ..Default::default() }; assert!(legacy_large.validate().is_err(), "large intent must name an explicit CPU job profile"); } + #[test] + fn cpu_path_is_explicit_bounded_offline_intent_and_roundtrips_without_changing_legacy_jobs() { + let old = CpuJob::default(); + assert!(old.path.is_none()); + assert!(serde_json::to_value(&old).unwrap().get("path").is_none()); + for depth in [1, 8, 16] { + let setup:RenderSetup=serde_json::from_value(json!({"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"path":{"max_depth":depth},"progressive":{"samples_per_pixel":7,"seed":9}}}})).unwrap(); + setup.validate().unwrap(); + let mut document = crate::Document::default(); + std::sync::Arc::make_mut(&mut document.render).setups.insert("GI".into(), setup); + let bytes = serde_json::to_vec(&document).unwrap(); + let reopened: crate::Document = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(document, reopened); + } + for raw in [ + json!({"path":{"max_depth":0},"progressive":{"samples_per_pixel":7,"seed":9}}), + json!({"path":{"max_depth":17},"progressive":{"samples_per_pixel":7,"seed":9}}), + json!({"path":{"max_depth":8}}), + json!({"path":{"max_depth":8},"progressive":{"samples_per_pixel":7,"seed":9},"shadows":false}), + ] { + let options: CpuJob = serde_json::from_value(raw).unwrap(); + assert!(options.to_runtime(0.0).is_err()); + } + assert!(serde_json::from_value::(json!({"path":{"max_depth":8,"unknown":true}})).is_err()); + } +} + +#[cfg(test)] +#[test] +fn cpu_denoise_saved_flag_roundtrips_offline_and_keeps_false_omitted() { + use solidcraft_render::job::CpuBudget; + let mut setup = RenderSetup { + width: 16, + height: 8, + job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(CpuJob { denoise: true, ..Default::default() }) }), + ..Default::default() + }; + setup.validate().unwrap(); + let wire = serde_json::to_value(&setup).unwrap(); + assert_eq!(wire["job"]["options"]["denoise"], true); + assert_eq!(serde_json::from_value::(wire).unwrap(), setup); + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU job expected") }; + assert!(options.to_runtime(1.5).unwrap().denoise); + options.denoise = false; + assert!(serde_json::to_value(&setup).unwrap()["job"]["options"].get("denoise").is_none()); + let default: CpuJob = serde_json::from_value(serde_json::json!({})).unwrap(); + let explicit: CpuJob = serde_json::from_value(serde_json::json!({"denoise":false})).unwrap(); + assert_eq!(default, explicit); + assert!(!default.to_runtime(0.0).unwrap().denoise); + assert!(serde_json::from_value::(serde_json::json!({"denoise":"true"})).is_err()); + setup.width = 8193; + setup.height = 1; + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU job expected") }; + options.budget = CpuBudget::Workstation; + setup.validate().unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU job expected") }; + options.denoise = true; + assert!(setup.validate().unwrap_err().to_string().contains("CPU denoising")); +} + +#[cfg(test)] +#[test] +fn composed_cpu_path_preserves_saved_optics_alpha_filter_lens_and_master_intent() { + use crate::render_optics::{OpticalMaterial, SavedOptics}; + use crate::render_surface::RenderBodyTarget; + use solidcraft_render::job::{CpuPathOptions, CpuProgressiveOptions, OutputOptions, ThinLens}; + let mut setup = RenderSetup { + camera: Camera { fov: 0.6, distance: 123.0, ..Default::default() }, + width: 8, + height: 8, + job: Some(RenderJob::CpuRaytrace { + transparent_background: true, + options: Box::new(CpuJob { + denoise: true, + path: Some(CpuPathOptions { max_depth: 3 }), + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 81 }), + lens: Some(ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 123.0 }), + output: Some(Box::new(OutputOptions { linear_exr: true, ..Default::default() })), + ..Default::default() + }), + }), + ..Default::default() + }; + setup.validate().unwrap(); + setup + .optics + .set( + SavedOptics { + target: RenderBodyTarget { definition: "Glass".into(), feature: 1, component: 0, occurrence_path: Vec::new() }, + optics: OpticalMaterial::default(), + }, + false, + ) + .unwrap(); + let before = setup.clone(); + setup.validate().unwrap(); + assert_eq!(setup, before, "validation must not lower or rewrite authored optics"); + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU fixture") }; + options.path = None; + setup.validate().unwrap(); + assert!(matches!(&setup.job, Some(RenderJob::CpuRaytrace { transparent_background:true, options }) + if options.denoise && options.output.as_ref().unwrap().linear_exr && options.lens.is_some())); +} + +#[cfg(test)] +#[test] +fn gpu_hard_directional_intent_roundtrips_and_hostile_lists_refuse_at_document_load() { + use serde_json::json; + let light = json!({"direction":[0.0,0.0,2.0],"color":[0.25,0.5,1.0],"intensity":0.0}); + let settings = json!({"setups":{"Lights":{"job":{"method":"gpu_path","options":{"lighting":{"directional_lights":vec![light.clone();8]}}}}}}); + let saved: RenderSettings = serde_json::from_value(settings.clone()).unwrap(); + let doc = crate::Document { render: std::sync::Arc::new(saved.clone()), ..Default::default() }; + assert_eq!(crate::Document::from_json(&doc.to_json()).unwrap(), doc); + let encoded = serde_json::to_value(&saved).unwrap(); + assert_eq!(encoded["setups"]["Lights"]["job"]["options"]["lighting"]["directional_lights"], json!(vec![light.clone(); 8])); + for list in [ + json!(vec![light.clone(); 9]), + json!([{"direction":[0,0,0],"color":[1,1,1],"intensity":1}]), + json!([{"direction":[0,0,1],"color":[1,1,1],"intensity":65}]), + ] { + let mut bad = settings.clone(); + bad["setups"]["Lights"]["job"]["options"]["lighting"]["directional_lights"] = list; + assert!(serde_json::from_value::(bad).is_err()); + } + let mut over_combined = settings; + over_combined["setups"]["Lights"]["job"]["options"]["lighting"]["sun"] = + json!({"direction":[0,0,1],"angular_radius_rad":0.02,"radiance":[1,1,1]}); + assert!(serde_json::from_value::(over_combined.clone()).is_err()); + let mut document = serde_json::to_value(crate::Document::default()).unwrap(); + document["render"] = over_combined; + assert!(crate::Document::from_json(&serde_json::to_string(&document).unwrap()).is_err()); + let old: RenderSettings = serde_json::from_value(json!({"setups":{"Old":{"job":{"method":"gpu_path","options":{}}}}})).unwrap(); + let Some(RenderJob::GpuPath { options, .. }) = &old.setups["Old"].job else { panic!("gpu job") }; + assert!(options.lighting.is_none()); +} + +#[cfg(test)] +#[test] +fn saved_cpu_aging_is_optional_bounded_and_preserves_stable_targets_without_runtime_ordinals() { + use crate::render_aging::SavedAgingStack; + use crate::render_surface::RenderBodyTarget; + use solidcraft_render::job::aging::{AgingKind, AgingLayer}; + let old = CpuJob::default(); + assert!(serde_json::to_value(&old).unwrap().get("aging").is_none()); + let mut layers = SavedAgingStack::default(); + layers.push(AgingLayer::preset(AgingKind::Dust)).unwrap(); + let target = RenderBodyTarget { definition: "Aged panel".into(), feature: 19, component: 0, occurrence_path: Vec::new() }; + layers.get_mut(0).unwrap().target = Some(target.clone()); + let job = CpuJob { aging: layers.clone(), progressive: Some(Default::default()), denoise: true, ..Default::default() }; + job.validate(0.5).unwrap(); + assert!(job.to_runtime(0.5).unwrap_err().to_string().contains("stable occurrence")); + let setup = RenderSetup { + width: 8, + height: 8, + exposure_ev: 0.5, + job: Some(RenderJob::CpuRaytrace { transparent_background: true, options: Box::new(job) }), + ..Default::default() + }; + setup.validate().unwrap(); + let wire = serde_json::to_value(&setup).unwrap(); + assert_eq!(wire["job"]["options"]["aging"][0]["target"]["definition"], "Aged panel"); + assert!(wire["job"]["options"]["aging"][0]["target"].get("body_index").is_none()); + assert_eq!(serde_json::from_value::(wire.clone()).unwrap(), setup); + let mut legacy = wire.clone(); + legacy["job"]["options"]["aging"][0]["target"] = serde_json::json!({"body_index":0,"body_name":"Aged panel"}); + assert!(serde_json::from_value::(legacy).unwrap_err().to_string().contains("explicit rebinding")); + let mut nine = wire; + nine["job"]["options"]["aging"] = serde_json::json!(vec![serde_json::json!({}); 9]); + assert!(serde_json::from_value::(nine).is_err()); + layers.get_mut(0).unwrap().target = None; + let runtime = CpuJob { aging: layers, ..Default::default() }.to_runtime(0.5).unwrap(); + assert!(runtime.aging.unwrap().active()); +} + +#[cfg(test)] +mod cpu_adaptive_saved_tests { + use super::*; + use serde_json::json; + use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions}; + #[test] + fn saved_cpu_adaptive_intent_roundtrips_offline_and_pays_pilots_inside_the_existing_profile() { + let setup: RenderSetup = serde_json::from_value(json!({"width":128,"height":64, + "job":{"method":"cpu_raytrace","transparent_background":true,"options":{ + "progressive":{"samples_per_pixel":48,"seed":81},"adaptive":{"pilot_samples":16,"min_samples":16}, + "denoise":true,"path":{"max_depth":3},"output":{"linear_exr":true}}}})) + .unwrap(); + setup.validate().unwrap(); + let value = serde_json::to_value(&setup).unwrap(); + assert_eq!(serde_json::from_value::(value.clone()).unwrap(), setup); + let Some(RenderJob::CpuRaytrace { options, .. }) = setup.job.as_ref() else { panic!("CPU job expected") }; + let runtime = options.to_runtime(0.0).unwrap(); + assert_eq!(runtime.adaptive.as_deref().copied(), options.adaptive); + assert_eq!(runtime.preview_target().unwrap(), 64); + assert_eq!(runtime.camera_sampling().unwrap(), Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 81 })); + let mut too_large = setup.clone(); + too_large.width = 1024; + too_large.height = 1024; + assert!(too_large.validate().is_err(), "64 total passes exceed Compact's existing camera-sample bound"); + let mut cap = value.clone(); + cap["job"]["options"]["progressive"]["samples_per_pixel"] = json!(64); + assert!( + serde_json::from_value::(cap).unwrap().validate().is_err(), + "16 pilots cannot be hidden outside Compact's 64-sample cap" + ); + for (budget, maximum) in [(CpuBudget::Compact, 64), (CpuBudget::Studio, 1024), (CpuBudget::Workstation, 4096)] { + let mut runtime = runtime.clone(); + runtime.budget = budget; + runtime.progressive = Some(CpuProgressiveOptions { samples_per_pixel: maximum - 16, seed: 81 }); + assert_eq!(runtime.preview_target().unwrap(), maximum); + runtime.progressive.as_mut().unwrap().samples_per_pixel += 1; + assert!(runtime.validate().is_err(), "{budget:?} must include the pilot stage in its unchanged cap"); + } + let mut fixed = value.clone(); + fixed["job"]["options"].as_object_mut().unwrap().remove("progressive"); + assert!(serde_json::from_value::(fixed).unwrap().validate().is_err()); + let mut hostile = value; + hostile["job"]["options"]["adaptive"]["certified_convergence"] = json!(true); + assert!(serde_json::from_value::(hostile).is_err()); + let old = serde_json::to_value(CpuJob::default()).unwrap(); + assert!(old.get("adaptive").is_none(), "default-absent saved jobs keep their prior schema bytes"); + } +} + +#[cfg(test)] +mod saved_coat_tests { + use super::*; + use crate::{ + Document, + render_coat::{CoatMaterial, SavedCoat}, + render_surface::RenderBodyTarget, + }; + use serde_json::{Value, json}; + use std::sync::Arc; + + fn target(feature: u64) -> RenderBodyTarget { + RenderBodyTarget { definition: format!("Coated{feature}"), feature, component: 0, occurrence_path: vec![] } + } + fn document(gpu: bool) -> Document { + let mut doc = Document::default(); + let job = if gpu { + RenderJob::GpuPath { transparent_background: false, options: Default::default() } + } else { + RenderJob::CpuRaytrace { transparent_background: false, options: Default::default() } + }; + Arc::make_mut(&mut doc.render).setups.insert("Coated".into(), RenderSetup { width: 8, height: 8, job: Some(job), ..Default::default() }); + doc + } + #[test] + fn saved_coat_document_roundtrip_preserves_every_number_and_old_omission_for_both_methods() { + for gpu in [false, true] { + let mut doc = document(gpu); + let old = doc.to_json(); + let old_value: Value = serde_json::from_str(&old).unwrap(); + assert!(old_value["render"]["setups"]["Coated"].get("coats").is_none()); + assert_eq!(Document::from_json(&old).unwrap().to_json(), old); + let coat = CoatMaterial { weight: -0.0, roughness: 0.22, ior: 1.74 }; + Arc::make_mut(&mut doc.render).setups.get_mut("Coated").unwrap().coats.set(SavedCoat { target: target(1), coat }, false).unwrap(); + let encoded = doc.to_json(); + let loaded = Document::from_json(&encoded).unwrap(); + assert_eq!(loaded.render, doc.render); + let saved = loaded.render.setups["Coated"].coats.iter().next().unwrap(); + assert_eq!(saved.coat, coat); + assert_eq!(saved.coat.weight.to_bits(), (-0.0_f64).to_bits()); + let wire = serde_json::to_value(saved).unwrap(); + assert!(wire.get("body_index").is_none() && wire.get("body_name").is_none()); + assert!(wire["target"].get("feature").is_some()); + let setup = Arc::make_mut(&mut doc.render).setups.get_mut("Coated").unwrap(); + let changed = SavedCoat { target: target(1), coat: CoatMaterial { weight: 0.0, ..coat } }; + assert!(setup.coats.set(changed.clone(), false).is_err(), "authored signed zero is not silently replaced"); + setup.coats.set(changed, true).unwrap(); + assert_eq!(setup.coats.iter().next().unwrap().coat.weight.to_bits(), 0.0_f64.to_bits()); + assert!(setup.coats.remove(&target(1))); + assert_eq!(doc.to_json(), old, "removing the only coat restores exact legacy document bytes"); + } + } + #[test] + fn malformed_saved_coats_refuse_through_the_full_document_loader() { + let mut doc = document(false); + Arc::make_mut(&mut doc.render) + .setups + .get_mut("Coated") + .unwrap() + .coats + .set(SavedCoat { target: target(1), coat: Default::default() }, false) + .unwrap(); + let base: Value = serde_json::from_str(&doc.to_json()).unwrap(); + for (key, value) in + [("weight", json!(-0.01)), ("weight", json!(1.01)), ("roughness", json!(0.02)), ("ior", json!(3.01)), ("unknown", json!(true))] + { + let mut bad = base.clone(); + bad["render"]["setups"]["Coated"]["coats"][0]["coat"][key] = value; + assert!(Document::from_json(&bad.to_string()).is_err(), "invalid coat {key}"); + } + let mut duplicate = base.clone(); + let row = duplicate["render"]["setups"]["Coated"]["coats"][0].clone(); + duplicate["render"]["setups"]["Coated"]["coats"] = json!([row, row]); + assert!(Document::from_json(&duplicate.to_string()).is_err()); + for key in ["body_index", "runtime_path"] { + let mut bad = base.clone(); + bad["render"]["setups"]["Coated"]["coats"][0][key] = json!(0); + assert!(Document::from_json(&bad.to_string()).is_err()); + } + let mut too_many = base; + too_many["render"]["setups"]["Coated"]["coats"] = + json!((1..=65).map(|feature| SavedCoat { target: target(feature), coat: Default::default() }).collect::>()); + assert!(Document::from_json(&too_many.to_string()).is_err()); + } + #[test] + fn saved_coat_uses_existing_sixty_four_target_bound_and_rejects_glass_even_at_zero_weight() { + use crate::render_optics::{OpticalMaterial, SavedOptics}; + for gpu in [false, true] { + let mut doc = document(gpu); + let setup = Arc::make_mut(&mut doc.render).setups.get_mut("Coated").unwrap(); + for feature in 1..=64 { + setup.coats.set(SavedCoat { target: target(feature), coat: CoatMaterial { weight: 0.0, ..Default::default() } }, false).unwrap(); + } + setup.validate().unwrap(); + assert_eq!(setup.coats.len(), 64); + let before = setup.coats.clone(); + assert!(setup.coats.set(SavedCoat { target: target(65), coat: Default::default() }, false).is_err()); + assert_eq!(setup.coats, before); + setup.optics.set(SavedOptics { target: target(1), optics: OpticalMaterial::default() }, false).unwrap(); + assert!(setup.validate().unwrap_err().to_string().contains("cannot share")); + setup.optics.remove(&target(1)); + setup.job = Some(RenderJob::Raster { transparent_background: false }); + assert!(setup.validate().unwrap_err().to_string().contains("raytrace")); + assert_eq!(setup.coats, before, "unsupported method retains all authored rows"); + } + } +} + +#[cfg(test)] +mod cpu_celestial_saved_tests { + use super::*; + use serde_json::json; + #[test] + fn saved_cpu_finite_sun_and_sky_roundtrip_exactly_and_require_explicit_path() { + let value = json!({"width":16,"height":12,"job":{"method":"cpu_raytrace","transparent_background":true,"options":{ + "path":{"max_depth":4},"progressive":{"samples_per_pixel":32,"seed":81},"adaptive":{"pilot_samples":16,"min_samples":16}, + "sun":{"direction":[0.2,-0.3,0.9],"angular_radius_rad":0.02,"radiance":[301.25,202.5,103.75]}, + "sky":{"kind":"sky","gradient":{"zenith":[0.25,0.5,1.0],"horizon":[0.75,0.5,0.25],"ground":[0.125,0.25,0.5]},"rotation_rad":0.731,"intensity":75}, + "denoise":true,"output":{"linear_exr":true},"lights":[]}}}); + let setup: RenderSetup = serde_json::from_value(value.clone()).unwrap(); + setup.validate().unwrap(); + let wire = serde_json::to_value(&setup).unwrap(); + assert_eq!(serde_json::from_value::(wire.clone()).unwrap(), setup); + let Some(RenderJob::CpuRaytrace { options, .. }) = &setup.job else { panic!("CPU expected") }; + let runtime = options.to_runtime(0.0).unwrap(); + assert_eq!(runtime.sun.as_deref().copied(), options.sun); + assert_eq!(runtime.sky.as_deref().unwrap().intensity, 75.0); + assert_eq!(runtime.sky.as_deref().unwrap().rotation_rad, 0.731); + for (field, replacement) in [ + ("path", serde_json::Value::Null), + ("sun", json!({"direction":[0,0,1],"angular_radius_rad":0,"radiance":[1,1,1]})), + ("environment", json!({"color":[1,1,1],"intensity":1})), + ] { + let mut invalid = wire.clone(); + invalid["job"]["options"][field] = replacement; + assert!(serde_json::from_value::(invalid).unwrap().validate().is_err(), "{field} must not be silently replaced"); + } + for (field, value) in [("intensity", json!(100.001)), ("rotation_rad", json!(1e6 + 1.0))] { + let mut invalid = wire.clone(); + invalid["job"]["options"]["sky"][field] = value; + assert!(serde_json::from_value::(invalid).unwrap().validate().is_err()); + } + let defaults = serde_json::to_value(CpuJob::default()).unwrap(); + assert!(defaults.get("sun").is_none() && defaults.get("sky").is_none()); + } } diff --git a/crates/doc/src/render_surface.rs b/crates/doc/src/render_surface.rs index 24e818295..5653425b5 100644 --- a/crates/doc/src/render_surface.rs +++ b/crates/doc/src/render_surface.rs @@ -315,4 +315,66 @@ mod tests { target.occurrence_path = vec![2, 2]; assert!(target.validate().is_err()); } + #[test] + fn saved_cpu_surface_maps_roundtrip_for_opaque_direct_and_path_and_preserve_unsupported_intent() { + use crate::render_settings::{CpuJob, RenderJob, RenderSetup}; + let mut options = CpuJob::default(); + let mut setup = RenderSetup { + job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options.clone()) }), + ..Default::default() + }; + setup.surfaces.set(fixture(), false).unwrap(); + setup.validate().unwrap(); + let mut direct_document = crate::Document::default(); + std::sync::Arc::make_mut(&mut direct_document.render).setups.insert("Maps".into(), setup.clone()); + assert_eq!(crate::Document::from_json(&direct_document.to_json()).unwrap(), direct_document); + options.progressive = Some(solidcraft_render::job::CpuProgressiveOptions { samples_per_pixel: 16, seed: 9 }); + options.shadows = true; + options.path = Some(solidcraft_render::job::CpuPathOptions { max_depth: 3 }); + setup.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options.clone()) }); + setup.validate().unwrap(); + let mut document = crate::Document::default(); + std::sync::Arc::make_mut(&mut document.render).setups.insert("Maps".into(), setup.clone()); + assert_eq!(crate::Document::from_json(&document.to_json()).unwrap(), document); + options.path = None; + let saved_options_wire = serde_json::to_value(&options).unwrap(); + let mut runtime = options.to_runtime(0.0).unwrap(); + runtime.reflections = Some(solidcraft_render::job::ReflectionOptions { + bodies: vec![solidcraft_render::job::ReflectionBody { body: "Panel".into(), mode: solidcraft_render::job::ReflectionMode::Mirror }], + samples: 1, + max_bounces: 2, + }); + runtime.validate().unwrap(); + let runtime_wire = serde_json::to_value(&runtime).unwrap(); + let error = solidcraft_render::job::textures::validate_cpu_options(&runtime).unwrap_err(); + assert!(error.message.contains("selected reflections")); + assert_eq!(serde_json::to_value(&runtime).unwrap(), runtime_wire, "map refusal preserves the exact runtime selected override"); + assert_eq!(serde_json::to_value(&options).unwrap(), saved_options_wire, "runtime overrides do not rewrite saved CPU fields"); + setup.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options.clone()) }); + setup.validate().unwrap(); + let mut unknown = serde_json::to_value(&setup).unwrap(); + unknown["job"]["options"]["reflections"] = serde_json::to_value(&runtime.reflections).unwrap(); + let error = serde_json::from_value::(unknown).unwrap_err(); + assert!(error.to_string().contains("reflections"), "saved CPU intent must not silently discard runtime-only selected overrides"); + // Prove the saved field is supported in fixed mode before checking + // its incompatibility with still-authored progressive sampling. + let mut fixed = options.clone(); + fixed.progressive = None; + fixed.primary_samples = 4; + fixed.validate_surface_maps(0.0).unwrap(); + let surfaces = setup.surfaces.clone(); + options.primary_samples = 4; + setup.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options) }); + let wire = serde_json::to_value(&setup).unwrap(); + assert!(setup.validate().unwrap_err().to_string().contains("CPU progressive requires")); + assert_eq!(serde_json::to_value(&setup).unwrap(), wire); + assert_eq!(setup.surfaces, surfaces); + assert_eq!(setup.surfaces.len(), 1); + for job in [None, Some(RenderJob::Raster { transparent_background: false })] { + setup.job = job; + assert!(setup.validate().is_err()); + assert_eq!(setup.surfaces, surfaces); + assert_eq!(setup.surfaces.len(), 1); + } + } } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 377a0113e..e57efbc1c 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -95,6 +95,8 @@ mod parameters; mod plastic; mod print_face; mod render; +pub(crate) use render::{PreparedCapture, prepare_capture_with_metadata, render_cancel_params}; +pub(crate) use render_ui::batch_request; mod render_ui; #[cfg(test)] mod script_tests; diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index b0b8f12b5..a58b722d4 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -11,9 +11,11 @@ use crate::params::bad; use crate::{Result, Session}; mod clear_coat; +mod coat_bindings; mod effects; mod environment; mod jobs; +pub(crate) use jobs::{Prepared as PreparedCapture, cancel_params as render_cancel_params, prepare_with_metadata as prepare_capture_with_metadata}; mod library; mod library_data; #[cfg(test)] @@ -49,7 +51,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("render.environment.set", "Set Render Environment", crate::checked!("render.environment.set", environment::set)).icon("settings").doc_only() .contract(&environment::CONTRACT) .output(crate::schema::output_schema_for::) - .params("name; set?: numerical setup patch; rotation_deg?: finite degrees within +/-1000000, wrapped to [-180,180); intensity?: finite linear intensity 0..64 CPU or 0..100 GPU. Edits the existing HDR, sky or constant environment in one undo, without selecting a source, moving the camera or starting a render. Absent environments and raster refuse."), + .params("name; set?: numerical setup patch; rotation_deg?: finite degrees within +/-1000000, wrapped to [-180,180); intensity?: finite linear intensity 0..64 CPU HDR/constant or 0..100 CPU/GPU Sky and GPU HDR. Edits the existing HDR, sky or constant environment in one undo, without selecting a source, moving the camera or starting a render. Absent environments and raster refuse."), CommandSpec::new("render.lights.set", "Set Render Light", crate::checked!("render.lights.set", lights::set)) .icon("render_scene").doc_only() .contract(&crate::schema::TypedContract::::new()) @@ -79,8 +81,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("Empty object. Read-only original Rust/patina/dust/grime/scratch/chip/fading presets and exact GPU aging contract. UI activation opens the shared Aging tab; edits remain a saved render draft, never engineering geometry or material-property mutation."), CommandSpec::new("render.effects.describe","Lens and Creative Effects",effects::presentation).icon("camera").noundo().doc_only() .params("Empty object. Read-only original photographic/creative filter defaults and constraints. UI activation opens shared Effects controls. Saved finishing and exact-master regrading preserve raw EXR bytes; no physical lens or branded-film calibration is implied."), + CommandSpec::new("render.coat.bind", "Save Clear Coat", crate::checked!("render.coat.bind", coat_bindings::bind)).icon("appearance").doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("name; set?: numerical setup patch; body_index/body_name: exact render.scene identity; expected_revision; coat:{weight:0..1,roughness:0.045..1,ior:1..3}; replace?:false. Stores up to the existing 64 target bound as stable definition/feature/component/occurrence bindings for CPU/GPU. Even zero-weight coats require opaque targets. Same-target Glass refuses. One undo; no geometry, engineering material or appearance mutation."), + CommandSpec::new("render.coat.unbind", "Remove Clear Coat", crate::checked!("render.coat.unbind", coat_bindings::unbind)).icon("appearance").doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("name; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that stable coat assignment in one undo, without device or file access."), CommandSpec::new("render.optics.bind","Save Optical Binding",optical_bindings::bind).icon("appearance") - .params("name: GPU setup; set?: complete numerical setup patch; body_index and body_name: exact captured target; expected_revision; optics:{ior,absorption_per_mm:[r,g,b],boundary:closed_mesh|closed_box|thin_sheet,thickness_mm,shadow_transmission,subsurface?:{scattering_per_mm,anisotropy}}; replace?:false. Stores stable definition/feature/occurrence identity in one undo without modifying engineering geometry/materials. Nested media require separate job.options.nested_media and producer certification. Unresolved or incompatible targets refuse atomically."), + .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."), CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only() .params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."), CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only() @@ -94,15 +104,15 @@ CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon(" CommandSpec::new("render.preset.resolve", "Review Native Studio", crate::checked!("render.preset.resolve", studio_presets::resolve)).icon("render_scene").noundo() .contract(&studio_presets::PRESET_CONTRACT) .output(crate::schema::output_schema_for::) - .params("id: NATIVE-STUDIO-001..025; name; set?: typed GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."), + .params("id: NATIVE-STUDIO-001..025; name; set?: typed CPU/GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."), CommandSpec::new("render.preset.apply", "Apply Native Studio", crate::checked!("render.preset.apply", studio_presets::apply)).icon("render_scene") .contract(&studio_presets::PRESET_CONTRACT) .output(crate::schema::output_schema_for::) .params("Same reviewed input as render.preset.resolve, expected_revision required, replace_lighting_and_environment:true and replace_stage:true when an existing stage would change. Re-resolves the complete candidate and publishes one undo or no mutation; camera, optical bindings, geometry and engineering materials are preserved."), CommandSpec::new("render.quality.prepare", "Review Fixed Sampling Budget", crate::checked!("render.quality.prepare", studio_presets::quality)).icon("settings").noundo().doc_only() .contract(&studio_presets::QUALITY_CONTRACT) - .output(crate::schema::output_schema_for::) - .params("id: Q-*; variant:fixed_samples_png; acknowledge_omissions:true. Read-only bounded GPU still-budget projection, not full adaptive/convergence/linear-master quality acceptance. Returns dimensions/samples/depth/seed/denoise and explicit omissions. Never switches executor or mutates a shot."), + .output(crate::schema::output_schema_for::) + .params("id: Q-*; variant:fixed_samples_png for the existing GPU projection, or cpu_progressive_png for Q-001/002/003 CPU cost budgets; acknowledge_omissions:true. Optional cpu:{minimum_budget:compact|studio|workstation,adaptive?:captured AdaptiveSampling} selects the smallest existing profile admitting pilots plus production without lowering minimum_budget. CPU budgets use authored sizes, 16/32/64 production samples and seed21026; preserve transport depth, denoise, optics and effects. Read-only numerical projections, not convergence/time guarantees or complete quality acceptance. Never switches executor, adopts fixed CPU sampling or mutates a shot."), CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", crate::checked!("render.shot.duplicate", shots::duplicate)).icon("copy").doc_only() .contract(&shots::CONTRACT) .output(crate::schema::output_schema_for::) @@ -134,7 +144,7 @@ CommandSpec::new("render.stage.clear", "Remove Render Stage", crate::checked!("r .output(crate::schema::output_schema_for::) .params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."), CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance") - .params("name: GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."), + .params("name: CPU or GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."), CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only() .params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."), CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only() @@ -156,11 +166,11 @@ CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appear CommandSpec::new("render.library.environment.apply", "Apply Built-in HDR Environment", library::apply_environment).icon("settings").doc_only() .params("id: HDR-*; name: saved setup; set?: typed CPU/GPU setup patch; rotation_rad?: authored rotation (native origin offset is explicit in the reply); intensity?:1; samples?:16 for CPU; replace_environment?:false. Hash-verifies and embeds original bytes, saves one atomic undo without external files or a render device. An HDR-owned sun cannot duplicate an analytic sun."), CommandSpec::new("render.library.surface.prepare", "Prepare Authored Surface Maps", library::prepare_surface).icon("appearance").noundo() - .params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1; rotation_rad?:0 (positive around the plane normal). Returns an explicit GPU planar map binding with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."), + .params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1; rotation_rad?:0 (positive around the plane normal). Returns an explicit GPU temporary planar binding and a source usable by saved CPU/GPU surface.bind, with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."), CommandSpec::new("render.library.studio.prepare", "Prepare Authored Studio Lights", library::prepare_studio).icon("inspect").noundo().doc_only() - .params("id: RIG-*; variant: complete for emitter-only rigs, emitters_only for rigs with passive cards; center_mm and subject_extent_mm required. Converts exact rectangular half-edges and solar direction/radius to GPU lighting. Blocked calibration and external-sun rigs refuse. Returns a geometry-clearance review requirement; does not create cards or modify the scene."), + .params("id: RIG-*; variant: complete for emitter-only rigs, emitters_only for rigs with passive cards; center_mm and subject_extent_mm required. Converts exact rectangular half-edges and solar direction/radius. Optional name and typed CPU set return the complete CPU projection and explicit indirect-lighting adoption plan; authored radiance beyond CPU intensity64 refuses without scaling. Blocked calibration and external-sun rigs refuse. Returns a geometry-clearance review requirement; does not create cards or modify the scene."), CommandSpec::new("render.library.studio.apply", "Apply Authored Studio Lights", library::apply_studio).icon("settings") - .params("rig: render.library.studio.prepare parameters; name; set?: typed GPU setup patch; replace_lighting_and_environment:true required. Saves the explicit rig projection in one undo, removing prior lighting/environment only with that confirmation. Subject clearance still needs review; passive cards are never silently omitted."), + .params("rig: id, variant, center_mm and subject_extent_mm; name; set?: typed CPU/GPU setup patch; expected_revision?:u64; enable_indirect?:false (explicit CPU Sun adoption after review); replace_lighting_and_environment:true required. Saves the explicit rig projection in one undo, removing prior lighting/environment only with that confirmation. Subject clearance still needs review; passive cards are never silently omitted."), CommandSpec::new("render.hdr.inspect", "Inspect HDR Source", crate::checked!("render.hdr.inspect", resources::inspect)).icon("inspect").noundo().doc_only() .contract(&resources::INSPECT_CONTRACT) .output(crate::schema::output_schema_for::) @@ -170,7 +180,7 @@ CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", .output(crate::schema::output_schema_for::) .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.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; no area/LED, anisotropy or dielectrics in this initial mode. See docs/render-cpu-progressive.md; environment?: {path: scoped HDR, expected_sha256?: inspected digest, rotation_radians: 0, intensity: 1, samples: 16} OR {resource: saved HDR digest, rotation_radians, intensity, samples}; embedded resources cannot combine with path/hash; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS or GI. CPU runtime dielectrics support only certified thin_sheet/closed_box boundaries with explicit IOR and Beer absorption; see docs/render-raytrace-dielectrics.md. CPU emissions are visible radiance only; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/64 for the whole strip, default16. At most8directional+8punctual+4rectangle/LED sources; shared area N. See docs/render-light-union.md. transparent_background?: false; replace?: false. With progressive:true, raytrace instead accepts GPU dielectrics/clear_coats/textures; environment instead accepts tagged hdr/embedded_hdr/sky with rotation_rad/intensity; file hdr supports expected_sha256, embedded_hdr uses a document resource digest. See docs/render-hdr-resources.md. GPU lens, studio lighting, tone_map, denoise, bounded finishing/backdrop and linear_exr retention are also available. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"), + .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace 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"), 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() @@ -180,7 +190,7 @@ CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete"). CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only() .params("job?: completed JobId (default selected result). Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only() - .params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), + .params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed CPU or GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), CommandSpec::new("render.backends", "Render Backends", backends).icon("list") .noundo() .doc_only() @@ -188,7 +198,7 @@ CommandSpec::new("render.backends", "Render Backends", backends).icon("list") CommandSpec::new("render.settings.get", "Render Settings", get_settings).icon("settings").noundo().doc_only() .params("name?: saved setup. Without name returns {setups, defaults}; with name returns {name, setup}. Does not evaluate the model or apply a camera. See docs/render-settings.md"), CommandSpec::new("render.settings.set", "Save Render Settings", set_settings).icon("settings").doc_only() - .params("name: setup name, set: object of fields to replace (backend, mode, camera, width, height, format, exposure_ev, environment_rotation, environment_intensity, background, job, surfaces, stage). job?: typed active raster/cpu_raytrace/gpu_path configuration with optional validated embedded HDR reference; omitted preserves, null clears, object replaces the complete job. Creates from defaults and saves without a host, validates atomically, one undo step; identical edits are no-ops. See docs/render-settings.md"), + .params("name: setup name, set: object of fields to replace (backend, mode, camera, width, height, format, exposure_ev, environment_rotation, environment_intensity, background, job, surfaces, optics, coats, stage). job?: typed active raster/cpu_raytrace/gpu_path configuration with optional validated embedded HDR reference; omitted preserves, null clears, object replaces the complete job. Creates from defaults and saves without a host, validates atomically, one undo step; identical edits are no-ops. See docs/render-settings.md"), CommandSpec::new("render.scene", "Inspect Render Scene", scene).noundo().at("RENDER", "SCENE").icon("render_scene") .params("No parameters. Authoritative product-scene metadata, without modelling overlays or mesh payloads. Explicitly settles stale geometry; does not render an image. See docs/render-workspace.md"), CommandSpec::new("render.settings.apply", "Apply Render Camera", apply_settings).icon("camera").noundo().doc_only() @@ -220,9 +230,13 @@ fn fit_camera(s: &mut Session, params: &Value) -> Result { Some(p) if p.len() == 1 && p.contains_key("aspect") => match p["aspect"].as_f64() { // The range a preview frame can show (`frame_rect` in the Render workspace). Some(a) if (1e-6..=1e6).contains(&a) => a, - _ => return Err(bad("render.camera.fit", "aspect must be a number from 0.000001 to 1000000: the picture's width over its height")), + _ => { + return Err(bad("render.camera.fit", "aspect must be a number from 0.000001 to 1000000: the picture's width over its height")); + } }, - _ => return Err(bad("render.camera.fit", "expected an empty parameter object or {aspect}")), + _ => { + return Err(bad("render.camera.fit", "expected an empty parameter object or {aspect}")); + } }; let scene = crate::product_scene::extract(s)?; let mut camera = s.camera.unwrap_or_default(); @@ -309,7 +323,10 @@ fn set_settings(s: &mut Session, params: &Value) -> Result { fn patched_settings(s: &Session, name: &str, set: &Value, cmd: &str) -> Result { RenderSettings::validate_name(name).map_err(|e| bad(cmd, e.to_string()))?; - let patch = set.as_object().filter(|p| p.len() <= 13).ok_or_else(|| bad(cmd, "`set` must be an object with at most 13 fields"))?; + // A full RenderSetup has 15 known fields, including maps, optics, coats and + // stage. Bound the patch by that schema; decoding below still rejects any + // unknown field instead of silently dropping saved intent. + let patch = set.as_object().filter(|p| p.len() <= 15).ok_or_else(|| bad(cmd, "`set` must be an object with at most 15 fields"))?; let current = s.doc.render.setups.get(name).cloned().unwrap_or_default(); let mut value = serde_json::to_value(¤t).map_err(|e| bad(cmd, e.to_string()))?; let object = value.as_object_mut().ok_or_else(|| bad(cmd, "invalid render setup"))?; diff --git a/crates/engine/src/cmd/render/clear_coat.rs b/crates/engine/src/cmd/render/clear_coat.rs index 4e71dc325..b9888f25d 100644 --- a/crates/engine/src/cmd/render/clear_coat.rs +++ b/crates/engine/src/cmd/render/clear_coat.rs @@ -18,7 +18,7 @@ pub(super) struct Override { ior: f64, } pub(super) fn apply(scene: &mut ProductScene, overrides: &[Override], command: &str) -> Result<()> { - if overrides.len() > 64 { + if overrides.len() > solidcraft_doc::render_coat::MAX_COAT_BINDINGS { return Err(bad(command, "at most 64 runtime clear-coat overrides are supported")); } let mut ordinals = std::collections::BTreeSet::new(); @@ -31,28 +31,33 @@ pub(super) fn apply(scene: &mut ProductScene, overrides: &[Override], command: & return Err(bad(command, "clear coats require bounded names and distinct captured body ordinals")); } let coat = ClearCoat::new(input.weight, input.roughness, input.ior).map_err(|e| bad(command, e.to_string()))?; - let body = scene - .meshes - .get_mut(input.body_index) - .filter(|m| m.name == input.body_name) - .ok_or_else(|| bad(command, "clear-coat body ordinal and exact name must both match render.scene"))?; - // A zero-weight override is a true no-op, including legacy appearances. - if coat.weight() == 0.0 { - continue; - } - if body.transmission.is_some() || body.faces.iter().any(|f| f.transmission.is_some()) { - return Err(bad(command, "clear coat and transmission cannot share a body")); - } - let surface = |color: [u8; 3], existing: Option| -> Result { - let [r, g, b] = color.map(srgb8_to_linear); - let base = - existing.map(Ok).unwrap_or_else(|| OpaqueSurface::new(Vec3::new(r, g, b), 0.0, 0.5, 1.5)).map_err(|e| bad(command, e.to_string()))?; - Ok(base.with_clear_coat(coat)) - }; - body.surface = Some(surface(body.color, body.surface)?); - for face in &mut body.faces { - face.surface = Some(surface(face.color, face.surface)?); - } + apply_one(scene, input.body_index, &input.body_name, coat, command)?; + } + Ok(()) +} + +pub(super) fn apply_one(scene: &mut ProductScene, body_index: usize, body_name: &str, coat: ClearCoat, command: &str) -> Result<()> { + let body = scene + .meshes + .get_mut(body_index) + .filter(|m| m.name == body_name) + .ok_or_else(|| bad(command, "clear-coat body ordinal and exact name must both match render.scene"))?; + // A zero-weight override is a true no-op, including legacy appearances. + if coat.weight() == 0.0 { + return Ok(()); + } + if body.transmission.is_some() || body.faces.iter().any(|f| f.transmission.is_some()) { + return Err(bad(command, "clear coat and transmission cannot share a body")); + } + let surface = |color: [u8; 3], existing: Option| -> Result { + let [r, g, b] = color.map(srgb8_to_linear); + let base = + existing.map(Ok).unwrap_or_else(|| OpaqueSurface::new(Vec3::new(r, g, b), 0.0, 0.5, 1.5)).map_err(|e| bad(command, e.to_string()))?; + Ok(base.with_clear_coat(coat)) + }; + body.surface = Some(surface(body.color, body.surface)?); + for face in &mut body.faces { + face.surface = Some(surface(face.color, face.surface)?); } Ok(()) } @@ -85,3 +90,149 @@ mod tests { assert!(apply(&mut original.clone(), &duplicate, "render.start").is_err()); } } + +#[cfg(test)] +mod stable_tests { + use super::*; + use crate::Session; + use serde_json::json; + use solidcraft_doc::render_coat::{CoatBindings, CoatMaterial, SavedCoat}; + use std::sync::Arc; + + #[test] + fn stable_coats_save_reopen_replace_and_undo_offline_for_cpu_and_gpu_without_changing_sources() { + for method in ["cpu_raytrace", "gpu_path"] { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Housing"})).unwrap(); + s.execute("material.assign", &json!({"bodies":["Housing"],"material":"Steel"})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Coat","set":{"width":8,"height":8,"job":{"method":method}}})).unwrap(); + let physical = s.execute("component.properties", &json!({})).unwrap(); + let model = s.model.state(); + let before = s.doc.clone(); + let undo = s.undo.len(); + let evaluations = s.evaluations; + let coat = json!({"weight":0.63,"roughness":0.61,"ior":1.7}); + s.execute("render.coat.bind", &json!({"name":"Coat","body_index":0,"body_name":"Housing","coat":coat,"expected_revision":s.revision})) + .unwrap(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.evaluations, evaluations); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(s.doc.features, before.features); + assert_eq!(s.doc.materials, before.materials); + assert_eq!(physical, s.execute("component.properties", &json!({})).unwrap()); + let saved = s.doc.clone(); + let loaded = solidcraft_doc::Document::from_json(&saved.to_json()).unwrap(); + assert_eq!(loaded.render, saved.render); + let original = crate::product_scene::extract(&s).unwrap(); + let mut scene = original.clone(); + let faces_capacity = scene.meshes[0].faces.capacity(); + let cpu = solidcraft_render::job::RaytraceOptions::default(); + super::super::coat_bindings::apply( + &s, + &mut scene, + &saved.render.setups["Coat"].coats, + (method == "cpu_raytrace").then_some(&cpu), + "check", + ) + .unwrap(); + let actual = scene.meshes[0].surface.unwrap().clear_coat().unwrap(); + assert_eq!((actual.weight(), actual.roughness(), actual.ior()), (0.63, 0.61, 1.7)); + assert!(Arc::ptr_eq(&original.meshes[0].mesh, &scene.meshes[0].mesh)); + assert_eq!(original.meshes[0].faces.len(), scene.meshes[0].faces.len()); + assert_eq!(faces_capacity, scene.meshes[0].faces.capacity()); + assert_eq!(s.doc, saved, "captured coat never changes the source appearance"); + for face in &scene.meshes[0].faces { + assert_eq!(face.surface.unwrap().clear_coat(), Some(actual)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + let replacement = json!({"name":"Coat","body_index":0,"body_name":"Housing","coat":{"weight":0.4,"roughness":0.3,"ior":1.8},"expected_revision":s.revision}); + assert!(s.execute("render.coat.bind", &replacement).is_err()); + assert_eq!(s.doc, saved); + let mut explicit = replacement; + explicit["replace"] = json!(true); + s.execute("render.coat.bind", &explicit).unwrap(); + assert_eq!(s.doc.render.setups["Coat"].coats.iter().next().unwrap().coat.ior, 1.8); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + let target = saved.render.setups["Coat"].coats.iter().next().unwrap().target.clone(); + s.execute("render.coat.unbind", &json!({"name":"Coat","target":target,"expected_revision":s.revision})).unwrap(); + assert!(s.doc.render.setups["Coat"].coats.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + } + } + #[test] + fn stable_coat_source_replacement_hidden_and_glass_guards_never_guess_or_mutate_a_binding() { + for method in ["cpu_raytrace", "gpu_path"] { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Housing"})).unwrap(); + s.execute( + "render.coat.bind", + &json!({"name":"Coat","set":{"width":4,"height":4,"job":{"method":method}}, + "body_index":0,"body_name":"Housing","coat":{"weight":0},"expected_revision":s.revision}), + ) + .unwrap(); + let saved = s.doc.render.setups["Coat"].coats.clone(); + let target = saved.iter().next().unwrap().target.clone(); + let original = crate::product_scene::extract(&s).unwrap(); + let mut zero = original.clone(); + super::super::coat_bindings::apply(&s, &mut zero, &saved, None, "check").unwrap(); + assert_eq!(zero.meshes[0].surface, original.meshes[0].surface); + assert!(Arc::ptr_eq(&zero.meshes[0].mesh, &original.meshes[0].mesh)); + let before = s.doc.clone(); + assert!( + s.execute( + "render.optics.bind", + &json!({"name":"Coat","body_index":0,"body_name":"Housing","optics":{},"expected_revision":s.revision}) + ) + .is_err() + ); + assert_eq!(s.doc, before, "zero weight is authored opaque intent, not permission to silently drop it on Glass"); + let mut glass = original; + glass.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap()); + assert!(super::super::coat_bindings::apply(&s, &mut glass, &saved, None, "check").unwrap_err().to_string().contains("opaque")); + s.execute("browser.visibility", &json!({"items":["Housing"],"visible":false})).unwrap(); + let mut hidden = crate::product_scene::extract(&s).unwrap(); + assert!(super::super::coat_bindings::apply(&s, &mut hidden, &saved, None, "check").unwrap_err().to_string().contains("hidden")); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("timeline.delete", &json!({"feature":target.feature.to_string()})).unwrap(); + s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Housing"})).unwrap(); + let mut replaced = crate::product_scene::extract(&s).unwrap(); + assert_eq!((replaced.meshes.len(), replaced.meshes[0].name.as_str()), (1, "Housing")); + assert!(super::super::coat_bindings::apply(&s, &mut replaced, &saved, None, "check").unwrap_err().to_string().contains("changed")); + assert_eq!(s.doc.render.setups["Coat"].coats, saved); + // Empty means the original capture path, even when no old target survives. + super::super::coat_bindings::apply(&s, &mut replaced, &CoatBindings::default(), None, "check").unwrap(); + } + } + #[test] + fn stable_cpu_coats_refuse_selected_transport_but_leave_authored_values_and_scene_sources_intact() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Housing"})).unwrap(); + let target = super::super::surface_bindings::targets(&s, "check").unwrap().into_keys().next().unwrap(); + let mut bindings = CoatBindings::default(); + bindings.set(SavedCoat { target, coat: CoatMaterial::default() }, false).unwrap(); + let scene = crate::product_scene::extract(&s).unwrap(); + let options = solidcraft_render::job::RaytraceOptions { + reflections: Some(solidcraft_render::job::ReflectionOptions { + samples: 1, + max_bounces: 1, + bodies: vec![solidcraft_render::job::ReflectionBody { + body: "Housing".into(), + mode: solidcraft_render::job::ReflectionMode::RoughSpecular, + }], + }), + ..Default::default() + }; + let before = s.doc.clone(); + let mut captured = scene.clone(); + let error = super::super::coat_bindings::apply(&s, &mut captured, &bindings, Some(&options), "check").unwrap_err().to_string(); + assert!(error.contains("selected reflection")); + assert_eq!(captured.meshes[0].surface, scene.meshes[0].surface); + assert_eq!(bindings.iter().next().unwrap().coat, CoatMaterial::default()); + assert_eq!(s.doc, before); + } +} diff --git a/crates/engine/src/cmd/render/coat_bindings.rs b/crates/engine/src/cmd/render/coat_bindings.rs new file mode 100644 index 000000000..d7fdf8800 --- /dev/null +++ b/crates/engine/src/cmd/render/coat_bindings.rs @@ -0,0 +1,124 @@ +//! Stable opaque clear-coat bindings shared by CPU and GPU scene capture. +//! Lowering changes only already-sized captured surface fields, never render options. +use crate::{Result, Session, params::bad}; +use serde_json::{Value, json}; +use solidcraft_doc::{ + render_coat::{CoatBindings, SavedCoat}, + render_settings::RenderJob, + render_surface::RenderBodyTarget, +}; +use solidcraft_render::{ProductScene, job::RaytraceOptions}; +use std::{collections::BTreeMap, sync::Arc}; + +/// No bindings is the original zero-allocation capture path. Even zero-weight +/// authored bindings require a current opaque target; they cannot mask Glass. +pub(super) fn apply(s: &Session, scene: &mut ProductScene, bindings: &CoatBindings, cpu: Option<&RaytraceOptions>, command: &str) -> Result<()> { + if bindings.is_empty() { + return Ok(()); + } + bindings.validate().map_err(|e| bad(command, e.to_string()))?; + let identities = super::surface_bindings::targets(s, command)?; + // The shared resolver indexes authored source identity. This additional + // captured-name index is bounded by the 64 requested targets, not scene size. + let mut visible = BTreeMap::new(); + for binding in bindings.iter() { + let name = identities.get(&binding.target).ok_or_else(|| bad(command, "saved clear-coat target changed; explicit rebinding required"))?; + if visible.insert(name.as_str(), None).is_some() { + return Err(bad(command, "ambiguous stable clear-coat world target")); + } + } + for (index, body) in scene.meshes.iter().enumerate() { + if let Some(slot) = visible.get_mut(body.name.as_str()) + && slot.replace(index).is_some() + { + return Err(bad(command, "ambiguous captured clear-coat target")); + } + } + let mut resolved = Vec::new(); + resolved.try_reserve_exact(bindings.len()).map_err(|_| bad(command, "could not reserve clear-coat capture metadata"))?; + if resolved.capacity() != bindings.len() { + return Err(bad(command, "clear-coat capture capacity exceeds admission")); + } + for binding in bindings.iter() { + let name = identities.get(&binding.target).ok_or_else(|| bad(command, "saved clear-coat target changed; explicit rebinding required"))?; + let index = visible.get(name.as_str()).copied().flatten().ok_or_else(|| bad(command, "saved clear-coat target is hidden or absent"))?; + let body = scene.meshes.get(index).ok_or_else(|| bad(command, "clear-coat target disappeared"))?; + if body.transmission.is_some() || body.faces.iter().any(|face| face.transmission.is_some()) { + return Err(bad(command, "saved clear coat requires an opaque target, including zero-weight authored coats")); + } + if cpu.is_some_and(|options| { + options.dielectrics.iter().any(|entry| entry.body_index == index) + || options.reflections.as_ref().is_some_and(|overrides| overrides.bodies.iter().any(|entry| entry.body == *name)) + || options.anisotropic_faces.iter().flatten().any(|entry| entry.body_index == index) + }) { + return Err(bad(command, "CPU clear-coat targets cannot share Glass, selected reflection or anisotropy overrides")); + } + resolved.push((index, name.as_str(), binding.coat.to_runtime().map_err(|e| bad(command, e.to_string()))?)); + } + drop(visible); + for (index, name, coat) in resolved { + super::clear_coat::apply_one(scene, index, name, coat, command)?; + } + Ok(()) +} + +pub(super) fn bind(s: &mut Session, params: &Value) -> Result { + let command = "render.coat.bind"; + let input: crate::schema::render::CoatBindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let coat = input.coat.material(); + coat.validate().map_err(|e| bad(command, e.to_string()))?; + if input.expected_revision != s.revision { + return Err(bad(command, "clear-coat binding review is stale")); + } + let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; + if s.doc.render.setups.get(&input.name).is_some_and(|old| old.coats != setup.coats) { + return Err(bad(command, "setup patch cannot replace saved clear coats; use explicit bind/unbind")); + } + if !matches!(setup.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) { + return Err(bad(command, "saved clear coats require an explicit CPU or GPU raytrace setup")); + } + let mut scene = crate::product_scene::extract(s)?; + let name = &scene + .meshes + .get(input.body_index) + .filter(|body| body.name == input.body_name) + .ok_or_else(|| bad(command, "clear-coat target ordinal and exact name do not match"))? + .name; + let identities = super::surface_bindings::targets(s, command)?; + let mut candidates = identities.iter().filter(|(_, world)| *world == name); + let target = + candidates.next().map(|(target, _)| target.clone()).ok_or_else(|| bad(command, "clear-coat target has no stable source identity"))?; + if candidates.next().is_some() { + return Err(bad(command, "ambiguous clear-coat target identity")); + } + setup.coats.set(SavedCoat { target, coat }, input.replace).map_err(|e| bad(command, e.to_string()))?; + setup.validate().map_err(|e| bad(command, e.to_string()))?; + // Verify the actual opaque source even for inactive authored values. Runtime + // options are not invented while saving an offline stable numerical setup. + apply(s, &mut scene, &setup.coats, None, command)?; + let mut settings = (*s.doc.render).clone(); + settings.setups.insert(input.name.clone(), setup.clone()); + settings.validate().map_err(|e| bad(command, e.to_string()))?; + if settings != *s.doc.render { + s.doc_mut().render = Arc::new(settings); + } + Ok(json!({"name":input.name,"setup":setup,"geometry_and_engineering_unchanged":true})) +} + +pub(super) fn unbind(s: &mut Session, params: &Value) -> Result { + let command = "render.coat.unbind"; + let input: crate::schema::render::CoatUnbindParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let target: RenderBodyTarget = serde_json::from_value(input.target).map_err(|e| bad(command, e.to_string()))?; + target.validate().map_err(|e| bad(command, e.to_string()))?; + if input.expected_revision != s.revision { + return Err(bad(command, "clear-coat removal review is stale")); + } + let mut settings = (*s.doc.render).clone(); + let setup = settings.setups.get_mut(&input.name).ok_or_else(|| bad(command, "unknown clear-coat setup"))?; + let removed = setup.coats.remove(&target); + settings.validate().map_err(|e| bad(command, e.to_string()))?; + if settings != *s.doc.render { + s.doc_mut().render = Arc::new(settings); + } + Ok(json!({"name":input.name,"removed":removed})) +} diff --git a/crates/engine/src/cmd/render/effects.rs b/crates/engine/src/cmd/render/effects.rs index d46c4264f..7002ad7be 100644 --- a/crates/engine/src/cmd/render/effects.rs +++ b/crates/engine/src/cmd/render/effects.rs @@ -13,9 +13,9 @@ fn empty(p: &Value, command: &str) -> Result<()> { } pub(super) fn aging(_: &mut Session, p: &Value) -> Result { empty(p, "render.aging.describe")?; - Ok(json!({"maximum_layers":8,"storage":"GPU saved job.options.aging","order":"bottom to top; later layers modify earlier surface results", + Ok(json!({"maximum_layers":8,"storage":"CPU/GPU saved job.options.aging","order":"bottom to top; later layers modify earlier surface results", "presets":AgingKind::ALL.map(AgingLayer::preset),"target":"all eligible opaque bodies or stable definition/feature/component/occurrence identity; capture indices are resolved only for the runtime job; passive stages and glass are excluded", - "coordinate_space":"world millimetres, explicit origin and 4096-cell periodic field; not object-following motion", + "coordinate_space":"world millimetres, explicit origin; 4096-cell periodic noise with directional Scratch bands; not object-following motion", "preserves":["engineering geometry","mass and physical material cards","pose","source textures","visibility"], "limitations":["authored optical weathering, not measured corrosion or age prediction","no geometric grooves or edge-curvature detection","no aging on glass or participating-medium boundaries","stack changes transport and requires a new render"], "airborne":"use the separately validated finite homogeneous GPU medium; it is not deposited surface dust or a physical lunar atmosphere"})) diff --git a/crates/engine/src/cmd/render/environment.rs b/crates/engine/src/cmd/render/environment.rs index 04ed92152..2d67d5027 100644 --- a/crates/engine/src/cmd/render/environment.rs +++ b/crates/engine/src/cmd/render/environment.rs @@ -29,9 +29,11 @@ pub(super) fn set(s: &mut crate::Session, params: &serde_json::Value) -> Result< .transpose()?; let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; let (angle, intensity, maximum) = match &mut setup.job { - Some(RenderJob::CpuRaytrace { options }) => { + Some(RenderJob::CpuRaytrace { options, .. }) => { if let Some(hdr) = &mut options.hdr { (Some(&mut hdr.rotation_rad), &mut hdr.intensity, 64.0) + } else if let Some(SkyEnvironment::Sky { rotation_rad, intensity, .. }) = &mut options.sky { + (Some(rotation_rad), intensity, 100.0) } else if let Some(environment) = &mut options.environment { (None, &mut environment.intensity, 64.0) } else { diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rs index a41131825..baebd37c3 100644 --- a/crates/engine/src/cmd/render/job_tests.rs +++ b/crates/engine/src/cmd/render/job_tests.rs @@ -104,7 +104,12 @@ fn saved_gpu_job_routes_before_dispatch_and_reaches_preflight_and_start_without_ "width":4,"height":4,"camera":camera,"exposure_ev":1.75,"job":{"method":"gpu_path","transparent_background":true,"options":{ "samples":7,"max_depth":3,"seed":456,"denoise":true,"tone_map":"aces_fitted", "lens":{"aperture_radius_mm":0.5,"focus_distance_mm":20}, - "lighting":{"environment":[0.1,0.3,0.6],"sun":{"direction":[1,-1,-1],"angular_radius_rad":0.05,"radiance":[2,3,4]},"area_lights":[]}, + "lighting":{"environment":[0.1,0.3,0.6],"sun":{"direction":[1,-1,-1],"angular_radius_rad":0.05,"radiance":[2,3,4]},"area_lights":[],"directional_lights":[ + {"direction":[0,0,2],"color":[0.25,0.5,1],"intensity":0}, + {"direction":[3,-4,5],"color":[0.6,0.4,0.2],"intensity":2.5}],"punctual_lights":[ + {"position_mm":[1.25,-2.5,4.75],"color":[0.25,0.5,1],"intensity":2,"reference_distance_mm":4.5,"minimum_distance_mm":0.002}, + {"position_mm":[4,5,6],"color":[1,0.5,0.25],"intensity":3,"reference_distance_mm":7,"minimum_distance_mm":0.003, + "cone":{"emitted_axis":[-4,-5,-6],"inner_half_angle_radians":0.2,"outer_half_angle_radians":0.7}}]}, "environment":{"kind":"sky","rotation_rad":0.75,"intensity":0.5,"gradient":{"zenith":[0.3,0.2,0.1],"horizon":[0.8,0.5,0.3],"ground":[0.1,0.1,0.1]}} }} }})).unwrap(); @@ -128,8 +133,40 @@ fn saved_gpu_job_routes_before_dispatch_and_reaches_preflight_and_start_without_ assert_eq!(checked["options"]["exposure_ev"], 1.75); assert_eq!(checked["options"]["samples"], 7); assert_eq!(checked["options"]["lighting"]["environment"], json!([0.1, 0.3, 0.6])); + let captured_options: JobOptions = serde_json::from_value(checked["options"].clone()).unwrap(); + assert_eq!(checked["retained_options_bytes"], json!(captured_options.retained_bytes().unwrap())); + assert_eq!(captured_options.lighting.unwrap().directional_lights.iter().count(), 2); + let sources: Vec<_> = captured_options.lighting.unwrap().punctual_lights.iter().copied().collect(); + assert_eq!(sources.len(), 2); + assert_eq!(sources[0].position_mm, [1.25, -2.5, 4.75]); + assert_eq!(sources[0].reference_distance_mm, 4.5); + assert_eq!(sources[0].minimum_distance_mm, 0.002); + assert_eq!( + sources[1].cone, + Some(solidcraft_render::job::SpotConeOptions { + emitted_axis: [-4.0, -5.0, -6.0], + inner_half_angle_radians: 0.2, + outer_half_angle_radians: 0.7 + }) + ); + let saved_lighting = match &saved.job { + Some(solidcraft_doc::render_settings::RenderJob::GpuPath { options, .. }) => options.lighting.unwrap(), + _ => panic!("GPU"), + }; + assert_eq!(captured_options.lighting, Some(saved_lighting), "portable options reach the exact runtime capture unchanged"); + assert_eq!(checked["options"]["lighting"]["directional_lights"][0]["intensity"].as_f64(), Some(0.0)); + assert_eq!(checked["options"]["denoise"], true); assert_eq!(checked["environment"]["rotation_rad"], 0.75); + assert_eq!(checked["transparency"], "coverage_alpha"); + assert_eq!(checked["request"]["transparent_background"], true); + // Protocol metadata follows the actual captured output flag; this executor + // fixture does not claim physical GPU image quality or material transmission. + let mut opaque = serde_json::to_value(&saved).unwrap(); + opaque["job"]["transparent_background"] = json!(false); + let opaque = s.execute("render.preflight", &json!({"settings":opaque})).unwrap(); + assert_eq!(opaque["transparency"], "opaque_only"); + assert_eq!(opaque["request"]["transparent_background"], false); assert_eq!(gpu.admitted_bytes(), 0); let started = s.execute("render.start", &named).unwrap(); let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); @@ -509,17 +546,38 @@ fn preflight_and_start_reject_excessive_pixel_work_without_reserving_a_job() { assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace"); assert!(preflight["admission"].get("projected_pixel_tests").is_none()); assert_eq!(raytrace_host.admitted_bytes(), 0); + let retained = preflight["retained_request_bytes"].as_u64().unwrap(); + let request: solidcraft_render::job::ImageRequest = serde_json::from_value(preflight["request"].clone()).unwrap(); + assert!(request.raytrace.is_none() && request.environment.is_none() && request.textures.is_none()); + assert_eq!(retained, solidcraft_render::job::ImageRequest::fixed_cpu_metadata_bytes()); let started = s.execute("render.start", ¶ms).unwrap(); let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); s.execute("render.cancel", &json!({"job":id})).unwrap(); - let status = s.render_job_handle(id).unwrap().wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Cancelled); - // The worker drops its reservation just after the job turns terminal. + // Terminal phase precedes actual work/proof release. The retained request + // belongs to Record and must remain funded while its handle is observed. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while raytrace_host.admitted_bytes() != 0 { - assert!(std::time::Instant::now() < deadline, "worker did not release the cancelled job's reservation"); + while !handle.work_released() { + assert!(std::time::Instant::now() < deadline, "worker did not release cancelled work/proof backing"); std::thread::yield_now(); } + assert!(handle.frame().unwrap().is_none() && handle.preview().unwrap().is_none()); + assert_eq!(raytrace_host.admitted_bytes(), retained, "only the exact retained request metadata remains"); + assert!(s.render_retained_results().unwrap().is_empty(), "collecting a cancelled job cannot create a completed image"); + assert!(s.render_job_handle(id).is_err(), "the cancelled live registry handle was collected"); + let historical = s.execute("render.status", &json!({"job":id})).unwrap(); + assert_eq!(historical["progress"]["phase"], "cancelled"); + assert_eq!(raytrace_host.admitted_bytes(), retained, "the external handle still owns its request reservation"); + drop(handle); + while raytrace_host.admitted_bytes() != 0 { + assert!(std::time::Instant::now() < deadline, "last cancelled Record did not release retained request metadata"); + std::thread::yield_now(); + } + // Plain status/history metadata does not retain Record or its lease. + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Cancelled); + assert_eq!(historical["progress"]["phase"], "cancelled"); assert!(Arc::ptr_eq(&doc, &s.doc)); assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len())); s.set_render_job_host(Some(host.clone())).unwrap(); @@ -593,6 +651,65 @@ fn saved_cpu_progressive_check_start_and_export_preserve_the_exact_final() { assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len())); } +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_output_runs_exports_and_regrades_its_exact_retained_native_master() { + use solidcraft_render::job::Phase; + let mut s = Session::default(); + s.execute( + "render.settings.set", + &json!({"name":"CPU output","set":{"width":8,"height":8,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81},"lights":[], + "output":{"tone_map":"aces_fitted","finishing":{"rgb_gain":[1.2,0.8,1.1],"photographic":{"grain":0.03,"seed":42}, + "bloom":{"strength":0.2,"threshold":0.5,"radius":1}},"backdrop":{"mode":"radial"},"linear_exr":true}}}}}), + ) + .unwrap(); + s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let request = json!({"setup":"CPU output"}); + let checked = s.execute("render.preflight", &request).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["exposure_ev"], 1.5); + assert_eq!(checked["request"]["raytrace"]["output"]["linear_exr"], true); + let reply = s.execute("render.start", &request).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap().progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + let master = frame.linear_exr().unwrap().to_vec(); + let path = std::env::temp_dir().join(format!("solidcraft-cpu-master-{}-{}.exr", std::process::id(), id.session)); + s.execute("render.export", &json!({"job":id,"path":path,"format":"exr"})).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), master); + std::fs::remove_file(path).unwrap(); + let derivative = s.execute("render.result.regrade", &json!({"job":id,"presentation":{"exposure_ev":-2,"background":[3,7,11]}})).unwrap(); + let derivative: JobId = serde_json::from_value(derivative["job"].clone()).unwrap(); + let derivative = s.render_job_handle(derivative).unwrap(); + assert_eq!(derivative.wait_timeout(std::time::Duration::from_secs(30)).unwrap().progress.phase, Phase::Completed); + assert_eq!(derivative.frame().unwrap().unwrap().linear_exr().unwrap(), master); + assert_eq!(frame.linear_exr().unwrap(), master); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_output_envelope_refuses_before_hdr_read_or_scene_capture() { + let mut s = Session::default(); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + let before = (s.revision, s.evaluations, s.undo.len()); + let request = json!({"integrator":"raytrace","settings":{"width":16384,"height":1}, + "raytrace":{"budget":"workstation","output":{"linear_exr":true}},"environment":{"path":"unopened-output.hdr"}}); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains("linear EXR"), "{error}"); + assert!(!error.contains("unopened-output.hdr"), "an incompatible output must refuse before source IO"); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len())); + } +} + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] #[test] fn progressive_limits_and_incompatibilities_fail_before_hdr_or_scene_capture() { @@ -1300,3 +1417,2119 @@ fn output_viewer_copy_validates_completed_job_without_mutation_or_pixel_payloads assert!(Arc::ptr_eq(&document, &s.doc)); assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), host.admitted_bytes())); } + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_physical_lens_saved_and_runtime_requests_share_one_captured_camera() { + let camera = solidcraft_render::Camera { fov: 0.7, distance: 20.0, roll: 0.3, ..Default::default() }; + let lens = solidcraft_render::job::ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 20.0 }; + let mut s = Session::default(); + s.execute( + "render.settings.set", + &json!({"name":"Focus","set":{"width":8,"height":8,"camera":camera,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"lens":lens,"progressive":{"samples_per_pixel":3,"seed":81},"lights":[]}}}}), + ) + .unwrap(); + s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let saved = s.execute("render.preflight", &json!({"setup":"Focus"})).unwrap(); + let runtime = s + .execute( + "render.preflight", + &json!({"settings":{"width":8,"height":8,"camera":camera},"integrator":"raytrace", + "raytrace":{"lens":lens,"exposure_ev":1.5,"progressive":{"samples_per_pixel":3,"seed":81},"lights":[]}}), + ) + .unwrap(); + assert_eq!(saved["request"], runtime["request"]); + assert_eq!(saved["request"]["camera"], json!(camera)); + assert_eq!(saved["request"]["raytrace"]["lens"], json!(lens)); + let started = s.execute("render.start", &json!({"setup":"Focus"})).unwrap(); + let job: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(job).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap().progress.phase, solidcraft_render::job::Phase::Completed); + assert!(handle.frame().unwrap().is_some()); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_lens_refuses_incompatible_sampling_and_camera_before_hdr_or_scene_capture() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for fixed in [false, true] { + let camera = solidcraft_render::Camera { fov: if fixed { 0.7 } else { 0.0 }, ..Default::default() }; + let mut request = json!({"integrator":"raytrace","settings":{"width":8,"height":8,"camera":camera}, + "raytrace":{"lens":{"aperture_radius_mm":0.5,"focus_distance_mm":20.0},"progressive":{"samples_per_pixel":3}}, + "environment":{"path":"must-not-open-cpu-lens.hdr"}}); + if fixed { + request["raytrace"].as_object_mut().unwrap().remove("progressive"); + } + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains(if fixed { "progressive" } else { "perspective" }), "{error}"); + assert!(!error.contains("must-not-open-cpu-lens.hdr")); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + } + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_alpha_refuses_opaque_only_output_before_hdr_io_or_scene_capture() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for output in [json!({"backdrop":{}}), json!({"finishing":{"bloom":{"strength":1}}}), json!({"finishing":{"photographic":{"grain":0.03}}})] { + let request = json!({"integrator":"raytrace","transparent_background":true,"settings":{"width":8,"height":8,"camera":solidcraft_render::Camera::default()}, + "raytrace":{"output":output},"environment":{"path":"must-not-open-cpu-alpha.hdr"}}); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains("opaque"), "{error}"); + assert!(!error.contains("must-not-open-cpu-alpha.hdr")); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), before); + } + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_denoise_reports_its_actual_native_request_and_keeps_regrade_raw() { + use solidcraft_render::job::Phase; + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Filtered"})).unwrap(); + s.execute( + "render.settings.set", + &json!({"name":"CPU denoise","set":{"width":8,"height":8, + "job":{"method":"cpu_raytrace","options":{"denoise":true,"progressive":{"samples_per_pixel":3,"seed":81},"output":{"linear_exr":true}}}}}), + ) + .unwrap(); + s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"CPU denoise"})).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["denoise"], true); + assert_eq!(checked["denoising"]["backend"], "native_cpu"); + assert_eq!(checked["denoising"]["passes"], 3); + assert_eq!(checked["denoising"]["raw_linear_accumulator_preserved"], true); + let started = s.execute("render.start", &json!({"setup":"CPU denoise"})).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request), checked["request"]); + let frame = handle.frame().unwrap().unwrap(); + let raw = frame.linear_exr().unwrap().to_vec(); + let result = s.execute("render.result.regrade", &json!({"job":id,"presentation":{"exposure_ev":-1.0}})).unwrap(); + let derivative: JobId = serde_json::from_value(result["job"].clone()).unwrap(); + let derivative = s.render_job_handle(derivative).unwrap(); + let finished = derivative.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(finished.progress.phase, Phase::Completed); + assert!(!finished.presentation.as_ref().unwrap().denoise_applied, "regrade never pretends to reconstruct absent geometry guides"); + assert_eq!(derivative.frame().unwrap().unwrap().linear_exr().unwrap(), raw); + assert_eq!(frame.linear_exr().unwrap(), raw); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), before); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_optics_match_runtime_capture_pixels_prefixes_cancel_and_accounting() { + use solidcraft_render::job::{CancelToken, ImageRequest, Phase}; + use solidcraft_render::raytrace::image::{ImagePoll, ImageTask}; + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Glass"})).unwrap(); + let camera = solidcraft_render::Camera { + target: solidcore_record::Vec3::new(5.0, 5.0, 1.5), + distance: 20.0, + yaw: 0.3, + pitch: 0.4, + fov: 0.5, + ..Default::default() + }; + s.execute("render.settings.set",&json!({"name":"CPU glass","set":{"camera":camera,"width":3,"height":3,"background":[255,255,255],"exposure_ev":1.0, + "job":{"method":"cpu_raytrace","options":{"lights":[],"environment":{"color":[1,1,1],"intensity":1},"progressive":{"samples_per_pixel":3,"seed":81}}}}})).unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"CPU glass","body_index":0,"body_name":"Glass","expected_revision":s.revision, + "optics":{"ior":1.51,"absorption_per_mm":[0.1,0.02,0.0],"boundary":"closed_mesh"}}), + ) + .unwrap(); + s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let saved = s.execute("render.preflight", &json!({"setup":"CPU glass"})).unwrap(); + let request: ImageRequest = serde_json::from_value(saved["request"].clone()).unwrap(); + let runtime=s.execute("render.preflight",&json!({"settings":{"camera":camera,"width":3,"height":3,"background":[255,255,255]},"integrator":"raytrace","raytrace":request.raytrace})).unwrap(); + assert_eq!(saved["request"], runtime["request"]); + let scene = crate::product_scene::extract(&s).unwrap(); + let saved_dielectrics = super::optical_bindings::resolve_cpu(&s, &scene, &s.doc.render.setups["CPU glass"].optics, "check").unwrap(); + let runtime_dielectrics = &request.raytrace.as_ref().unwrap().dielectrics; + assert_eq!(saved_dielectrics, *runtime_dielectrics); + // Saved lowering reserves exactly its targets; hostile runtime input reserves + // the bounded eight-target array. Equal serialized intent need not have equal + // allocation capacity. Prove the entire difference from the actual captures. + assert_eq!(saved_dielectrics.capacity(), saved_dielectrics.len()); + assert_eq!(runtime_dielectrics.capacity(), 8); + for (saved_input, runtime_input) in saved_dielectrics.iter().zip(runtime_dielectrics) { + assert_eq!(saved_input.body_name.capacity(), runtime_input.body_name.capacity()); + } + let extra_slots = runtime_dielectrics.capacity() - saved_dielectrics.capacity(); + let extra_bytes = (extra_slots * std::mem::size_of::()) as u64; + assert_eq!(saved["retained_request_bytes"].as_u64().unwrap() + extra_bytes, runtime["retained_request_bytes"].as_u64().unwrap()); + // Two options copies belong to image work; a third belongs to the retained + // immutable request. All other admission fields must remain exactly equal. + let mut expected_runtime_admission = saved["admission"].clone(); + for (field, copies) in [("preparation_bytes", 2), ("estimated_total_bytes", 3)] { + expected_runtime_admission[field] = json!(saved["admission"][field].as_u64().unwrap() + copies * extra_bytes); + } + assert_eq!(expected_runtime_admission, runtime["admission"]); + assert_eq!(saved["refraction"], true); + let original_mesh = scene.meshes[0].mesh.clone(); + assert!(!scene.has_transmission(), "saved CPU lowering leaves the captured product appearance and physical material unchanged"); + let complete = |request: ImageRequest, quantum| { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene.clone(), request, CancelToken::default(), options).unwrap(); + let mut previews = Vec::new(); + for _ in 0..200000 { + match task.step_with_previews(quantum).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => previews.push((samples_per_pixel, png)), + ImagePoll::Complete(png) => return (previews, png), + } + } + panic!("bounded saved-optics producer did not finish") + }; + let (previews, png) = complete(request.clone(), 1); + assert_eq!(previews.iter().map(|p| p.0).collect::>(), [1, 2]); + assert_eq!((previews.clone(), png.clone()), complete(request.clone(), 16384)); + for (samples, preview) in previews { + let mut prefix = request.clone(); + prefix.raytrace.as_mut().unwrap().progressive.as_mut().unwrap().samples_per_pixel = samples; + assert_eq!(complete(prefix, 3).1, preview); + } + let cancel = CancelToken::default(); + let mut interrupted = ImageTask::new(scene.clone(), request.clone(), cancel.clone(), request.raytrace.clone().unwrap()).unwrap(); + let mut checkpoint = false; + for _ in 0..200000 { + if matches!(interrupted.step_with_previews(1).unwrap(), ImagePoll::Preview { .. }) { + checkpoint = true; + break; + } + } + assert!(checkpoint, "cancel exercises a real complete saved-optics checkpoint"); + cancel.cancel(); + assert_eq!(interrupted.step_with_previews(1).err().unwrap().code, solidcraft_render::job::ErrorCode::Cancelled); + assert!(interrupted.take_linear_exr().is_none()); + let started = s.execute("render.start", &json!({"setup":"CPU glass"})).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let terminal = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(terminal.progress.phase, Phase::Completed, "{:?}", terminal.error); + assert_eq!(handle.frame().unwrap().unwrap().png(), png); + assert!(Arc::ptr_eq(&original_mesh, &crate::product_scene::extract(&s).unwrap().meshes[0].mesh)); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_saved_closed_optics_do_not_broaden_geometry_or_guess_stale_targets() { + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius":5,"height":3,"body_name":"Curved"})).unwrap(); + s.execute("render.settings.set", &json!({"name":"CPU glass","set":{"width":3,"height":3,"job":{"method":"cpu_raytrace"}}})).unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"CPU glass","body_index":0,"body_name":"Curved","expected_revision":s.revision,"optics":{"ior":1.5,"boundary":"closed_mesh"}}), + ) + .unwrap(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &json!({"setup":"CPU glass"})).unwrap_err().to_string(); + // The finer main147 tessellation reaches the exact axis-plane guard. + assert!(error.starts_with("InvalidScene:") && error.contains("box face is not axis aligned"), "{error}"); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(host.admitted_bytes(), 0); + } + s.execute("browser.visibility", &json!({"items":["Curved"],"visible":false})).unwrap(); + let error = s.execute("render.preflight", &json!({"setup":"CPU glass"})).unwrap_err().to_string(); + assert!(error.contains("hidden or absent"), "{error}"); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_saved_thin_sheet_uses_its_authored_ior_beer_thickness_and_roundtrips_offline() { + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("solidcraft-cpu-saved-sheet-{}-{nonce}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let source = dir.join("Sheet.obj"); + std::fs::write(&source, "o Sheet\nv -10 -10 0\nv 10 -10 0\nv 10 10 0\nv -10 10 0\nf 1 2 3\nf 1 3 4\n").unwrap(); + let mut s = Session::default(); + s.execute("file.insert_mesh", &json!({"path":source})).unwrap(); + let scene = s.execute("render.scene", &json!({})).unwrap(); + let name = scene["bodies"][0]["name"].as_str().unwrap().to_owned(); + let mut camera = solidcraft_render::Camera { distance: 10.0, ..Default::default() }; + camera.set_view(solidcraft_render::StandardView::Top); + s.execute( + "render.settings.set", + &json!({"name":"Sheet","set":{"camera":camera,"width":1,"height":1,"job":{"method":"cpu_raytrace","options":{ + "lights":[],"environment":{"color":[1,1,1],"intensity":1},"progressive":{"samples_per_pixel":3,"seed":81}}}}}), + ) + .unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"Sheet","body_index":0,"body_name":name,"expected_revision":s.revision, + "optics":{"boundary":"thin_sheet","thickness_mm":2.0,"ior":1.51,"absorption_per_mm":[0.1,0.2,0.0],"shadow_transmission":false}}), + ) + .unwrap(); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + s = Session::new(reopened); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + let before = s.doc.clone(); + let checked = s.execute("render.preflight", &json!({"setup":"Sheet"})).unwrap(); + assert_eq!(checked["request"]["raytrace"]["dielectrics"][0]["boundary"], "thin_sheet"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"][0]["thickness_mm"], 2.0); + let started = s.execute("render.start", &json!({"setup":"Sheet"})).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + let decoded = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + let f = ((1.0f64 - 1.51) / (1.0 + 1.51)).powi(2); + let rgb = [0.1f64, 0.2, 0.0].map(|sigma| { + let a = (-sigma * 2.0).exp(); + let denominator = 1.0 - f * f * a * a; + let scene = f + (1.0 - f).powi(2) * (f * a * a + a) / denominator; + solidcraft_geom::srgb::encode8(scene / (1.0 + scene)) + }); + assert_eq!(decoded.get_pixel(0, 0).0, [rgb[0], rgb[1], rgb[2], 255]); + assert!(Arc::ptr_eq(&before, &s.doc)); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_path_saved_and_runtime_captures_execute_without_mutating_document_or_history() { + let mut s = Session::default(); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + let camera = solidcraft_render::Camera::default(); + s.execute("render.settings.set",&json!({"name":"Path","set":{"width":8,"height":8,"camera":camera,"job":{"method":"cpu_raytrace","options":{"path":{"max_depth":3},"progressive":{"samples_per_pixel":3,"seed":9},"lights":[]}}}})).unwrap(); + let saved = s.execute("render.preflight", &json!({"setup":"Path"})).unwrap(); + let runtime=s.execute("render.preflight",&json!({"settings":{"width":8,"height":8,"camera":camera},"integrator":"raytrace","raytrace":{"path":{"max_depth":3},"progressive":{"samples_per_pixel":3,"seed":9},"lights":[]}})).unwrap(); + assert_eq!(saved["request"], runtime["request"]); + assert_eq!(saved["request"]["raytrace"]["path"]["max_depth"], 3); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let started = s.execute("render.start", &json!({"setup":"Path"})).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap().progress.phase, solidcraft_render::job::Phase::Completed); + assert!(handle.frame().unwrap().is_some()); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_path_refuses_fixed_or_shadowless_transport_before_hdr_io() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for fixed in [false, true] { + let mut request = json!({"integrator":"raytrace","settings":{"width":8,"height":8,"camera":solidcraft_render::Camera::default()},"raytrace":{"path":{"max_depth":3},"progressive":{"samples_per_pixel":3},"shadows":false},"environment":{"path":"must-not-open-path.hdr"}}); + if fixed { + request["raytrace"].as_object_mut().unwrap().remove("progressive"); + request["raytrace"]["shadows"] = json!(true); + } + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains(if fixed { "progressive" } else { "shadows" }), "{error}"); + assert!(!error.contains("must-not-open-path.hdr")); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + } + } +} + +#[test] +fn composed_saved_cpu_path_and_subsurface_refuse_before_hdr_resources_or_scene_capture() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Glass"})).unwrap(); + s.execute( + "render.settings.set", + &json!({"name":"Glass","set":{"width":8,"height":8, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81}}}}}), + ) + .unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"Glass","body_index":0,"body_name":"Glass","expected_revision":s.revision, + "optics":{"ior":1.51,"boundary":"closed_box","shadow_transmission":false}}), + ) + .unwrap(); + let mut settings = serde_json::to_value(&s.doc.render.setups["Glass"]).unwrap(); + settings["job"]["transparent_background"] = json!(true); + settings["job"]["options"]["path"] = json!({"max_depth":3}); + settings["job"]["options"]["denoise"] = json!(true); + settings["job"]["options"]["output"] = json!({"linear_exr":true}); + settings["job"]["options"]["hdr"] = json!({"resource":"0".repeat(64),"rotation_rad":0,"intensity":1,"samples":16}); + settings["optics"][0]["optics"]["subsurface"] = json!({"scattering_per_mm":0.1,"anisotropy":0}); + let authored = settings.clone(); + let document = s.doc.clone(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for command in ["render.preflight", "render.start", "render.settings.set"] { + let request = if command == "render.settings.set" { json!({"name":"Invalid","set":settings}) } else { json!({"settings":settings}) }; + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains("subsurface"), "{command}: {error}"); + assert!(!error.contains("missing embedded HDR"), "compatibility must precede resource access: {error}"); + assert_eq!(settings, authored); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), history); + assert!(s.render_retained_results().unwrap().is_empty()); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn composed_runtime_cpu_path_and_closed_shadow_approximation_refuse_before_missing_hdr_io() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Glass"})).unwrap(); + let request = json!({"integrator":"raytrace","settings":{"width":8,"height":8},"transparent_background":true, + "raytrace":{"path":{"max_depth":3},"denoise":true,"progressive":{"samples_per_pixel":3,"seed":81}, + "output":{"linear_exr":true},"dielectrics":[{"body_index":0,"body_name":"Glass","ior":1.51,"boundary":"closed_mesh","shadow_transmission":true,"absorption_per_mm":[0,0,0],"thickness_mm":0}]}, + "environment":{"path":"must-not-open-composed-optics.hdr"}}); + let authored = request.clone(); + let document = s.doc.clone(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains("dielectric"), "{error}"); + assert!(!error.contains("must-not-open-composed-optics.hdr")); + assert_eq!(host.admitted_bytes(), 0); + assert_eq!(request, authored); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), history); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_stage_preflight_describes_actual_opt_in_path_transport_without_changing_the_physical_stage() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Subject"})).unwrap(); + s.execute( + "render.settings.set", + &json!({"name":"Stage","set":{"width":8,"height":8, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81},"lights":[]}}}}), + ) + .unwrap(); + s.execute("render.stage.ground", &json!({"name":"Stage"})).unwrap(); + let saved = s.doc.render.setups["Stage"].clone(); + assert_eq!(saved.stage.len(), 1); + let product = crate::product_scene::extract(&s).unwrap(); + let product_triangles: usize = product.meshes.iter().map(|body| body.mesh.triangles.len()).sum(); + assert!(product_triangles > 0); + let document = s.doc.clone(); + let model = s.model.state(); + let history = (s.revision, s.undo.len(), s.redo.len()); + let direct = s.execute("render.preflight", &json!({"setup":"Stage"})).unwrap(); + let mut path = saved.clone(); + let Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut path.job else { panic!("CPU fixture") }; + options.path = Some(solidcraft_render::job::CpuPathOptions { max_depth: 3 }); + let indirect = s.execute("render.preflight", &json!({"settings":path})).unwrap(); + assert_eq!(direct["stage_transport"], "CPU direct/specular only; no diffuse interreflection"); + assert_eq!(indirect["stage_transport"], "CPU finite-depth opaque diffuse/specular path lighting"); + for reply in [&direct, &indirect] { + assert_eq!(reply["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(reply["stage_panels"], 1); + assert_eq!( + reply["admission"]["triangles"].as_u64(), + Some(product_triangles as u64 + 2), + "the same real finite ground is present in each captured scene" + ); + assert_eq!(reply["request"]["camera"], serde_json::to_value(saved.camera).unwrap()); + assert_eq!(reply["scene_generation"], s.revision); + } + assert!(direct["request"]["raytrace"].get("path").is_none()); + assert_eq!(indirect["request"]["raytrace"]["path"]["max_depth"], 3); + assert_eq!(s.doc.render.setups["Stage"], saved); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), history); + assert!(s.render_retained_results().unwrap().is_empty()); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_aging_cold_reopen_resolves_exact_target_and_changes_real_png_without_engineering_edits() { + use solidcraft_doc::render_aging::SavedAgingStack; + use solidcraft_render::job::aging::{AgingKind, AgingLayer}; + let mut s = Session::default(); + s.execute("solid.box", &json!({"body_name":"Weathered panel","length":10,"width":10,"height":2})).unwrap(); + let targets = super::surface_bindings::targets(&s, "test").unwrap(); + let (target, name) = targets.iter().find(|(_, name)| name.as_str() == "Weathered panel").unwrap(); + let name = name.clone(); + let mut layers = SavedAgingStack::default(); + layers + .push(AgingLayer { + kind: AgingKind::Dust, + strength: 1.0, + coverage: 1.0, + upward_bias: 0.0, + color_srgb: [255, 0, 0], + metallic: 0.0, + roughness: 1.0, + ..Default::default() + }) + .unwrap(); + layers.get_mut(0).unwrap().target = Some(target.clone()); + let physical = s.execute("component.properties", &json!({})).unwrap(); + let mut camera = solidcraft_render::Camera { distance: 15.0, target: solidcore_record::Vec3::new(5.0, 5.0, 1.0), fov: 0.0, ..Default::default() }; + camera.set_view(solidcraft_render::StandardView::Top); + s.execute("render.settings.set", &json!({"name":"CPU aging","set":{"width":8,"height":8,"camera":camera, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81},"aging":layers,"denoise":true,"output":{"linear_exr":true},"lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":std::f64::consts::PI}]}}}})).unwrap(); + let saved = s.doc.render.setups["CPU aging"].clone(); + let native = solidcraft_io::write_design_container(&s.doc).unwrap(); + s = Session::new(solidcraft_io::read_design(&native).unwrap()); + assert_eq!(s.doc.render.setups["CPU aging"], saved); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty()); + let checked = s.execute("render.preflight", &json!({"setup":"CPU aging"})).unwrap(); + assert_eq!(checked["request"]["raytrace"]["aging"][0]["target"]["body_name"], name); + assert_eq!(checked, s.execute("render.preflight", &json!({"settings":saved})).unwrap()); + let started = s.execute("render.start", &json!({"setup":"CPU aging"})).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request), checked["request"]); + let frame = handle.frame().unwrap().unwrap(); + assert!(frame.linear_exr().is_some()); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert!( + image.pixels().any(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 20 && u16::from(pixel[0]) > u16::from(pixel[2]) + 20), + "actual captured CPU aging must colour the visible panel" + ); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty())); + assert_eq!(s.execute("component.properties", &json!({})).unwrap(), physical); + assert_eq!(s.doc.render.setups["CPU aging"], saved); + let mut stale = saved; + let solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. } = stale.job.as_mut().unwrap() else { panic!("CPU fixture") }; + options.aging.get_mut(0).unwrap().target.as_mut().unwrap().feature += 100; + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &json!({"settings":stale})).unwrap_err().to_string(); + assert!(error.contains("rebinding"), "{error}"); + assert!(Arc::ptr_eq(&document, &s.doc)); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_aging_mixed_stable_runtime_and_anisotropic_intent_refuse_before_hdr_io_or_scene_capture() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let layer = json!({"kind":"dust"}); + let base = json!({"integrator":"raytrace","settings":{"width":8,"height":8},"aging":[layer], + "raytrace":{},"environment":{"path":"must-not-open-aging.hdr"}}); + let mut duplicate = base.clone(); + duplicate["raytrace"]["aging"] = json!([layer]); + let mut anisotropic = base.clone(); + anisotropic["raytrace"]["anisotropic_faces"] = + json!([{"body_index":0,"body_name":"Panel","face":0,"tangent":[1,0,0],"orientation":"zero","roughness_x":0.2,"roughness_y":0.6},null]); + let mut raster = base; + raster["integrator"] = json!("raster"); + for (input, reason) in [(duplicate, "not both"), (anisotropic, "anisotropic roughness"), (raster, "CPU raytrace integrator")] { + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &input).unwrap_err().to_string(); + assert!(error.contains(reason), "{error}"); + assert!(!error.contains("must-not-open-aging.hdr")); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + assert_eq!(host.admitted_bytes(), 0); + } + } +} + +#[cfg(all(feature = "bundled-render-library", feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_saved_surface_preflight_and_real_factory_render_captured_builtins_after_reopen_without_mutation() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":2,"body_name":"Coupon"})).unwrap(); + let scene = crate::product_scene::extract(&s).unwrap(); + let mut camera = solidcraft_render::Camera::default(); + camera.fit(&scene.bounds); + s.execute("render.library.surface.bind",&json!({"name":"CPU maps","surface":{"id":"SURF-001","body_index":0,"body_name":"Coupon"}, + "set":{"camera":camera,"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":9},"output":{"linear_exr":true}}}}})).unwrap(); + s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + s.execute("render.scene", &json!({})).unwrap(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let state = s.model.state(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"CPU maps"})).unwrap(); + assert_eq!(checked["textures"]["bodies"], 1); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(host.admitted_bytes(), 0); + let started = s.execute("render.start", &json!({"setup":"CPU maps"})).unwrap(); + let job: JobId = 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(60)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + assert!(status.request.textures.is_none()); + assert_eq!(status.textures.unwrap().bodies, 1); + let frame = handle.frame().unwrap().unwrap(); + assert!(frame.linear_exr().is_some()); + assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().dimensions(), (8, 8)); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + assert!(Arc::ptr_eq(&state, &s.model.state())); + let mut plain = s.doc.render.setups["CPU maps"].clone(); + plain.surfaces = Default::default(); + let started = s.execute("render.start", &json!({"settings":plain,"replace":true})).unwrap(); + let job: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let baseline = s.render_job_handle(job).unwrap(); + assert_eq!(baseline.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, solidcraft_render::job::Phase::Completed); + assert_ne!( + frame.png(), + baseline.frame().unwrap().unwrap().png(), + "the engine must capture and consume actual builtin maps, not only publish metadata" + ); + assert!(Arc::ptr_eq(&document, &s.doc)); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_adaptive_saved_and_runtime_admission_include_pilots_before_hdr_or_geometry_io() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for (width, height, samples) in [(8, 8, 64), (1024, 1024, 16)] { + let request = json!({"integrator":"raytrace","settings":{"width":width,"height":height}, + "raytrace":{"progressive":{"samples_per_pixel":samples,"seed":81},"adaptive":{"pilot_samples":16,"min_samples":16}}, + "environment":{"path":"must-not-open-adaptive.hdr"}}); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request).unwrap_err().to_string(); + assert!(error.contains("CPU") || error.contains("camera-sample"), "{error}"); + assert!(!error.contains("must-not-open-adaptive.hdr")); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + } + } + s.execute( + "render.settings.set", + &json!({"name":"Adaptive CPU","set":{"width":3,"height":1, + "job":{"method":"cpu_raytrace","transparent_background":true,"options":{"progressive":{"samples_per_pixel":48,"seed":81}, + "adaptive":{"pilot_samples":16,"min_samples":16},"lights":[],"denoise":true,"output":{"linear_exr":true}}}}}), + ) + .unwrap(); + let saved = s.doc.render.setups["Adaptive CPU"].clone(); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["Adaptive CPU"], saved); + s = Session::new(reopened); + s.set_render_job_host(Some(host)).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let doc = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"Adaptive CPU"})).unwrap(); + assert_eq!( + checked["request"]["raytrace"]["adaptive"], + json!({"pilot_samples":16,"min_samples":16,"relative_error":0.05,"absolute_error":0.002,"coverage_error":0.01}) + ); + let id: JobId = serde_json::from_value(s.execute("render.start", &json!({"setup":"Adaptive CPU"})).unwrap()["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request), checked["request"]); + let report = status.sampling.unwrap(); + assert_eq!((report.pilot_samples_per_pixel, report.production_samples, report.primary_path_evaluations), (16, 48, 96)); + assert!(handle.frame().unwrap().unwrap().linear_exr().is_some()); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_general_closed_mesh_path_matches_runtime_and_actual_captured_cylinder_after_reopen() { + use solidcraft_render::job::{ImageRequest, Phase}; + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius":5,"height":3,"body_name":"Curved"})).unwrap(); + let camera = solidcraft_render::Camera { + target: solidcore_record::Vec3::new(0.0, 0.0, 1.5), + distance: 20.0, + yaw: 0.3, + pitch: 0.4, + fov: 0.5, + ..Default::default() + }; + s.execute( + "render.settings.set", + &json!({"name":"General Glass","set":{"camera":camera,"width":3,"height":3, + "job":{"method":"cpu_raytrace","options":{"path":{"max_depth":12},"progressive":{"samples_per_pixel":3,"seed":81}, + "lights":[],"environment":{"color":[1,1,1],"intensity":1},"output":{"linear_exr":true}}}}}), + ) + .unwrap(); + let geometry = s.doc.features.clone(); + let materials = s.doc.materials.clone(); + let undo = s.undo.len(); + s.execute( + "render.optics.bind", + &json!({"name":"General Glass","body_index":0,"body_name":"Curved","expected_revision":s.revision, + "optics":{"ior":1.51,"absorption_per_mm":[0.1,0.02,0],"boundary":"closed_mesh"}}), + ) + .unwrap(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.doc.features, geometry); + assert_eq!(s.doc.materials, materials); + let saved = s.doc.to_json(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc.render.setups["General Glass"].optics.is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc.to_json(), saved); + s = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host)).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"General Glass"})).unwrap(); + assert_eq!(checked["dielectric_boundaries"], json!(["thin_sheet", "closed_box", "closed_mesh"])); + assert_eq!(checked["stage_transport"], "CPU finite-depth diffuse/specular and dielectric path lighting"); + let captured: ImageRequest = serde_json::from_value(checked["request"].clone()).unwrap(); + assert_eq!(captured.raytrace.as_ref().unwrap().dielectrics[0].boundary, solidcraft_render::job::DielectricBoundary::ClosedMesh); + assert_eq!(captured.raytrace.as_ref().unwrap().path.unwrap().max_depth, 12); + let runtime = s + .execute("render.preflight", &json!({"integrator":"raytrace","settings":{"camera":camera,"width":3,"height":3},"raytrace":captured.raytrace})) + .unwrap(); + assert_eq!(runtime["request"], checked["request"]); + let started = s.execute("render.start", &json!({"setup":"General Glass"})).unwrap(); + let id = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let complete = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(complete.progress.phase, Phase::Completed, "{:?}", complete.error); + assert_eq!(json!(complete.request), checked["request"]); + let frame = handle.frame().unwrap().unwrap(); + assert!(!frame.png().is_empty()); + assert!(frame.linear_exr().is_some()); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), before); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn runtime_checked_hdr_keeps_two_stable_glass_targets_and_exact_cpu_options_without_saving_the_draft() { + use solidcraft_doc::render_optics::{OpticalMaterial, SavedOptics}; + use solidcraft_doc::render_settings::RenderJob; + use solidcraft_render::job::Phase; + let mut s = Session::default(); + for (name, corner) in [("Saved glass", [0, 0, 0]), ("Draft glass", [4, 0, 0])] { + s.execute("solid.box", &json!({"body_name":name,"length":2,"width":2,"height":2,"corner":corner,"operation":"new"})).unwrap(); + } + let camera = solidcraft_render::Camera { target: solidcore_record::Vec3::new(3.0, 1.0, 1.0), distance: 20.0, fov: 0.6, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":"Glass HDR","set":{"width":4,"height":3,"camera":camera,"exposure_ev":0.75, + "job":{"method":"cpu_raytrace","transparent_background":true,"options":{"path":{"max_depth":12},"progressive":{"samples_per_pixel":3,"seed":81}, + "lights":[],"lens":{"aperture_radius_mm":0.01,"focus_distance_mm":20},"output":{"linear_exr":true}}}}})).unwrap(); + let targets = s.execute("render.library.targets", &json!({})).unwrap(); + let target = |name: &str| targets["items"].as_array().unwrap().iter().find(|row| row["name"] == name).unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"Glass HDR","body_index":target("Saved glass")["ordinal"],"body_name":"Saved glass", + "expected_revision":s.revision,"optics":{"ior":1.5,"boundary":"closed_mesh","absorption_per_mm":[0.1,0.0,0.0]}}), + ) + .unwrap(); + let saved = s.doc.render.setups["Glass HDR"].clone(); + let mut draft = saved.clone(); + draft + .optics + .set( + SavedOptics { + target: serde_json::from_value(target("Draft glass")["stable_target"].clone()).unwrap(), + optics: OpticalMaterial { ior: 1.2, absorption_per_mm: [0.0, 0.2, 0.0], ..Default::default() }, + }, + false, + ) + .unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = draft.job.take() else { panic!("CPU fixture") }; + let options = options.to_runtime(draft.exposure_ev).unwrap(); + draft.exposure_ev = 0.0; + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("solidcraft-stable-glass-hdr-{}-{nonce}.hdr", std::process::id())); + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 128, 128, 129]); + } + std::fs::write(&path, &bytes).unwrap(); + let info = s.execute("render.hdr.inspect", &json!({"path":path})).unwrap(); + let params = json!({"integrator":"raytrace","settings":draft,"raytrace":options,"transparent_background":true, + "environment":{"path":path,"expected_sha256":info["sha256"],"rotation_radians":0.75,"intensity":1.25,"samples":4}}); + let original = params.clone(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let model = s.model.state(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", ¶ms).unwrap(); + let mut captured: solidcraft_render::job::ImageRequest = serde_json::from_value(checked["request"].clone()).unwrap(); + let optics = &captured.raytrace.as_ref().unwrap().dielectrics; + assert_eq!(optics.len(), 2); + for (name, ior, absorption) in [("Saved glass", 1.5, [0.1, 0.0, 0.0]), ("Draft glass", 1.2, [0.0, 0.2, 0.0])] { + let actual = optics.iter().find(|entry| entry.body_name == name).unwrap(); + assert_eq!(actual.body_index, target(name)["ordinal"].as_u64().unwrap() as usize); + assert_eq!((actual.ior, actual.absorption_per_mm), (ior, absorption)); + assert_eq!(actual.boundary, solidcraft_render::job::DielectricBoundary::ClosedMesh); + } + captured.raytrace.as_mut().unwrap().dielectrics.clear(); + assert_eq!(captured.raytrace.as_ref().unwrap(), &options); + assert_eq!(captured.camera, camera); + assert!(captured.transparent_background); + assert_eq!(checked["environment"]["rotation_radians"], 0.75); + assert_eq!(checked["environment"]["intensity"], 1.25); + let mut mixed = params.clone(); + mixed["raytrace"]["dielectrics"] = checked["request"]["raytrace"]["dielectrics"].clone(); + mixed["environment"]["path"] = json!("must-not-open-mixed-stable-glass.hdr"); + assert!(s.execute("render.preflight", &mixed).unwrap_err().to_string().contains("cannot combine with runtime")); + let mut raster = params.clone(); + raster["integrator"] = json!("raster"); + raster.as_object_mut().unwrap().remove("raytrace"); + raster["environment"]["path"] = json!("must-not-open-raster-stable-glass.hdr"); + assert!(s.execute("render.preflight", &raster).unwrap_err().to_string().contains("stable optics require")); + let mut over_cap = params.clone(); + over_cap["settings"]["optics"] = json!( + (0..9) + .map(|i| { + let mut row = params["settings"]["optics"][0].clone(); + row["target"]["definition"] = json!(format!("Unique unknown optical body {i}")); + row + }) + .collect::>() + ); + over_cap["environment"]["path"] = json!("must-not-open-over-cap-stable-glass.hdr"); + assert!(s.execute("render.preflight", &over_cap).unwrap_err().to_string().contains("at most eight")); + let mut changed_hdr = params.clone(); + changed_hdr["environment"]["expected_sha256"] = json!("0".repeat(64)); + assert!(s.execute("render.preflight", &changed_hdr).unwrap_err().to_string().contains("changed since selection")); + assert_eq!(host.admitted_bytes(), 0); + let started = s.execute("render.start", ¶ms).unwrap(); + assert_eq!(started["request"], checked["request"]); + std::fs::remove_file(path).unwrap(); + let id = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let terminal = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(terminal.progress.phase, Phase::Completed, "{:?}", terminal.error); + assert_eq!(json!(terminal.request), checked["request"]); + let frame = handle.frame().unwrap().unwrap(); + assert!(!frame.png().is_empty() && frame.linear_exr().is_some()); + assert!(Arc::ptr_eq(&document, &s.doc) && Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + assert_eq!(s.doc.render.setups["Glass HDR"], saved); + assert_eq!(params, original); +} + +#[cfg(all(feature = "bundled-render-library", feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_path_maps_glass_and_targeted_aging_reach_real_preflight_and_render_after_cold_reopen() { + let mut s = Session::default(); + for (name, corner) in [("Glass", [0, 0, 0]), ("Panel", [20, 0, 0])] { + s.execute("solid.box", &json!({"body_name":name,"length":10,"width":10,"height":2,"corner":corner,"operation":"new"})).unwrap(); + } + let targets = s.execute("render.library.targets", &json!({})).unwrap(); + let glass = targets["items"].as_array().unwrap().iter().find(|target| target["name"] == "Glass").unwrap().clone(); + let panel = targets["items"].as_array().unwrap().iter().find(|target| target["name"] == "Panel").unwrap().clone(); + let scene = crate::product_scene::extract(&s).unwrap(); + let mut camera = solidcraft_render::Camera::default(); + camera.set_view(solidcraft_render::StandardView::Top); + camera.fit(&scene.bounds); + s.execute( + "render.settings.set", + &json!({"name":"Mixed","set":{"camera":camera,"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{ + "progressive":{"samples_per_pixel":3,"seed":9},"path":{"max_depth":4},"lights":[], + "environment":{"color":[1,1,1],"intensity":1},"output":{"linear_exr":true}, + "aging":[{"kind":"fading","target":panel["stable_target"],"strength":0.25,"coverage":1.0,"upward_bias":0.0}] + }}}}), + ) + .unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"Mixed","body_index":glass["ordinal"],"body_name":"Glass","expected_revision":s.revision, + "optics":{"ior":1.0,"absorption_per_mm":[0.1,0.2,0.0],"boundary":"closed_mesh"}}), + ) + .unwrap(); + s.execute("render.library.surface.bind", &json!({"name":"Mixed","surface":{"id":"SURF-001","body_index":panel["ordinal"],"body_name":"Panel"}})) + .unwrap(); + let setup = s.doc.render.setups["Mixed"].clone(); + s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + s.execute("render.scene", &json!({})).unwrap(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let model = s.model.state(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"Mixed"})).unwrap(); + assert_eq!(checked["textures"]["bodies"], 1); + assert_eq!(checked["request"]["raytrace"]["path"]["max_depth"], 4); + assert_eq!(checked["request"]["raytrace"]["dielectrics"][0]["body_name"], "Glass"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"][0]["boundary"], "closed_mesh"); + assert_eq!(checked["request"]["raytrace"]["aging"][0]["target"]["body_name"], "Panel"); + let run = |session: &mut Session, params: Value| { + let started = session.execute("render.start", ¶ms).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + let started_cleanup = std::time::Instant::now(); + while !handle.work_released() && started_cleanup.elapsed() < std::time::Duration::from_secs(60) { + std::thread::yield_now(); + } + assert!(handle.work_released(), "pool assertions require completed worker cleanup, not only a terminal phase"); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().dimensions(), (8, 8)); + assert!(frame.linear_exr().is_some()); + (frame.png().to_vec(), frame.linear_exr().unwrap().to_vec()) + }; + let saved = run(&mut s, json!({"setup":"Mixed"})); + assert_eq!(saved, run(&mut s, json!({"settings":setup,"replace":true})), "named and prospective captures keep identical maps/optics/aging"); + let mut plain = setup.clone(); + plain.surfaces = Default::default(); + assert_ne!( + saved, + run(&mut s, json!({"settings":plain,"replace":true})), + "the factory must consume actual opaque maps alongside Glass, not publish metadata alone" + ); + for same_target in [true, false] { + let mut invalid = setup.clone(); + if same_target { + let mut binding = invalid.surfaces.iter().next().unwrap().clone(); + binding.target = invalid.optics.iter().next().unwrap().target.clone(); + invalid.surfaces = Default::default(); + invalid.surfaces.set(binding, false).unwrap(); + } else if let Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut invalid.job { + options.path = None; + } + let bytes = host.admitted_bytes(); + assert!(s.execute("render.preflight", &json!({"settings":invalid})).is_err()); + assert_eq!(host.admitted_bytes(), bytes, "invalid authored combinations acquire no new render lease"); + } + assert!(Arc::ptr_eq(&document, &s.doc)); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_coat_cpu_direct_and_path_render_match_independent_normal_incidence_layer_and_zero_is_exact() { + // Independent OpenEXR scanline/FLOAT reader for this fully covered1×1 oracle. + // No production encoder/decoder or optional image codec participates. + fn raw_pixel(bytes: &[u8]) -> [f32; 4] { + fn word(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) + } + fn string<'a>(bytes: &'a [u8], at: &mut usize) -> &'a [u8] { + let start = *at; + *at += bytes[start..].iter().position(|b| *b == 0).unwrap() + 1; + &bytes[start..*at - 1] + } + assert_eq!(word(bytes, 0), 20_000_630); + assert_eq!(word(bytes, 4), 2); + let mut at = 8; + let (mut channels, mut window, mut compression) = (false, false, false); + while bytes[at] != 0 { + let name = string(bytes, &mut at); + let kind = string(bytes, &mut at); + let length = word(bytes, at) as usize; + at += 4; + let data = &bytes[at..at + length]; + at += length; + match name { + b"channels" => { + assert_eq!(kind, b"chlist"); + let mut c = 0; + for expected in [b"A", b"B", b"G", b"R"] { + assert_eq!(string(data, &mut c), expected); + assert_eq!(word(data, c), 2); // FLOAT, never HALF + assert_eq!(&data[c + 4..c + 8], &[0; 4]); + assert_eq!((word(data, c + 8), word(data, c + 12)), (1, 1)); + c += 16; + } + assert_eq!(&data[c..], &[0]); + channels = true; + } + b"dataWindow" => { + assert_eq!(kind, b"box2i"); + assert_eq!(data, &[0; 16]); + window = true; + } + b"compression" => { + assert_eq!(kind, b"compression"); + assert_eq!(data, &[0]); + compression = true; + } + _ => {} + } + } + assert!(channels && window && compression); + at += 1; + let offset = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()) as usize; + assert_eq!((word(bytes, offset), word(bytes, offset + 4)), (0, 16)); + let channel = |i: usize| f32::from_bits(word(bytes, offset + 8 + i * 4)); + [channel(3), channel(2), channel(1), channel(0)] + } + use solidcore_record::Vec3; + use solidcraft_doc::render_coat::SavedCoat; + use std::f64::consts::{FRAC_PI_2, PI, SQRT_2}; + for indirect in [false, true] { + let mut s = Session::default(); + s.execute("solid.box", &json!({"body_name":"Panel","corner":[-10,-10,-2],"length":20,"width":20,"height":2})).unwrap(); + s.execute( + "appearance.assign", + &json!({"bodies":["Panel"],"name":"Analytic substrate","color":[128,64,32], + "pbr":{"metallic":0,"roughness":0.5,"dielectric_ior":1}}), + ) + .unwrap(); + let camera = + solidcraft_render::Camera { target: Vec3::ZERO, distance: 1.0, yaw: 0.0, pitch: FRAC_PI_2, roll: 0.0, fov: 0.0, ..Default::default() }; + let mut options = json!({"progressive":{"samples_per_pixel":4,"seed":81},"lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":PI}], + "environment":{"color":[0,0,0],"intensity":0},"output":{"linear_exr":true}}); + if indirect { + options["path"] = json!({"max_depth":1}); + } + s.execute("render.coat.bind", &json!({"name":"Coat","body_index":0,"body_name":"Panel","expected_revision":s.revision, + "coat":{"weight":0.63,"roughness":0.61,"ior":1.7},"set":{"camera":camera,"width":1,"height":1,"job":{"method":"cpu_raytrace","options":options}}})).unwrap(); + let container = solidcraft_io::write_design_container(&s.doc).unwrap(); + s = Session::new(solidcraft_io::read_design(&container).unwrap()); + s.execute("render.scene", &json!({})).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 before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"Coat"})).unwrap(); + assert_eq!(checked["coats"], json!(s.doc.render.setups["Coat"].coats)); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(host.admitted_bytes(), 0); + let complete = |s: &mut Session, settings: Value| { + let reply = s.execute("render.start", &json!({"settings":settings})).unwrap(); + let job: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = s.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + handle.frame().unwrap().unwrap() + }; + let setup = s.doc.render.setups["Coat"].clone(); + let frame = complete(&mut s, json!(setup)); + let raw = raw_pixel(frame.linear_exr().unwrap()); + assert_eq!(raw[3], 1.0); + // Closed-form normal-incidence coat over an IOR1 Lambert substrate. + // The model's conservative entry/exit factor uses its45-degree bound. + let f0 = ((1.7_f64 - 1.0) / (1.7 + 1.0)).powi(2); + let bound = f0 + (1.0 - f0) * (1.0 - 1.0 / SQRT_2).powi(5); + let attenuation = (1.0 - 0.63 * bound).powi(2); + let highlight = 0.63 * f0 / (4.0 * 0.61_f64.powi(4)); + let expected = [128_u8, 64, 32].map(|code| { + let encoded = f64::from(code) / 255.0; + let linear = if encoded <= 0.04045 { encoded / 12.92 } else { ((encoded + 0.055) / 1.055).powf(2.4) }; + linear * attenuation + highlight + }); + for (actual, expected) in raw[..3].iter().zip(expected) { + assert!((f64::from(*actual) - expected).abs() < 2e-7, "direct/path coat radiance {actual} vs independent {expected}"); + } + let mut plain = setup.clone(); + plain.coats = Default::default(); + let plain_check = s.execute("render.preflight", &json!({"settings":plain})).unwrap(); + assert_eq!(checked["admission"], plain_check["admission"], "coat uses existing inline surface metadata and the same bounded producer stages"); + assert_eq!(checked["retained_request_bytes"], plain_check["retained_request_bytes"]); + let mut zero = setup; + let row = zero.coats.iter().next().unwrap().clone(); + zero.coats.set(SavedCoat { coat: solidcraft_doc::render_coat::CoatMaterial { weight: 0.0, ..row.coat }, ..row }, true).unwrap(); + let baseline = complete(&mut s, json!(plain)); + let identity = complete(&mut s, json!(zero)); + assert_eq!(baseline.png(), identity.png()); + assert_eq!(baseline.linear_exr().unwrap(), identity.linear_exr().unwrap()); + assert_ne!(frame.linear_exr().unwrap(), baseline.linear_exr().unwrap(), "active coat must change actual transport, not metadata only"); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert!(Arc::ptr_eq(&geometry, &s.model.state())); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), before); + } +} + +#[cfg(all(feature = "bundled-render-library", feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_coat_survives_builtin_maps_aging_and_guided_filter_without_changing_the_raw_master() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"body_name":"Panel","corner":[-10,-10,-2],"length":20,"width":20,"height":2})).unwrap(); + s.execute("appearance.assign", &json!({"bodies":["Panel"],"color":[128,64,32],"pbr":{"metallic":0,"roughness":0.5,"dielectric_ior":1}})).unwrap(); + let camera = + solidcraft_render::Camera { distance: 10.0, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, fov: 0.0, ..Default::default() }; + s.execute( + "render.coat.bind", + &json!({"name":"Coat","body_index":0,"body_name":"Panel","expected_revision":s.revision, + "coat":{"weight":0.63,"roughness":0.61,"ior":1.7},"set":{"camera":camera,"width":16,"height":16,"job":{"method":"cpu_raytrace","options":{ + "progressive":{"samples_per_pixel":4,"seed":81},"path":{"max_depth":2},"shadows":true,"denoise":true, + "lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":3}],"environment":{"color":[0,0,0],"intensity":0}, + "aging":[{"kind":"dust","strength":0.2,"coverage":1}],"output":{"linear_exr":true}}}}}), + ) + .unwrap(); + s.execute("render.library.surface.bind", &json!({"name":"Coat","surface":{"id":"SURF-001","body_index":0,"body_name":"Panel","scale":10}})) + .unwrap(); + let bytes = solidcraft_io::write_design_container(&s.doc).unwrap(); + s = Session::new(solidcraft_io::read_design(&bytes).unwrap()); + s.execute("render.scene", &json!({})).unwrap(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host)).unwrap(); + let document = s.doc.clone(); + let state = s.model.state(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let complete = |s: &mut Session, setup: solidcraft_doc::render_settings::RenderSetup| { + let reply = s.execute("render.start", &json!({"settings":setup})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed, "{:?}", status.error); + handle.frame().unwrap().unwrap() + }; + let saved = s.doc.render.setups["Coat"].clone(); + let actual = complete(&mut s, saved.clone()); + let mut uncoated = saved.clone(); + uncoated.coats = Default::default(); + let plain = complete(&mut s, uncoated); + assert_ne!(actual.linear_exr().unwrap(), plain.linear_exr().unwrap(), "maps and aging must not erase the captured coat"); + let mut unmapped = saved.clone(); + unmapped.surfaces = Default::default(); + let no_map = complete(&mut s, unmapped); + assert_ne!(actual.linear_exr().unwrap(), no_map.linear_exr().unwrap(), "saved maps must still reach the coated closure"); + let mut unaged = saved.clone(); + let Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut unaged.job else { panic!("CPU") }; + options.aging = Default::default(); + let no_age = complete(&mut s, unaged); + assert_ne!(actual.linear_exr().unwrap(), no_age.linear_exr().unwrap(), "aging still modifies the mapped coat/substrate"); + let mut unfiltered = saved.clone(); + let Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut unfiltered.job else { panic!("CPU") }; + options.denoise = false; + let raw = complete(&mut s, unfiltered); + assert_eq!(actual.linear_exr().unwrap(), raw.linear_exr().unwrap(), "guided finishing cannot modify coated raw transport"); + assert_eq!(s.doc.render.setups["Coat"], saved); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert!(Arc::ptr_eq(&state, &s.model.state())); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), history); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_subsurface_cold_capture_matches_runtime_real_png_raw_and_one_undo_without_geometry_changes() { + use solidcraft_render::job::{ImageRequest, Phase}; + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":2,"body_name":"Scattering"})).unwrap(); + let camera = solidcraft_render::Camera { + target: solidcore_record::Vec3::new(5.0, 5.0, 0.5), + distance: 0.5, + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + fov: 0.6, + ..Default::default() + }; + s.execute( + "render.settings.set", + &json!({"name":"SSS","set":{"camera":camera,"width":3,"height":3,"job":{"method":"cpu_raytrace","options":{ + "path":{"max_depth":16},"progressive":{"samples_per_pixel":3,"seed":9},"lights":[], + "environment":{"color":[1,1,1],"intensity":1},"output":{"linear_exr":true} + }}}}), + ) + .unwrap(); + let before = s.doc.clone(); + let undo = s.undo.len(); + s.execute( + "render.optics.bind", + &json!({"name":"SSS","body_index":0,"body_name":"Scattering","expected_revision":s.revision, + "optics":{"ior":1.0,"boundary":"closed_mesh","absorption_per_mm":[0.1,0.2,0.0],"subsurface":{"scattering_per_mm":0.3,"anisotropy":0.4}}}), + ) + .unwrap(); + let saved = s.doc.clone(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + assert_eq!(saved.appearances, before.appearances); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + s = Session::new(solidcraft_io::read_design(&solidcraft_io::write_design_container(&saved).unwrap()).unwrap()); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let document = s.doc.clone(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"SSS"})).unwrap(); + let captured: ImageRequest = serde_json::from_value(checked["request"].clone()).unwrap(); + let input = &captured.raytrace.as_ref().unwrap().dielectrics[0]; + assert_eq!(input.subsurface.unwrap().scattering_per_mm, 0.3); + assert_eq!(input.subsurface.unwrap().anisotropy, 0.4); + let runtime = json!({"integrator":"raytrace","settings":{"camera":camera,"width":3,"height":3},"raytrace":captured.raytrace}); + assert_eq!(s.execute("render.preflight", &runtime).unwrap()["request"], checked["request"]); + let run = |s: &mut Session, params: Value| { + let started = s.execute("render.start", ¶ms).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + (frame.png().to_vec(), frame.linear_exr().unwrap().to_vec()) + }; + let pixels = run(&mut s, json!({"setup":"SSS"})); + let mut runtime = runtime; + runtime["replace"] = json!(true); + assert_eq!(pixels, run(&mut s, runtime)); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn saved_cpu_atmosphere_cold_capture_start_matches_runtime_pixels_raw_and_one_undo_without_camera_or_geometry_edits() { + use solidcraft_render::job::{ImageRequest, Phase}; + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":2,"body_name":"Fog receiver"})).unwrap(); + let camera = solidcraft_render::Camera { + target: solidcore_record::Vec3::new(5.0, 5.0, 1.0), + distance: 5.0, + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + fov: 0.5, + ..Default::default() + }; + s.execute("render.settings.set",&json!({"name":"Fog","set":{"camera":camera,"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{ + "path":{"max_depth":8},"progressive":{"samples_per_pixel":3,"seed":9},"lights":[],"environment":{"color":[1,1,1],"intensity":1},"output":{"linear_exr":true} + }}}})).unwrap(); + let before = s.doc.clone(); + let undo = s.undo.len(); + let volume = json!({"min_mm":[-10,-10,-1],"max_mm":[20,20,5],"extinction_per_mm":0.3,"scattering_albedo":[0.2,0.4,0.6],"anisotropy":-0.37}); + let mut job = serde_json::to_value(before.render.setups["Fog"].job.as_ref().unwrap()).unwrap(); + job["options"]["volume"] = volume.clone(); + s.execute("render.settings.set", &json!({"name":"Fog","set":{"job":job}})).unwrap(); + let saved = s.doc.clone(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(saved.render.setups["Fog"].camera, before.render.setups["Fog"].camera); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + assert_eq!(saved.appearances, before.appearances); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + s = Session::new(solidcraft_io::read_design(&solidcraft_io::write_design_container(&saved).unwrap()).unwrap()); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let document = s.doc.clone(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let checked = s.execute("render.preflight", &json!({"setup":"Fog"})).unwrap(); + let request: ImageRequest = serde_json::from_value(checked["request"].clone()).unwrap(); + let authored: solidcraft_render::job::volume::HomogeneousVolume = serde_json::from_value(volume).unwrap(); + assert_eq!(request.raytrace.as_ref().unwrap().volume, Some(authored)); + let runtime = json!({"integrator":"raytrace","settings":{"camera":camera,"width":8,"height":8},"raytrace":request.raytrace}); + assert_eq!(s.execute("render.preflight", &runtime).unwrap()["request"], checked["request"]); + let run = |s: &mut Session, params: Value| { + let started = s.execute("render.start", ¶ms).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + (frame.png().to_vec(), frame.linear_exr().unwrap().to_vec()) + }; + let pixels = run(&mut s, json!({"setup":"Fog"})); + let mut runtime = runtime; + runtime["replace"] = json!(true); + assert_eq!(pixels, run(&mut s, runtime)); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} + +#[test] +fn saved_cpu_atmosphere_incompatibility_is_pure_before_hdr_capture_and_keeps_authored_data() { + let mut s = Session::default(); + let before = s.doc.clone(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let volume = json!({"min_mm":[-2,-2,-2],"max_mm":[2,2,2],"extinction_per_mm":0.3,"scattering_albedo":[0.2,0.4,0.6],"anisotropy":-0.37}); + for mut options in + [json!({"volume":volume,"denoise":true,"path":{"max_depth":4},"progressive":{"samples_per_pixel":4,"seed":9}}), json!({"volume":volume})] + { + options["hdr"] = json!({"resource":"0".repeat(64),"rotation_rad":0,"intensity":1,"samples":16}); + let params = json!({"settings":{"camera":solidcraft_render::Camera::default(),"width":4,"height":4,"job":{"method":"cpu_raytrace","options":options}}}); + let error = s.execute("render.preflight", ¶ms).unwrap_err().to_string(); + assert!(error.contains("Atmosphere"), "{error}"); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + } +} + +#[test] +fn saved_cpu_atmosphere_and_glass_refuse_before_missing_hdr_access_without_dropping_either_authored_choice() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":4,"width":4,"height":2,"body_name":"Glass"})).unwrap(); + s.execute("render.settings.set",&json!({"name":"Fog","set":{"width":4,"height":4,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":4,"seed":9}}}}})).unwrap(); + s.execute("render.optics.bind",&json!({"name":"Fog","body_index":0,"body_name":"Glass","expected_revision":s.revision,"optics":{"ior":1.5,"boundary":"closed_box","shadow_transmission":false}})).unwrap(); + let mut settings = serde_json::to_value(&s.doc.render.setups["Fog"]).unwrap(); + settings["job"]["options"]["path"] = json!({"max_depth":4}); + settings["job"]["options"]["volume"] = + json!({"min_mm":[-10,-10,-10],"max_mm":[10,10,10],"extinction_per_mm":0.2,"scattering_albedo":[0.1,0.3,0.7],"anisotropy":0.2}); + settings["job"]["options"]["hdr"] = json!({"resource":"0".repeat(64),"rotation_rad":0,"intensity":1,"samples":16}); + let authored = settings.clone(); + let document = s.doc.clone(); + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + for command in ["render.preflight", "render.start", "render.settings.set"] { + let params = if command == "render.settings.set" { json!({"name":"Fog","set":settings}) } else { json!({"settings":settings}) }; + let error = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(error.contains("Atmosphere"), "{command}: {error}"); + assert_eq!(settings, authored); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_sun_sky_named_runtime_reopen_and_actual_output_keep_the_same_capture() { + use solidcraft_render::job::Phase; + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3})).unwrap(); + let camera = solidcraft_render::Camera { distance: 30.0, fov: 0.7, ..Default::default() }; + let options = json!({"path":{"max_depth":3},"progressive":{"samples_per_pixel":3,"seed":81},"lights":[],"denoise":true, + "sun":{"direction":[0.2,-0.3,0.9],"angular_radius_rad":0.2,"radiance":[10,8,6]}, + "sky":{"kind":"sky","gradient":{"zenith":[0.25,0.5,1.0],"horizon":[0.75,0.5,0.25],"ground":[0.125,0.25,0.5]},"rotation_rad":0.731,"intensity":1.75}, + "lens":{"aperture_radius_mm":0.01,"focus_distance_mm":30},"output":{"linear_exr":true}}); + s.execute("render.settings.set",&json!({"name":"CPU celestial","set":{"width":8,"height":6,"camera":camera,"job":{"method":"cpu_raytrace","transparent_background":true,"options":options}}})).unwrap(); + let saved = s.doc.render.setups["CPU celestial"].clone(); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["CPU celestial"], saved); + s = Session::new(reopened); + s.set_render_job_host(Some(host.clone())).unwrap(); + let checked = s.execute("render.preflight", &json!({"setup":"CPU celestial"})).unwrap(); + let mut runtime_options = options.clone(); + runtime_options["sky"].as_object_mut().unwrap().remove("kind"); + let runtime = + json!({"integrator":"raytrace","settings":{"width":8,"height":6,"camera":camera},"transparent_background":true,"raytrace":runtime_options}); + assert_eq!(checked["request"], s.execute("render.preflight", &runtime).unwrap()["request"]); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let mut pngs = Vec::new(); + let mut masters = Vec::new(); + for input in [json!({"setup":"CPU celestial"}), runtime] { + let id: JobId = serde_json::from_value(s.execute("render.start", &input).unwrap()["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request), checked["request"]); + let frame = handle.frame().unwrap().unwrap(); + pngs.push(frame.png().to_vec()); + masters.push(frame.linear_exr().unwrap().to_vec()); + } + assert_eq!(pngs[0], pngs[1]); + assert_eq!(masters[0], masters[1]); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); +} +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_celestial_conflicts_refuse_before_hdr_vfs_and_never_mutate_the_scene() { + let mut s = Session::default(); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let sky = json!({"gradient":{"zenith":[1,1,1],"horizon":[1,1,1],"ground":[1,1,1]},"rotation_rad":0.731,"intensity":1}); + for path in [Value::Null, json!({"max_depth":3})] { + let options = json!({"path":path,"progressive":{"samples_per_pixel":3,"seed":81},"sky":sky}); + let input = + json!({"integrator":"raytrace","settings":{"width":8,"height":6},"raytrace":options,"environment":{"path":"must-not-read-cpu-sky.hdr"}}); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &input).unwrap_err().to_string(); + assert!(error.contains(if path.is_null() { "Indirect" } else { "choose either CPU HDR" }), "{error}"); + assert!(!error.contains("must-not-read-cpu-sky.hdr")); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.undo.len(), s.redo.len())); + } + } +} + +mod bounded_render_preparation { + use super::*; + use crate::render_preparation::{Kind, finish, prepare}; + use solidcraft_render::job::{CancelToken, CpuHost, JobId}; + + fn camera_bits(camera: Option) -> Option<(solidcraft_render::UpAxis, [u64; 8])> { + camera.map(|camera| { + ( + camera.up, + [camera.target.x, camera.target.y, camera.target.z, camera.yaw, camera.pitch, camera.roll, camera.distance, camera.fov] + .map(f64::to_bits), + ) + }) + } + fn fixture() -> (Session, CpuHost) { + let host = CpuHost::cooperative(); + let mut session = Session::default(); + session.set_render_job_host(Some(host.clone())).unwrap(); + session.execute("render.scene", &json!({})).unwrap(); + (session, host) + } + fn params() -> Value { + json!({"settings":{"width":3,"height":2}}) + } + fn drain(host: &CpuHost) { + for _ in 0..10_000 { + if !host.pump(128).unwrap() { + return; + } + } + panic!("prepared tiny raster did not finish"); + } + + #[test] + fn check_and_start_commit_only_in_the_real_session_with_exact_existing_reply_and_source() { + let (mut session, host) = fixture(); + let doc = session.doc.clone(); + let state = session.model.state(); + let before = (session.revision, session.evaluations, session.undo.len(), session.redo.len(), camera_bits(session.camera)); + let expected = session.execute("render.preflight", ¶ms()).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + let checked = prepare(session.scratch(), Kind::Check, params(), CancelToken::default()).unwrap(); + assert_eq!(checked.kind(), Kind::Check); + assert!(host.admitted_bytes() > 0, "a completed preparation owns its reserved captured resources"); + assert_eq!(finish(&mut session, checked).unwrap(), expected); + assert_eq!(host.admitted_bytes(), 0); + let prepared = prepare(session.scratch(), Kind::Start, params(), CancelToken::default()).unwrap(); + let held = host.admitted_bytes(); + let started = finish(&mut session, prepared).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + assert_eq!(id.serial, 1, "Check and scratch preparation never mint or consume job identities"); + assert_eq!(started["request"], expected["request"]); + assert_eq!(host.admitted_bytes(), held, "commit transfers the same leases without another admission"); + assert!(session.scratch().execute("render.status", &json!({"job":id})).is_err(), "the scratch registry never owns the final job"); + drain(&host); + let handle = session.render_job_handle(id).unwrap(); + assert_eq!(handle.status().unwrap().progress.phase, solidcraft_render::job::Phase::Completed); + let actual = handle.frame().unwrap().unwrap(); + let (mut control, control_host) = fixture(); + let control_id: JobId = serde_json::from_value(control.execute("render.start", ¶ms()).unwrap()["job"].clone()).unwrap(); + drain(&control_host); + assert_eq!(actual.png(), control.render_job_handle(control_id).unwrap().frame().unwrap().unwrap().png()); + assert!(Arc::ptr_eq(&doc, &session.doc)); + assert!(Arc::ptr_eq(&state, &session.model.state())); + assert_eq!((session.revision, session.evaluations, session.undo.len(), session.redo.len(), camera_bits(session.camera)), before); + } + + #[test] + fn cancelled_or_unverified_source_host_and_owner_changes_never_publish_a_prepared_job() { + for change in 0..5 { + let (mut session, host) = fixture(); + let cancel = CancelToken::default(); + let prepared = prepare(session.scratch(), Kind::Start, params(), cancel.clone()).unwrap(); + match change { + 0 => cancel.cancel(), + 1 => session.revision += 1, + 2 => session.camera = Some(solidcraft_render::Camera { distance: 51.0, ..Default::default() }), + 3 => session.set_render_job_host(Some(CpuHost::cooperative())).unwrap(), + 4 => { + let (mut unrelated, _) = fixture(); + assert!(finish(&mut unrelated, prepared).is_err()); + assert_eq!(host.admitted_bytes(), 0); + continue; + } + _ => panic!("unexpected prepared-source rejection fixture"), + } + let doc = session.doc.clone(); + let before = (session.revision, session.evaluations, session.undo.len(), session.redo.len()); + assert!(finish(&mut session, prepared).is_err()); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); + assert!(Arc::ptr_eq(&doc, &session.doc)); + assert_eq!((session.revision, session.evaluations, session.undo.len(), session.redo.len()), before); + } + } + + #[test] + fn preparation_checks_cancel_before_any_capture_or_admission() { + let (session, host) = fixture(); + let cancel = CancelToken::default(); + cancel.cancel(); + assert!(prepare(session.scratch(), Kind::Check, params(), cancel).is_err()); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); + } + #[test] + fn prepared_capture_cannot_bypass_current_embedding_command_refusal() { + let (mut session, host) = fixture(); + session.set_command_check(Some(Arc::new(|command, _, _| { + if command == "render.preflight" { Err("embedding policy refuses checking".into()) } else { Ok(()) } + }))); + let error = prepare(session.scratch(), Kind::Check, params(), solidcraft_render::job::CancelToken::default()).err().unwrap(); + assert!(error.to_string().contains("embedding policy refuses checking")); + assert_eq!(host.admitted_bytes(), 0); + session.set_command_check(None); + let prepared = prepare(session.scratch(), Kind::Start, params(), solidcraft_render::job::CancelToken::default()).unwrap(); + session.set_command_check(Some(Arc::new(|command, _, _| { + if command == "render.start" { Err("embedding policy changed before publication".into()) } else { Ok(()) } + }))); + assert!(finish(&mut session, prepared).unwrap_err().to_string().contains("embedding policy changed")); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); + } + #[test] + fn retained_completion_keeps_source_and_leases_until_same_worker_ack_on_every_outcome() { + use crate::render_preparation::finish_retained; + for outcome in ["check", "start", "stale", "host", "cancel", "queue"] { + let (mut session, host) = fixture(); + let doc = session.doc.clone(); + let baseline_refs = Arc::strong_count(&doc); + let cancel = solidcraft_render::job::CancelToken::default(); + let snapshot = session.scratch(); + let kind = if outcome == "check" { Kind::Check } else { Kind::Start }; + // The same bounded worker prepares, yields ownership, waits for it + // back, disposes it, then acknowledges actual release. + let (ready, receiver) = std::sync::mpsc::sync_channel(1); + let (retire, returned) = std::sync::mpsc::sync_channel::(1); + let (ack, released) = std::sync::mpsc::sync_channel(1); + let token = cancel.clone(); + let worker = std::thread::spawn(move || { + let prepared = prepare(snapshot, kind, params(), token).unwrap(); + ready.send(prepared).unwrap(); + drop(returned.recv().unwrap()); + ack.send(()).unwrap(); + }); + let mut prepared = receiver.recv().unwrap(); + let held = host.admitted_bytes(); + assert!(held > 0 && Arc::strong_count(&doc) > baseline_refs); + match outcome { + "stale" => session.revision += 1, + "host" => session.set_render_job_host(Some(CpuHost::cooperative())).unwrap(), + "cancel" => cancel.cancel(), + "queue" => { + // Fill the actual shared host after preparation, without + // minting any job in this Session's real registry. + let empty = || solidcraft_render::ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }; + for serial in 1..=2 { + host.submit( + JobId { session: 991, serial, generation: serial }, + 0, + empty(), + solidcraft_render::job::ImageRequest { + width: 1, + height: 1, + integrator: solidcraft_render::job::Integrator::Raster, + camera: Default::default(), + raytrace: None, + studio_weights: None, + environment: None, + textures: None, + background: [255; 3], + transparent_background: false, + }, + ) + .unwrap(); + } + } + _ => {} + } + let before = host.admitted_bytes(); + let result = finish_retained(&mut session, &mut prepared); + assert_eq!(result.is_ok(), matches!(outcome, "check" | "start"), "{outcome}"); + assert_eq!(host.admitted_bytes(), before, "completion never falsely releases prepared credit: {outcome}"); + assert!(Arc::strong_count(&doc) > baseline_refs, "completion retains scratch source: {outcome}"); + assert!(retire.try_send(prepared).is_ok()); + released.recv().unwrap(); + worker.join().unwrap(); + assert_eq!(Arc::strong_count(&doc), baseline_refs, "source's final preparation reference drops before ack: {outcome}"); + if outcome == "start" { + assert_eq!(host.admitted_bytes(), before, "job owns transferred leases after scratch retirement"); + drain(&host); + } else { + assert_eq!(host.admitted_bytes(), before - held, "{outcome}"); + if outcome == "queue" { + drain(&host); + } + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod native_camera_queue_preparation { + use super::*; + use crate::render_preparation::{batch, batch_payload}; + use solidcraft_render::job::{CancelToken, Phase}; + use std::sync::mpsc::{Receiver, SyncSender}; + + fn fixture(count: usize) -> (Session, CpuHost) { + let (mut s, host) = super::session(); + for i in 0..count { + let camera = solidcraft_render::Camera { yaw: i as f64 * 0.2, pitch: 0.3, distance: 51.0 + i as f64, ..Default::default() }; + s.execute( + "render.settings.set", + &json!({"name":format!("Shot{i:02}"),"set":{ + "width":3+i,"height":2,"camera":camera,"job":{"method":"raster"}}}), + ) + .unwrap(); + } + s.execute("render.scene", &json!({})).unwrap(); + (s, host) + } + struct Worker { + retire: SyncSender, + ack: Receiver<()>, + thread: std::thread::JoinHandle<()>, + } + impl Worker { + fn prepare(claim: batch::Claim) -> (batch::Prepared, Self) { + let (ready, received) = std::sync::mpsc::sync_channel(1); + let (retire, returned) = std::sync::mpsc::sync_channel(1); + let (ack, released) = std::sync::mpsc::sync_channel(1); + let thread = std::thread::spawn(move || { + batch::with_scope(claim, |claim| { + ready.send(batch::prepare(claim)).unwrap(); + drop(returned.recv().unwrap()); + }); + ack.send(()).unwrap(); + }); + (received.recv().unwrap(), Self { retire, ack: released, thread }) + } + fn retire(self, prepared: batch::Prepared) { + self.retire.send(prepared).unwrap(); + self.ack.recv().unwrap(); + self.thread.join().unwrap(); + } + } + fn initial(s: &mut Session, params: Value) -> (batch::Prepared, Worker) { + let mut input = Some(params); + let mut scope = None; + let claim = batch::claim(s, &mut input, &mut scope, CancelToken::default()).unwrap(); + assert!(input.is_none()); + Worker::prepare(claim) + } + fn complete(host: &CpuHost) { + for _ in 0..10000 { + if !host.pump(4096).unwrap() { + return; + } + } + panic!("small native queue job did not finish"); + } + fn retire_plan(plan: batch::Plan) { + std::thread::spawn(move || batch::retire_plan(plan)).join().unwrap(); + } + + #[test] + fn batch_arena_prepaid_exact_capacities_preserve_full_numbers_presence_and_moved_strings() { + let mut object = serde_json::Map::new(); + let key = |name: &str| { + let mut key = String::with_capacity(128); + key.push_str(name); + key + }; + let mut text = String::with_capacity(256); + text.push_str("owned text"); + object.insert(key("negative_zero"), json!(-0.0)); + object.insert(key("unsigned"), json!(u64::MAX)); + object.insert(key("signed"), json!(i64::MIN)); + object.insert(key("null"), Value::Null); + object.insert(key("array"), Value::Array(vec![Value::String(text), Value::Bool(true), Value::Object(Default::default())])); + let value = Value::Object(object); + let expected = value.clone(); + let cancel = CancelToken::default(); + let counts = batch_payload::count(&value, &cancel).unwrap(); + let (node, edge) = batch_payload::test_element_bytes(); + let independent = (9 * node + 8 * edge + 5 * 128 + 256) as u64; + assert_eq!(counts.bytes().unwrap(), independent); + let payload = batch_payload::Payload::new(value, counts, &cancel).unwrap(); + assert_eq!(payload.test_capacities(), (9, 8, (5 * 128 + 256) as u64)); + assert_eq!(payload.heap_bytes().unwrap(), independent); + let restored = payload.value(&cancel).unwrap(); + assert_eq!(restored, expected); + assert_eq!(restored["negative_zero"].as_f64().unwrap().to_bits(), (-0.0_f64).to_bits()); + assert_eq!(restored["unsigned"].as_u64(), Some(u64::MAX)); + assert_eq!(restored["signed"].as_i64(), Some(i64::MIN)); + assert!(restored.get("missing").is_none() && restored.get("null").is_some()); + cancel.cancel(); + assert!(payload.value(&cancel).is_err()); + } + + #[test] + fn native_batch_32_camera_semantics_real_ids_and_status_advancement_stay_metadata_only() { + let (mut s, host) = fixture(32); + let doc = s.doc.clone(); + let model = s.model.state(); + let camera = s.camera; + let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len()); + let cameras: [solidcraft_render::Camera; 32] = s.doc.render.setups.values().map(|setup| setup.camera).collect::>().try_into().unwrap(); + let (mut prepared, worker) = initial(&mut s, json!({})); + assert!(prepared.is_first() && prepared.owner_matches(&s) && !prepared.committed()); + assert!(s.render_queue_state().job.is_none(), "no scratch or invented preparing job ID"); + assert!(s.render_queue_state().preparing); + assert_eq!(s.render_queue_state().waiting, 31, "the claimed camera is separate from waiting cameras"); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + assert_eq!(batch::finish_retained(&mut s, &mut prepared).unwrap(), json!({"queued":32})); + let mut plan = batch::take_plan(&mut prepared).unwrap(); + let plan_bytes = plan.as_ref().unwrap().retained_bytes(); + assert!(plan_bytes > 0 && prepared.committed()); + worker.retire(prepared); + assert_eq!(host.admitted_bytes(), bytes); + let mut previous = None; + for (index, expected_camera) in cameras.iter().enumerate() { + let id = s.render_queue_state().job.unwrap(); + if let Some(previous) = previous { + assert_eq!(id.serial, previous + 1); + } + previous = Some(id.serial); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.status().unwrap(); + assert_eq!( + (status.request.width, status.request.height), + (3, 2), + "one first-saved common runtime setup, not every shot's different width" + ); + assert_eq!(status.request.camera, *expected_camera); + assert_eq!(s.render_queue_state().shot, Some(format!("Shot{index:02}"))); + complete(&host); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Completed); + let held = host.admitted_bytes(); + for _ in 0..4 { + s.advance_render_batch().unwrap(); + let status = s.render_jobs.peek_status(id).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.request.camera, *expected_camera); + assert_eq!(host.admitted_bytes(), held, "native metadata polling cannot collect or evict a completed result"); + } + assert!(!host.pump(1).unwrap(), "native status polling may not enqueue/capture the next shot"); + // The ordinary result/status API deliberately collects terminal + // owners and applies its eight-result retention policy. Keep this + // separate from native scheduling's immutable status boundary. + let status = s.execute("render.status", &json!({"job":id})).unwrap(); + assert_eq!(status["progress"]["phase"], "completed"); + let collected = host.admitted_bytes(); + for _ in 0..3 { + assert_eq!(s.execute("render.status", &json!({"job":id})).unwrap()["progress"]["phase"], "completed"); + assert_eq!(host.admitted_bytes(), collected, "repeated ordinary status does not retire another result"); + } + assert!(!host.pump(1).unwrap(), "ordinary status polling cannot prepare or enqueue the next native shot"); + if index == 31 { + break; + } + assert_eq!(s.render_queue_state().waiting, 31 - index); + let claim = batch::claim_next(&mut s, &mut plan, CancelToken::default()).unwrap().unwrap(); + assert!(plan.is_none()); + let (mut next, worker) = Worker::prepare(claim); + assert!(!next.is_first() && next.owner_matches(&s)); + let reply = batch::finish_retained(&mut s, &mut next).unwrap(); + assert_eq!(reply["job"], json!(s.render_queue_state().job.unwrap())); + plan = batch::take_plan(&mut next).unwrap(); + worker.retire(next); + if index < 30 { + assert_eq!(plan.as_ref().unwrap().retained_bytes(), plan_bytes); + } else { + assert!(plan.is_none()); + } + } + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().job.is_none()); + assert!(Arc::ptr_eq(&doc, &s.doc) && Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(s.camera, camera); + assert_eq!((s.revision, s.evaluations, s.undo.len(), s.redo.len()), history); + } + + #[test] + fn native_batch_owner_and_cancelled_identical_front_cannot_publish_into_wrong_or_replacement_registry() { + let (mut s, host) = fixture(2); + let (mut other, _) = fixture(2); + let (mut old, worker) = initial(&mut s, json!({})); + let held = host.admitted_bytes(); + assert!(!old.owner_matches(&other)); + assert!(batch::finish_retained(&mut other, &mut old).is_err()); + assert_eq!(host.admitted_bytes(), held); + let cancelled = s.execute("render.cancel", &json!({})).unwrap(); + assert_eq!(cancelled["cancel_requested"], true); + assert_eq!(cancelled["preparing"], true); + assert!(s.render_queue_state().job.is_none()); + let mut input = Some(json!({})); + let mut scope = None; + let replacement = batch::claim(&mut s, &mut input, &mut scope, CancelToken::default()).unwrap(); + assert!(batch::finish_retained(&mut s, &mut old).is_err()); + assert_eq!(s.render_queue_state().waiting, 1, "late identical front cannot cancel a replacement queue"); + assert!(s.render_queue_state().preparing); + worker.retire(old); + assert_eq!(host.admitted_bytes(), 0); + let (mut current, worker) = Worker::prepare(replacement); + batch::finish_retained(&mut s, &mut current).unwrap(); + let id = s.render_queue_state().job.unwrap(); + assert_eq!(id.serial, 1); + assert!(other.render_job_handle(id).is_err()); + let plan = batch::take_plan(&mut current).unwrap().unwrap(); + worker.retire(current); + batch::cancel(&mut s).unwrap(); + retire_plan(plan); + complete(&host); + } + + #[test] + fn native_batch_failed_next_shot_retains_plan_credit_until_worker_ack_and_keeps_previous_result() { + let (mut s, host) = fixture(2); + let (mut first, worker) = initial(&mut s, json!({})); + batch::finish_retained(&mut s, &mut first).unwrap(); + let mut plan = batch::take_plan(&mut first).unwrap(); + worker.retire(first); + let id = s.render_queue_state().job.unwrap(); + complete(&host); + let original = s.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + let plan_bytes = plan.as_ref().unwrap().retained_bytes(); + s.set_command_check(Some(Arc::new(|command, params, _| { + if command == "render.start" && params["settings"]["camera"]["yaw"].as_f64() == Some(0.2) { + Err("second camera policy refusal".into()) + } else { + Ok(()) + } + }))); + let claim = batch::claim_next(&mut s, &mut plan, CancelToken::default()).unwrap().unwrap(); + let (mut failed, worker) = Worker::prepare(claim); + let held = host.admitted_bytes(); + assert!(batch::finish_retained(&mut s, &mut failed).unwrap_err().to_string().contains("second camera policy refusal")); + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().job.is_none()); + assert_eq!(host.admitted_bytes(), held, "failure is not plan/source release"); + worker.retire(failed); + assert_eq!(host.admitted_bytes(), held - plan_bytes); + assert_eq!(s.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), original); + } + + #[test] + fn native_batch_individual_replace_invalidates_claim_without_consuming_scratch_job_ids() { + let (mut s, host) = fixture(2); + let (mut old, worker) = initial(&mut s, json!({})); + let reply = s.execute("render.start", &json!({"settings":{"width":2,"height":2},"replace":true})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + assert_eq!(id.serial, 1); + let held = host.admitted_bytes(); + assert!(batch::finish_retained(&mut s, &mut old).is_err()); + assert_eq!(host.admitted_bytes(), held); + assert!(!old.committed()); + worker.retire(old); + complete(&host); + assert_eq!(s.render_job_handle(id).unwrap().status().unwrap().progress.phase, Phase::Completed); + } + #[test] + fn native_batch_plan_and_first_job_obey_exact_same_pool_boundary_before_arena_publication() { + use solidcraft_render::job::{Admission, ErrorCode, ImageExecutor, ImageHost, ImageRequest, ImageWork, JobError, JobOptions}; + struct BudgetExecutor(u64); + impl ImageExecutor for BudgetExecutor { + fn descriptor(&self) -> solidcraft_render::job::Result { + let mut d = CpuHost::cooperative().descriptor()?; + d.id = solidcraft_render::ExecutorId::new("batch-budget").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?; + Ok(d) + } + fn memory_limit_bytes(&self) -> u64 { + self.0 + } + fn admit( + &self, + scene: &solidcraft_render::ProductScene, + request: &ImageRequest, + _: JobOptions, + ) -> solidcraft_render::job::Result { + solidcraft_render::job::admit(scene, request) + } + fn begin( + &self, + _: solidcraft_render::ProductScene, + _: ImageRequest, + _: JobOptions, + _: CancelToken, + ) -> solidcraft_render::job::Result> { + Err(JobError::new(ErrorCode::Internal, "boundary test never enqueues a renderer")) + } + } + let run = |limit: u64| { + let (mut s, _) = fixture(2); + let host = ImageHost::with_executor(Arc::new(BudgetExecutor(limit))).unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let (prepared, worker) = initial(&mut s, json!({})); + assert!(s.render_queue_state().job.is_none()); + let actual = host.admitted_bytes(); + batch::cancel(&mut s).unwrap(); + worker.retire(prepared); + assert_eq!(host.admitted_bytes(), 0); + actual + }; + let exact = run(512 * 1024 * 1024); + assert_eq!(run(exact), exact, "the exact plan+first-job pool boundary admits without hidden backing"); + assert!( + run(exact - 1) < exact - 1, + "one-byte shortage refuses the new arena lease and leaves only the retained failed preparation until ack" + ); + } + + #[test] + fn native_batch_idle_cancel_and_host_replacement_keep_plan_until_explicit_worker_retirement() { + for replace_host in [false, true] { + let (mut s, host) = fixture(2); + let (mut first, worker) = initial(&mut s, json!({})); + batch::finish_retained(&mut s, &mut first).unwrap(); + let mut plan = batch::take_plan(&mut first).unwrap(); + worker.retire(first); + complete(&host); + let bytes = plan.as_ref().unwrap().retained_bytes(); + let held = host.admitted_bytes(); + if replace_host { + s.set_render_job_host(Some(CpuHost::cooperative())).unwrap(); + } else { + batch::cancel(&mut s).unwrap(); + } + assert!(batch::claim_next(&mut s, &mut plan, CancelToken::default()).is_err()); + assert!(plan.is_some(), "wrong owner/stale queue refuses without dropping heavy plan on UI"); + let before = host.admitted_bytes(); + assert!(before >= bytes); + retire_plan(plan.take().unwrap()); + assert_eq!(host.admitted_bytes(), before - bytes); + assert!(held >= bytes); + } + } + #[test] + fn stale_idle_plan_cancellation_cannot_stop_an_identical_new_queue() { + let (mut s, host) = fixture(2); + let (mut first, worker) = initial(&mut s, json!({})); + batch::finish_retained(&mut s, &mut first).unwrap(); + let stale = batch::take_plan(&mut first).unwrap().unwrap(); + worker.retire(first); + batch::cancel(&mut s).unwrap(); + complete(&host); + let mut params = Some(json!({})); + let mut scope = None; + let next = batch::claim(&mut s, &mut params, &mut scope, CancelToken::default()).unwrap(); + assert!(stale.owner_matches(&s), "same real owner does not prove the current queue epoch"); + assert!(!batch::cancel_plan(&mut s, &stale).unwrap()); + assert_eq!(s.render_queue_state().waiting, 1); + assert!(s.render_queue_state().preparing); + retire_plan(stale); + let (mut current, worker) = Worker::prepare(next); + batch::finish_retained(&mut s, &mut current).unwrap(); + let plan = batch::take_plan(&mut current).unwrap().unwrap(); + worker.retire(current); + assert!(batch::cancel_plan(&mut s, &plan).unwrap()); + retire_plan(plan); + complete(&host); + } + #[test] + fn native_batch_replace_design_keeps_only_hosts_and_retires_old_plan_under_its_original_lease() { + let (mut s, host) = fixture(2); + let (mut first, worker) = initial(&mut s, json!({})); + batch::finish_retained(&mut s, &mut first).unwrap(); + let mut plan = batch::take_plan(&mut first).unwrap(); + worker.retire(first); + let bytes = plan.as_ref().unwrap().retained_bytes(); + s.replace_design(Session::default()); + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().job.is_none()); + assert!(!plan.as_ref().unwrap().owner_matches(&s)); + assert!(batch::claim_next(&mut s, &mut plan, CancelToken::default()).is_err()); + assert!(plan.is_some()); + let before = host.admitted_bytes(); + retire_plan(plan.take().unwrap()); + assert_eq!(host.admitted_bytes(), before - bytes); + complete(&host); + } + #[test] + fn native_batch_rechecks_arbitrary_current_guard_with_full_arena_restored_negative_zero_params() { + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut s, host) = fixture(2); + let allow = Arc::new(AtomicBool::new(true)); + let policy = allow.clone(); + let calls = Arc::new(std::sync::Mutex::new(Vec::new())); + let observed = calls.clone(); + let uid = s.uid; + s.set_command_check(Some(Arc::new(move |id, params, owner| { + if id == "render.batch" || id == "render.start" { + let request = if id == "render.batch" { ¶ms["request"] } else { params }; + assert_eq!(request["studio_weights"][0].as_f64().unwrap().to_bits(), (-0.0_f64).to_bits()); + assert_eq!(owner.uid, uid); + observed.lock().unwrap().push((id.to_string(), std::thread::current().id())); + if id == "render.start" && !policy.load(Ordering::Acquire) { + return Err("current mutable callback refused the next camera".into()); + } + } + Ok(()) + }))); + let params = json!({"request":{"settings":{"width":3,"height":2},"studio_weights":[-0.0,0.5,1.0]}}); + let (mut first, worker) = initial(&mut s, params); + batch::finish_retained(&mut s, &mut first).unwrap(); + let mut plan = batch::take_plan(&mut first).unwrap(); + worker.retire(first); + complete(&host); + let claim = batch::claim_next(&mut s, &mut plan, CancelToken::default()).unwrap().unwrap(); + let (mut next, worker) = Worker::prepare(claim); + let held = host.admitted_bytes(); + allow.store(false, Ordering::Release); + assert!(batch::finish_retained(&mut s, &mut next).unwrap_err().to_string().contains("mutable callback")); + assert!(!next.committed()); + assert_eq!(host.admitted_bytes(), held); + worker.retire(next); + assert_eq!(s.render_queue_state().waiting, 0); + let calls = calls.lock().unwrap(); + assert_eq!(calls.len(), 6); + let window = std::thread::current().id(); + assert_eq!(calls[0].0, "render.batch"); + assert_eq!(calls[0].1, window); + assert_ne!(calls[1].1, window); + assert_eq!(calls[2].0, "render.batch"); + assert_eq!(calls[2].1, window); + assert_eq!(calls[3].0, "render.start"); + assert_eq!(calls[3].1, window); + assert_ne!(calls[4].1, window); + assert_eq!(calls[5].1, window); + } + + #[test] + fn native_batch_first_commit_rechecks_only_batch_refusal_with_exact_moved_input_and_retains_credit() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + let (mut s, host) = fixture(2); + let mut method = String::with_capacity(512); + method.push_str("raster"); + let params = json!({"request":{"settings":{"width":3,"height":2,"job":{"method":method}},"studio_weights":[-0.0,0.5,1.0]}}); + let original_method = params["request"]["settings"]["job"]["method"].as_str().unwrap().as_ptr() as usize; + let expected = params.clone(); + let allow = Arc::new(AtomicBool::new(true)); + let policy = allow.clone(); + let batches = Arc::new(AtomicUsize::new(0)); + let batch_calls = batches.clone(); + let starts = Arc::new(AtomicUsize::new(0)); + let start_calls = starts.clone(); + let uid = s.uid; + s.set_command_check(Some(Arc::new(move |id, input, owner| { + assert_eq!(owner.uid, uid); + if id == "render.batch" { + batch_calls.fetch_add(1, Ordering::AcqRel); + assert_eq!(*input, expected); + assert_eq!( + input["request"]["settings"]["job"]["method"].as_str().unwrap().as_ptr() as usize, + original_method, + "the original raw input moves; guard metadata is not reconstructed or cloned" + ); + assert_eq!(input["request"]["studio_weights"][0].as_f64().unwrap().to_bits(), (-0.0_f64).to_bits()); + if !policy.load(Ordering::Acquire) { + return Err("current Batch-only policy refuses this first camera".into()); + } + } else if id == "render.start" { + start_calls.fetch_add(1, Ordering::AcqRel); + } + Ok(()) + }))); + let (mut first, worker) = initial(&mut s, params); + assert_eq!(batches.load(Ordering::Acquire), 1); + assert_eq!(starts.load(Ordering::Acquire), 1, "worker Start policy remains allowed"); + let held = host.admitted_bytes(); + assert!(held > 0); + allow.store(false, Ordering::Release); + let error = batch::finish_retained(&mut s, &mut first).unwrap_err(); + assert!(error.to_string().contains("Batch-only policy")); + assert_eq!(batches.load(Ordering::Acquire), 2, "current real-owner Batch guard runs at first commit"); + assert_eq!(starts.load(Ordering::Acquire), 1, "Batch refusal occurs before any actual Start enqueue"); + assert!(!first.committed()); + assert!(s.render_retained_results().unwrap().is_empty()); + assert!(s.render_queue_state().job.is_none()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert_eq!(host.admitted_bytes(), held, "window-side refusal retains all source, request and plan leases"); + worker.retire(first); + assert_eq!(host.admitted_bytes(), 0, "same worker drops ownership before acknowledgement"); + s.set_command_check(None); + let reply = s.execute("render.start", &json!({"settings":{"width":1,"height":1,"job":{"method":"raster"}}})).unwrap(); + let job: solidcraft_render::job::JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + assert_eq!(job.serial, 1, "refused Batch and scratch preparation consumed no actual registry identity"); + complete(&host); + } + + #[test] + fn native_batch_worker_context_survives_plan_take_until_source_drop_and_release_ack() { + use std::sync::atomic::{AtomicBool, Ordering}; + struct DropInScope { + path: String, + seen: Arc, + } + impl Drop for DropInScope { + fn drop(&mut self) { + let scope = solidcraft_io::vfs::current_scope().expect("source destruction stays in its original worker permission context"); + scope.check(&self.path).unwrap(); + self.seen.store(true, Ordering::Release); + } + } + let (mut s, host) = fixture(2); + let seen = Arc::new(AtomicBool::new(false)); + let probe = + DropInScope { path: std::env::temp_dir().join("solidcraft-batch-scope-drop.hdr").to_string_lossy().into_owned(), seen: seen.clone() }; + s.set_command_check(Some(Arc::new(move |_, _, _| { + assert!(!probe.path.is_empty()); + Ok(()) + }))); + let mut params = Some(json!({})); + let mut scope = Some(solidcraft_io::vfs::PathScope::new([std::env::temp_dir()])); + let claim = batch::claim(&mut s, &mut params, &mut scope, CancelToken::default()).unwrap(); + let (mut prepared, worker) = Worker::prepare(claim); + batch::finish_retained(&mut s, &mut prepared).unwrap(); + let plan = batch::take_plan(&mut prepared).unwrap().unwrap(); + s.set_command_check(None); + assert!(!seen.load(Ordering::Acquire)); + worker.retire(prepared); + assert!(seen.load(Ordering::Acquire), "ack follows source destruction inside original scope even though Plan moved to UI"); + batch::cancel_plan(&mut s, &plan).unwrap(); + retire_plan(plan); + complete(&host); + } + + #[test] + fn pending_batch_cancel_policy_check_uses_the_same_typed_params_and_current_host_refusal() { + let (mut s, host) = fixture(1); + let doc = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len()); + assert_eq!(batch::check_cancel(&s, &json!({})).unwrap(), None); + assert!(batch::check_cancel(&s, &json!({"unexpected":true})).is_err()); + assert!(batch::check_cancel(&s, &json!({"job":{"session":999,"serial":1,"generation":1}})).is_err()); + s.set_command_check(Some(Arc::new(|id, _, _| if id == "render.cancel" { Err("embedding cancellation refusal".into()) } else { Ok(()) }))); + assert!(batch::check_cancel(&s, &json!({})).unwrap_err().to_string().contains("embedding cancellation refusal")); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), before); + assert_eq!(s.render_queue_state().waiting, 0); + assert_eq!(host.admitted_bytes(), 0); + } +} diff --git a/crates/engine/src/cmd/render/jobs.rs b/crates/engine/src/cmd/render/jobs.rs index 5636b2b9c..a3948f2b4 100644 --- a/crates/engine/src/cmd/render/jobs.rs +++ b/crates/engine/src/cmd/render/jobs.rs @@ -11,6 +11,7 @@ use solidcraft_render::{ #[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct Start { + aging: solidcraft_doc::render_aging::SavedAgingStack, studio_weights: Option<[f64; 3]>, progressive: bool, denoise: bool, @@ -74,14 +75,10 @@ struct ProgressiveStart { denoise: bool, } -struct Prepared { - replace: bool, - scene: solidcraft_render::ProductScene, - request: ImageRequest, - reply: Value, - executor: solidcraft_render::ExecutorId, - options: solidcraft_render::job::JobOptions, - environment: Option, +pub(crate) struct Prepared { + pub(crate) replace: bool, + pub(crate) submission: Option, + pub(crate) reply: Value, } fn lower_led(input: &mut Start, command: &str) -> Result<()> { @@ -179,12 +176,13 @@ fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result json!({"transparent_background":transparent_background}), - RenderJob::CpuRaytrace { options } => { + RenderJob::CpuRaytrace { mut options, transparent_background } => { hdr = options.hdr.map(SavedHdr::Cpu); + let aging = std::mem::take(&mut options.aging); let raytrace = options.to_runtime(settings.exposure_ev).map_err(|e| bad(command, e.to_string()))?; // The legacy CPU path reads EV from RaytraceOptions. There is one saved authority. settings.exposure_ev = 0.0; - json!({"integrator":"raytrace","raytrace":raytrace}) + json!({"integrator":"raytrace","raytrace":raytrace,"aging":aging,"transparent_background":transparent_background}) } RenderJob::GpuPath { transparent_background, options } => { hdr = options.hdr.map(SavedHdr::Gpu); @@ -209,14 +207,26 @@ fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result Result { +pub(crate) fn prepare(s: &Session, params: &Value, command: &str, cancel: &solidcraft_render::job::CancelToken) -> Result { + prepare_with_metadata(s, params, command, cancel, None) +} +pub(crate) fn prepare_with_metadata( + s: &Session, + params: &Value, + command: &str, + cancel: &solidcraft_render::job::CancelToken, + retained: Option<&solidcraft_render::job::RetainedMetadata>, +) -> Result { + cancel.check().map_err(job_error)?; let normalized = normalize_saved_job(s, params, command)?; let saved_hdr = normalized.as_ref().and_then(|normalized| normalized.hdr.as_ref()); let params = normalized.as_ref().map_or(params, |normalized| &normalized.params); if params.get("progressive").and_then(Value::as_bool) == Some(true) { let hdr = match saved_hdr { Some(SavedHdr::Gpu(hdr)) => Some(*hdr), - Some(SavedHdr::Cpu(_)) => return Err(bad(command, "saved CPU HDR cannot enter a GPU request")), + Some(SavedHdr::Cpu(_)) => { + return Err(bad(command, "saved CPU HDR cannot enter a GPU request")); + } None => None, }; return prepare_progressive( @@ -227,6 +237,8 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { hdr, normalized.as_ref().map(|n| &n.surfaces), normalized.as_ref().map(|n| &n.optics), + cancel, + retained, ); } let gpu_raytrace = @@ -242,12 +254,42 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { )); } let mut input: Start = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let coats = input.settings.as_mut().map_or_else(Default::default, |settings| std::mem::take(&mut settings.coats)); + // A checked file HDR uses the runtime request lane, but its optical targets + // remain stable authored identities. Extract them before validating job:null + // settings, just as for stable coats; never discard or turn them into ordinals + // in the UI. Exact visible identities are resolved from the captured scene. + let inline_optics = input.settings.as_mut().map_or_else(Default::default, |settings| std::mem::take(&mut settings.optics)); + let normalized_optics = normalized.as_ref().map(|n| &n.optics).filter(|bindings| !bindings.is_empty()); + if normalized_optics.is_some() && !inline_optics.is_empty() { + return Err(bad(command, "choose normalized or inline stable optics, not both")); + } + let saved_optics = normalized_optics.or((!inline_optics.is_empty()).then_some(&inline_optics)); + if let Some(bindings) = saved_optics { + if input.integrator != Integrator::Raytrace { + return Err(bad(command, "stable optics require CPU or GPU ray tracing")); + } + let options = input.raytrace.get_or_insert_default(); + bindings.validate_for_cpu_path(options.path.is_some()).map_err(|e| bad(command, e.to_string()))?; + if options.volume.is_some_and(|volume| volume.active()) { + return Err(bad(command, "CPU Atmosphere cannot combine with saved Glass or subsurface scattering; settings are kept")); + } + if options.denoise && bindings.iter().any(|binding| binding.optics.subsurface.is_some_and(|scatter| scatter.active())) { + return Err(bad(command, "CPU subsurface random walks have no surface-denoiser guides; disable denoising explicitly")); + } + if !options.dielectrics.is_empty() { + return Err(bad(command, "saved optics cannot combine with runtime dielectric overrides")); + } + } + if !coats.is_empty() && input.integrator != Integrator::Raytrace { + return Err(bad(command, "stable clear coats require CPU or GPU ray tracing")); + } validate_studio_weights(input.studio_weights, command)?; if input.integrator == Integrator::Raytrace && input.studio_weights.is_some() { return Err(bad(command, "studio_weights apply to raster or the implicit GPU studio; use explicit CPU light intensities")); } if input.progressive { - return prepare_progressive(s, params, command, false, None, None, None); + return prepare_progressive(s, params, command, false, None, None, None, cancel, retained); } if input.denoise { return Err(bad(command, "denoise requires GPU progressive rendering")); @@ -266,14 +308,36 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { } host.validate_integrator(input.integrator).map_err(job_error)?; lower_led(&mut input, command)?; + if !input.aging.is_empty() { + if input.integrator != Integrator::Raytrace { + return Err(bad(command, "stable CPU aging requires the CPU raytrace integrator")); + } + input.aging.validate().map_err(|e| bad(command, e.to_string()))?; + input.raytrace.get_or_insert_with(RaytraceOptions::default); + } + let saved_surfaces = normalized.as_ref().map(|n| &n.surfaces).filter(|bindings| !bindings.is_empty()); + if saved_surfaces.is_some() { + if input.integrator != Integrator::Raytrace { + return Err(bad(command, "saved opaque surfaces require CPU or GPU ray tracing")); + } + solidcraft_render::job::textures::validate_cpu_options(input.raytrace.as_ref().unwrap_or(&RaytraceOptions::default())).map_err(job_error)?; + if normalized.as_ref().is_some_and(|n| !n.optics.is_empty()) && input.raytrace.as_ref().is_none_or(|options| options.path.is_none()) { + return Err(bad(command, "CPU maps with Glass require Indirect lighting and separate targets")); + } + } if input.integrator == Integrator::Raster && input.raytrace.is_some() { return Err(bad(command, "raytrace options require integrator: raytrace")); } - if input.integrator == Integrator::Raytrace && input.transparent_background { - return Err(bad(command, "raytrace supports opaque backgrounds only")); - } if let Some(options) = &input.raytrace { options.retained_bytes().map_err(job_error)?; + if !input.aging.is_empty() { + if options.aging.as_ref().is_some_and(|stack| !stack.is_empty()) { + return Err(bad(command, "choose stable authored aging or captured runtime aging, not both")); + } + if input.aging.iter().any(|layer| layer.active()) && options.anisotropic_faces.iter().any(Option::is_some) { + return Err(bad(command, "CPU aging cannot replace independently authored anisotropic roughness axes")); + } + } options.budget.validate_execution().map_err(job_error)?; // Check the complete image envelope before any source file is read. let dimensions = if let Some(name) = &input.setup { @@ -285,7 +349,29 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { let defaults = RenderSetup::default(); (defaults.width, defaults.height) }; - options.budget.validate_image(dimensions.0, dimensions.1, options.progressive).map_err(job_error)?; + options.budget.validate_image(dimensions.0, dimensions.1, options.camera_sampling().map_err(job_error)?).map_err(job_error)?; + if let Some(lens) = options.lens { + let camera = input + .setup + .as_ref() + .and_then(|name| s.doc.render.setups.get(name)) + .map(|setup| setup.camera) + .or_else(|| input.settings.as_ref().map(|setup| setup.camera)) + .or(s.camera) + .unwrap_or_default(); + lens.validate_camera(&camera).map_err(job_error)?; + } + if let Some(output) = &options.output { + output.validate_image(dimensions.0, dimensions.1).map_err(job_error)?; + output.presentation(options.exposure_ev, [0; 3], input.transparent_background).validate().map_err(job_error)?; + } + } + // Refuse conflicting sources before VFS/resource access. Sky is a direct + // radiance consumer and never a substitute for unread HDR bytes. + if (saved_hdr.is_some() || input.environment.is_some()) + && input.raytrace.as_ref().is_some_and(|options| options.sky.is_some() || options.environment.is_some()) + { + return Err(bad(command, "choose either CPU HDR input, gradient Sky or constant environment")); } let environment = if let Some(saved_hdr) = saved_hdr { let SavedHdr::Cpu(hdr) = saved_hdr else { @@ -336,15 +422,23 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { None }; let mut scene = crate::product_scene::extract(s)?; - let textures = if let Some(bindings) = normalized.as_ref().map(|saved| &saved.surfaces).filter(|bindings| !bindings.is_empty()) { - if input.integrator != Integrator::Raytrace { - return Err(bad(command, "saved surface maps require a raytrace executor")); + if let Some(bindings) = saved_optics { + let options = input.raytrace.as_mut().ok_or_else(|| bad(command, "saved CPU optics require a CPU raytrace request"))?; + if !options.dielectrics.is_empty() { + return Err(bad(command, "saved optics cannot combine with runtime dielectric overrides")); } - let overrides = super::surface_bindings::resolve(s, &scene, bindings, command)?; - super::textures::capture_with_resources(&scene, &overrides, Some(&s.doc.render.texture_resources), command)? - } else { - None - }; + options.dielectrics = super::optical_bindings::resolve_cpu_path(s, &scene, bindings, options.path.is_some(), command)?; + options.validate().map_err(job_error)?; + } + super::coat_bindings::apply(s, &mut scene, &coats, input.raytrace.as_ref(), command)?; + if !input.aging.is_empty() { + let options = input.raytrace.as_mut().ok_or_else(|| bad(command, "CPU aging requires a CPU raytrace request"))?; + if options.aging.as_ref().is_some_and(|stack| !stack.is_empty()) { + return Err(bad(command, "choose stable authored aging or captured runtime aging, not both")); + } + options.aging = Some(Box::new(super::effects::resolve_aging(s, &scene, &input.aging, command)?)); + options.validate().map_err(job_error)?; + } if environment.is_some() { input.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()).validate_environment_reflections(&scene).map_err(job_error)?; } @@ -369,7 +463,13 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { if input.integrator == Integrator::Raytrace { settings.validate_for_cpu(budget).map_err(|e| bad(command, e.to_string()))?; budget.validate_execution().map_err(job_error)?; - budget.validate_image(settings.width, settings.height, input.raytrace.as_ref().and_then(|o| o.progressive)).map_err(job_error)?; + budget + .validate_image( + settings.width, + settings.height, + input.raytrace.as_ref().map(|o| o.camera_sampling()).transpose().map_err(job_error)?.flatten(), + ) + .map_err(job_error)?; } else { settings.validate().map_err(|e| bad(command, e.to_string()))?; } @@ -416,6 +516,12 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { if resolved.executor != expected_executor { return Err(bad(command, "resolved executor is not installed as an image job host")); } + let textures = if let Some(bindings) = saved_surfaces { + let overrides = super::surface_bindings::resolve(s, &scene, bindings, command)?; + super::textures::capture_with_resources(&scene, &overrides, Some(&s.doc.render.texture_resources), command)? + } else { + None + }; let request = ImageRequest { studio_weights: validate_studio_weights(input.studio_weights, command)?, environment: None, @@ -428,12 +534,18 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { background: settings.background, transparent_background: input.transparent_background, }; - let mut admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?; let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?; + let submission = + host.prepare_submission_with_metadata(scene, request, Default::default(), environment, cancel.clone(), retained).map_err(job_error)?; + let request = submission.request(); + let mut admission = submission.admission(); let retained_lights = request.raytrace.as_ref().map_or(Ok(0), |o| o.retained_bytes()).map_err(job_error)?; let retained_environment = if environment_info.is_some() { std::mem::size_of::() as u64 } else { 0 }; - let retained_request_bytes = retained_lights.checked_add(retained_environment).ok_or_else(|| bad(command, "request metadata overflow"))?; + let retained_request_bytes = retained_lights + .checked_add(retained_environment) + .and_then(|bytes| bytes.checked_add(request.retained_resource_metadata_bytes())) + .ok_or_else(|| bad(command, "request metadata overflow"))?; admission.estimated_total_bytes = admission .estimated_total_bytes @@ -446,10 +558,38 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result { let transparency = match input.integrator { Integrator::Raster => "sorted_alpha_approximation", Integrator::Raytrace if refraction => "physical_transmission", + Integrator::Raytrace if input.transparent_background => "coverage_alpha", Integrator::Raytrace => "opaque_only", }; - let reply = json!({"ignored_controls":ignored,"stage_panels":settings.stage.len(),"stage_transport":"CPU direct/specular only; no diffuse interreflection", "cpu_budget":budget,"cpu_limits":budget.limits(),"environment":environment_info,"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":refraction,"dielectric_boundaries":if refraction {vec!["thin_sheet","closed_box"]} else {Vec::<&str>::new()}}); - Ok(Prepared { replace: input.replace, scene, request, reply, environment, executor: resolved.executor, options: Default::default() }) + let path = request.raytrace.as_ref().is_some_and(|options| options.path.is_some()); + let stage_transport = if path && refraction { + "CPU finite-depth diffuse/specular and dielectric path lighting" + } else if path { + "CPU finite-depth opaque diffuse/specular path lighting" + } else { + "CPU direct/specular only; no diffuse interreflection" + }; + let dielectric_boundaries = match (refraction, path) { + (true, true) => vec!["thin_sheet", "closed_box", "closed_mesh"], + (true, false) => vec!["thin_sheet", "closed_box"], + (false, _) => Vec::new(), + }; + let mut reply = json!({"ignored_controls":ignored,"stage_panels":settings.stage.len(),"stage_transport":stage_transport, "cpu_budget":budget,"cpu_limits":budget.limits(),"environment":environment_info,"textures":request.textures.as_ref().map(|maps|maps.summary()),"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":refraction,"dielectric_boundaries":dielectric_boundaries}); + if !coats.is_empty() { + reply["coats"] = json!(coats); + } + if request.raytrace.as_ref().is_some_and(|options| options.denoise) { + reply["denoising"] = json!({ + "method":"edge_aware_atrous", "backend":"native_cpu", "passes":3, "steps":[1,2,4], + "guides":"deterministic_center_ray_albedo_normal_camera_relative_position_depth", + "bypass":"glass, sharp CPU mirror overrides, smooth metal/coat, emitter, background and partial coverage first hits", + "limitation":"biased spatial filter; first-hit guides do not reconstruct reflection/refraction or depth-of-field correspondences", + "raw_linear_accumulator_preserved":true,"raw_linear_exr_preserved":true, + "output_stage":"linear_before_tone_map", "work_units":"one pixel visit per pass, each with at most 25 taps", + "checkpoints":"every complete published pass uses the same filter" + }); + } + Ok(Prepared { replace: input.replace, submission: Some(submission), reply }) } fn prepare_progressive( @@ -460,6 +600,8 @@ fn prepare_progressive( saved_hdr: Option, saved_surfaces: Option<&solidcraft_doc::render_surface::SurfaceBindings>, saved_optics: Option<&solidcraft_doc::render_optics::OpticalBindings>, + cancel: &solidcraft_render::job::CancelToken, + retained: Option<&solidcraft_render::job::RetainedMetadata>, ) -> Result { let cpu_raytrace = params .get("raytrace") @@ -474,6 +616,19 @@ fn prepare_progressive( return Err(bad(command, "progressive rendering does not accept CPU raytrace, environment or LED options")); } let mut input: ProgressiveStart = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let coats = input.settings.as_mut().map_or_else(Default::default, |settings| std::mem::take(&mut settings.coats)); + let inline_optics = input.settings.as_mut().map_or_else(Default::default, |settings| std::mem::take(&mut settings.optics)); + let normalized_optics = saved_optics.filter(|bindings| !bindings.is_empty()); + if normalized_optics.is_some() && !inline_optics.is_empty() { + return Err(bad(command, "choose normalized or inline stable optics, not both")); + } + let saved_optics = normalized_optics.or((!inline_optics.is_empty()).then_some(&inline_optics)); + if let Some(bindings) = saved_optics { + bindings.validate().map_err(|e| bad(command, e.to_string()))?; + if !input.raytrace.dielectrics.is_empty() || !input.raytrace.clear_coats.is_empty() { + return Err(bad(command, "saved optical bindings cannot be mixed with transient optical overrides")); + } + } validate_studio_weights(input.studio_weights, command)?; if input.studio_weights.is_some() && (input.lighting.is_some() || input.environment.is_some() || saved_hdr.is_some()) { return Err(bad(command, "studio_weights require the implicit GPU studio without environment lighting")); @@ -512,7 +667,11 @@ fn prepare_progressive( } input.raytrace.dielectrics = super::optical_bindings::resolve(s, &scene, bindings, command)?; } + if !coats.is_empty() && !input.raytrace.clear_coats.is_empty() { + return Err(bad(command, "stable clear coats cannot combine with runtime clear-coat overrides")); + } super::transmission::apply(&mut scene, &input.raytrace.dielectrics, command)?; + super::coat_bindings::apply(s, &mut scene, &coats, None, command)?; super::clear_coat::apply(&mut scene, &input.raytrace.clear_coats, command)?; let settings = if let Some(name) = &input.setup { s.doc.render.setups.get(name).cloned().ok_or_else(|| bad(command, "no saved render setup with that name"))? @@ -635,15 +794,22 @@ fn prepare_progressive( transparent_background: input.transparent_background, textures: super::textures::capture_with_resources(&scene, &input.raytrace.textures, Some(&s.doc.render.texture_resources), command)?, }; - let mut admission = host.admit(&scene, &request, options).map_err(job_error)?; + let refraction = input.progressive && scene.has_transmission(); + let submission = host.prepare_submission_with_metadata(scene, request, options, None, cancel.clone(), retained).map_err(job_error)?; + let request = submission.request(); + let mut admission = submission.admission(); + let retained_options_bytes = options.retained_bytes().map_err(job_error)?; admission.estimated_total_bytes = admission .estimated_total_bytes .checked_add(request.retained_resource_metadata_bytes()) + .and_then(|bytes| bytes.checked_add(retained_options_bytes)) .filter(|bytes| *bytes <= host.job_limit_bytes()) .ok_or_else(|| bad(command, "GPU work and retained metadata exceed the per-job limit"))?; - let refraction = input.progressive && scene.has_transmission(); - let reply = json!({"stage_panels":settings.stage.len(),"resolved":resolved,"admission":admission,"request":request,"textures":request.textures.as_ref().map(|resources|resources.summary()),"scene_generation":s.revision,"host":host.kind(),"transparency":if refraction {"physical_transmission"} else if input.progressive {"opaque_only"} else {"sorted_alpha_approximation"},"options":options,"environment":request.environment.as_ref().map(|source|source.info()),"refraction":refraction,"dielectric_boundaries": if resolved.executor.as_str() == "gpu-path" {vec!["thin_sheet","closed_box","closed_mesh"]} else {Vec::<&str>::new()}}); + let reply = json!({"stage_panels":settings.stage.len(),"resolved":resolved,"admission":admission,"request":request,"textures":request.textures.as_ref().map(|resources|resources.summary()),"scene_generation":s.revision,"host":host.kind(),"transparency":if refraction {"physical_transmission"} else if input.transparent_background {"coverage_alpha"} else if input.progressive {"opaque_only"} else {"sorted_alpha_approximation"},"options":options,"retained_options_bytes":retained_options_bytes,"environment":request.environment.as_ref().map(|source|source.info()),"refraction":refraction,"dielectric_boundaries": if resolved.executor.as_str() == "gpu-path" {vec!["thin_sheet","closed_box","closed_mesh"]} else {Vec::<&str>::new()}}); let mut reply = reply; + if !coats.is_empty() { + reply["coats"] = json!(coats); + } if options.denoise { reply["denoising"] = json!({ "method":"edge_aware_atrous", "passes":3, "steps":[1,2,4], @@ -653,7 +819,7 @@ fn prepare_progressive( "raw_linear_accumulator_preserved":true, "output_stage":"linear_before_tone_map" }); } - Ok(Prepared { replace: input.replace, scene, request, reply, executor: resolved.executor, options, environment: None }) + Ok(Prepared { replace: input.replace, submission: Some(submission), reply }) } /// The setup's controls the raster image executor doesn't apply: those not at their neutral value. @@ -672,24 +838,18 @@ fn ignored_controls(settings: &RenderSetup) -> Vec<&'static str> { } pub(super) fn preflight(s: &mut Session, params: &Value) -> Result { - prepare(s, params, "render.preflight").map(|p| p.reply) + prepare(s, params, "render.preflight", &solidcraft_render::job::CancelToken::default()).map(|p| p.reply) } pub(super) fn start(s: &mut Session, params: &Value) -> Result { - let p = prepare(s, params, "render.start")?; + let p = prepare(s, params, "render.start", &solidcraft_render::job::CancelToken::default())?; let status = s .render_jobs - .start_with_environment( + .start_prepared( s.revision, - p.scene, - p.request, + p.submission.ok_or_else(|| bad("render.start", "missing prepared submission"))?, p.replace, - crate::render_jobs::Execution { - executor: p.executor, - options: p.options, - environment: p.environment, - shot: params.get("setup").and_then(Value::as_str).map(str::to_owned), - }, + params.get("setup").and_then(Value::as_str).map(str::to_owned), ) .map_err(job_error)?; let mut status = json!(status); @@ -764,9 +924,18 @@ pub(super) fn copy(s: &mut Session, params: &Value) -> Result { Ok(json!({"frame":frame.info})) } -pub(super) fn cancel(s: &mut Session, params: &Value) -> Result { +pub(crate) fn cancel_params(params: &Value) -> Result> { + let empty = Value::Object(Default::default()); + let params = if params.is_null() { &empty } else { params }; let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; - let job = input.job.or(s.render_queue_state().job).ok_or_else(|| bad("render.cancel", "job is required without an active shot queue"))?; + Ok(input.job) +} +pub(super) fn cancel(s: &mut Session, params: &Value) -> Result { + let requested = cancel_params(params)?; + if requested.is_none() && s.cancel_native_preparation() { + return Ok(json!({"preparing":true,"cancel_requested":true,"queue":s.render_queue_state()})); + } + let job = requested.or(s.render_queue_state().job).ok_or_else(|| bad("render.cancel", "job is required without an active shot queue"))?; let status = s.render_jobs.status(job).map_err(job_error)?; s.cancel_render_batch(job); if status.progress.phase.terminal() { diff --git a/crates/engine/src/cmd/render/library.rs b/crates/engine/src/cmd/render/library.rs index 5b62a4b55..032d44b64 100644 --- a/crates/engine/src/cmd/render/library.rs +++ b/crates/engine/src/cmd/render/library.rs @@ -9,17 +9,17 @@ use serde::Deserialize; use serde_json::{Value, json}; use solidcraft_doc::{ render_resources::{CpuHdrEnvironment, GpuHdrEnvironment, HdrId, HdrResource}, - render_settings::RenderJob, + render_settings::{CpuJob, RenderJob, RenderSetup}, }; use solidcraft_render::{ - job::{AreaLight, AreaLights, StudioLighting, Sun}, + job::{AreaLight, AreaLights, RectangleLightOptions, StudioLighting, Sun}, texture_input::MapRole, }; use crate::schema::TypedContract; use crate::schema::render_library::{ LibraryDescribeParams, LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryResource, LibraryTargets, - LibraryTargetsParams, Pbr, RenderTarget, ResourceSummary, SceneBounds, + LibraryTargetsParams, Pbr, RenderTarget, ResourceSummary, SceneBounds, StableRenderTarget, }; use crate::{Result, Session, params::bad}; @@ -98,7 +98,7 @@ fn projection(kind: &str, value: &Value) -> Value { "native_scenes" => json!({"status":"native_composition","executor":"gpu-path","variants":["review_then_apply"], "preserves":["camera","materials","geometry","engineering_properties"],"requires_subject_and_explicit_replacement_consent":true}), "surfaces" => { - json!({"status":"implemented_pending_batch_validation","variants":if cfg!(feature="bundled-render-library") {vec!["uniform_opaque","gpu_planar_maps"]} else {vec!["uniform_opaque"]}, + json!({"status":"implemented_pending_batch_validation","variants":if cfg!(feature="bundled-render-library") {vec!["uniform_opaque","gpu_planar_maps","cpu_saved_planar_maps"]} else {vec!["uniform_opaque"]}, "omitted":["height_displacement","true_anisotropic_brdf","manufacturing_geometry"],"maps_portability":"version_and_digest_pinned_builtin_setup_bindings"}) } "selene_appearances" => json!({"status":"implemented_pending_batch_validation","variants":["uniform_opaque"], @@ -227,6 +227,12 @@ pub(super) fn targets(s: &mut Session, params: &Value) -> Result { } let query = input.query.to_lowercase(); let scene = crate::product_scene::extract(s)?; + let mut stable = BTreeMap::new(); + for (target, name) in super::surface_bindings::targets(s, command)? { + if stable.insert(name, target).is_some() { + return Err(bad(command, "ambiguous stable occurrence name")); + } + } let count = scene.meshes.iter().filter(|body| body.name.to_lowercase().contains(&query)).count(); let items: Vec<_> = scene .meshes @@ -238,6 +244,7 @@ pub(super) fn targets(s: &mut Session, params: &Value) -> Result { .map(|(ordinal, body)| RenderTarget { ordinal, name: body.name.clone(), + stable_target: stable.get(&body.name).map(StableRenderTarget::from), color: body.color, opacity: body.opacity, pbr: body.surface.map(|v| Pbr { metallic: v.metallic(), roughness: v.roughness(), dielectric_ior: v.dielectric_ior() }), @@ -435,7 +442,7 @@ struct EnvironmentApply { fn has_environment(setup: &solidcraft_doc::render_settings::RenderSetup) -> bool { match &setup.job { - Some(RenderJob::CpuRaytrace { options }) => options.hdr.is_some() || options.environment.is_some(), + Some(RenderJob::CpuRaytrace { options, .. }) => options.hdr.is_some() || options.environment.is_some() || options.sky.is_some(), Some(RenderJob::GpuPath { options, .. }) => options.hdr.is_some() || options.environment.is_some(), _ => false, } @@ -452,10 +459,13 @@ pub(super) fn apply_environment(s: &mut Session, params: &Value) -> Result { - if !input.replace_environment && (options.hdr.is_some() || options.environment.is_some()) { + Some(RenderJob::CpuRaytrace { options, .. }) => { + if !input.replace_environment && (options.hdr.is_some() || options.environment.is_some() || options.sky.is_some()) { return Err(bad(command, "existing environment requires replace_environment: true")); } + if metadata["solar_disk"] == true && options.sun.is_some() { + return Err(bad(command, "the selected HDR already owns the sun; remove the analytic sun explicitly")); + } CpuHdrEnvironment::check_controls(rotation, input.intensity, input.samples).map_err(|e| bad(command, e.to_string()))?; } Some(RenderJob::GpuPath { options, .. }) => { @@ -474,8 +484,9 @@ pub(super) fn apply_environment(s: &mut Session, params: &Value) -> Result { + Some(RenderJob::CpuRaytrace { options, .. }) => { options.environment = None; + options.sky = None; options.hdr = Some(CpuHdrEnvironment { resource: digest, rotation_rad: rotation, intensity: input.intensity, samples: input.samples }); } Some(RenderJob::GpuPath { options, .. }) => { @@ -556,7 +567,9 @@ pub(super) fn prepare_surface(s: &mut Session, params: &Value) -> Result "base_color_srgb":format!("builtin://{}/base_color",input.id),"normal_opengl":format!("builtin://{}/normal_open_gl",input.id), "roughness_linear":format!("builtin://{}/roughness",input.id),"metallic_linear":format!("builtin://{}/metallic",input.id)}, "source_maps":manifest["maps"],"omitted":["height_displacement","true_anisotropic_brdf","manufacturing_geometry"], - "dielectric_ior":"captured_body_value","persistence":"transient_request_binding; authored source bytes are built in"})) + "dielectric_ior":"captured_body_value","persistence":"transient_request_binding; authored source bytes are built in", + "compatible_saved_methods":if cfg!(feature="bundled-render-library") {vec!["cpu_raytrace","gpu_path"]} else {Vec::<&str>::new()}, + "cpu_maps":"saved_builtin_opaque_only; direct_or_indirect_lighting; level_zero_bilinear; incompatible_optics_refuse"})) } #[derive(Deserialize)] @@ -620,7 +633,13 @@ pub(super) fn rig_lighting(input: &RigInput, command: &str) -> Result<(StudioLig _ => return Err(bad(command, "authored light has no exact runtime adapter")), } } - let lighting = StudioLighting { environment: [0.0; 3], sun, area_lights: AreaLights::new(&areas).map_err(|e| bad(command, e.to_string()))? }; + let lighting = StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + environment: [0.0; 3], + sun, + area_lights: AreaLights::new(&areas).map_err(|e| bad(command, e.to_string()))?, + }; lighting.validate().map_err(|e| bad(command, e.to_string()))?; Ok(( lighting, @@ -684,12 +703,106 @@ pub(super) fn rig_clearance(scene: &solidcraft_render::ProductScene, lighting: & } Ok(()) } -pub(super) fn prepare_studio(_s: &mut Session, params: &Value) -> Result { +/// Exact typed bridge for the currently authored achromatic area/Sun rigs. +/// This changes lighting authority only, retaining dormant CPU sampling fields. +pub(super) fn cpu_studio_lighting(options: &mut CpuJob, lighting: &StudioLighting, command: &str) -> Result { + lighting.validate().map_err(|e| bad(command, e.to_string()))?; + if lighting.environment != [0.0; 3] || !lighting.directional_lights.is_empty() || !lighting.punctual_lights.is_empty() { + return Err(bad(command, "authored CPU studio projection requires its explicit area/Sun rig and separate environment authority")); + } + let mut areas = Vec::new(); + areas.try_reserve_exact(lighting.area_lights.iter().count()).map_err(|_| bad(command, "could not reserve CPU studio lights"))?; + for (index, light) in lighting.area_lights.iter().enumerate() { + let [r, g, b] = light.radiance; + if r.to_bits() != g.to_bits() || r.to_bits() != b.to_bits() { + return Err(bad( + command, + format!("authored rectangle {index} needs a lossless CPU colour/intensity projection; this rig is not supported"), + )); + } + if !(0.0..=64.0).contains(&r) { + return Err(bad( + command, + format!( + "authored rectangle {index} radiance {r} exceeds CPU area intensity 0..64; this rig is unavailable without changing its authored light" + ), + )); + } + areas.push(RectangleLightOptions { + center_mm: light.center, + edge_u_mm: light.u.map(|value| value * 2.0), + edge_v_mm: light.v.map(|value| value * 2.0), + color: [1.0; 3], + intensity: r, + }); + } + let needs_indirect = lighting.sun.is_some() && options.path.is_none(); + options.preset = None; + options.lights = Some(Vec::new()); + options.punctual_lights = Some(Vec::new()); + options.area_lights = Some(areas); + options.sun = lighting.sun; + options.environment = None; + options.sky = None; + options.hdr = None; + Ok(needs_indirect) +} +fn adopt_studio_indirect(setup: &mut RenderSetup) { + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job { + options.path.get_or_insert_default(); + options.progressive.get_or_insert_default(); + options.primary_samples = 1; + options.shadows = true; + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct StudioPrepare { + id: String, + variant: String, + center_mm: [f64; 3], + subject_extent_mm: f64, + #[serde(default)] + name: Option, + #[serde(default = "empty_patch")] + set: Value, + #[serde(default)] + enable_indirect: bool, +} +pub(super) fn prepare_studio(s: &mut Session, params: &Value) -> Result { let command = "render.library.studio.prepare"; - let input: RigInput = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; - let (lighting, projection) = rig_lighting(&input, command)?; - let stage = rig_stage(&input, command)?; - Ok(json!({"lighting":lighting,"stage":stage,"projection":projection,"requires_geometry_clearance_review":true,"document_changed":false})) + let input: StudioPrepare = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let rig = RigInput { id: input.id, variant: input.variant, center_mm: input.center_mm, subject_extent_mm: input.subject_extent_mm }; + let (lighting, projection) = rig_lighting(&rig, command)?; + let stage = rig_stage(&rig, command)?; + let mut report = + json!({"lighting":lighting,"stage":stage,"projection":projection,"requires_geometry_clearance_review":true,"document_changed":false}); + if let Some(name) = input.name { + let mut setup = super::patched_settings(s, &name, &input.set, command)?; + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { + return Err(bad(command, "typed rig context requires a selected CPU raytrace setup")); + }; + let needs_indirect = cpu_studio_lighting(options, &lighting, command)?; + // Resolve the complete prospective adoption without publishing it. Apply + // still requires the separate explicit action below, at current revision. + if needs_indirect { + adopt_studio_indirect(&mut setup); + } + setup.stage = stage; + setup.validate().map_err(|e| bad(command, e.to_string()))?; + report["setup"] = json!(setup); + report["executor"] = json!("cpu-raytrace"); + report["revision"] = json!(s.revision); + report["requires_indirect"] = json!(needs_indirect); + report["indirect_adoption"] = json!( + needs_indirect + .then_some(json!({"path_depth":8,"progressive_if_absent":{"samples_per_pixel":16,"seed":0},"primary_samples":1,"shadows":true})) + ); + } else if input.enable_indirect || input.set != json!({}) { + return Err(bad(command, "CPU rig context needs name and typed set")); + } + Ok(report) } #[derive(Deserialize)] @@ -702,6 +815,10 @@ struct StudioApply { replace_lighting_and_environment: bool, #[serde(default)] replace_stage: bool, + #[serde(default)] + enable_indirect: bool, + #[serde(default)] + expected_revision: Option, } pub(super) fn apply_studio(s: &mut Session, params: &Value) -> Result { let command = "render.library.studio.apply"; @@ -709,22 +826,35 @@ pub(super) fn apply_studio(s: &mut Session, params: &Value) -> Result { if !input.replace_lighting_and_environment { return Err(bad(command, "confirm replacing lighting and environment explicitly to preserve a single energy owner")); } + if input.expected_revision.is_some_and(|revision| revision != s.revision) { + return Err(bad(command, "scene or saved settings changed after rig review")); + } if !input.replace_stage && s.doc.render.setups.get(&input.name).is_some_and(|setup| !setup.stage.is_empty()) { return Err(bad(command, "existing stage requires replace_stage: true")); } let (lighting, projection) = rig_lighting(&input.rig, command)?; let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; - let Some(RenderJob::GpuPath { options, .. }) = &mut setup.job else { - return Err(bad(command, "authored area/sun rigs require an explicit GPU job")); - }; let stage = rig_stage(&input.rig, command)?; if !setup.stage.is_empty() && !input.replace_stage { return Err(bad(command, "existing stage requires replace_stage: true")); } setup.stage = stage; - options.lighting = Some(lighting); - options.environment = None; - options.hdr = None; + let needs_indirect = match &mut setup.job { + Some(RenderJob::CpuRaytrace { options, .. }) => cpu_studio_lighting(options, &lighting, command)?, + Some(RenderJob::GpuPath { options, .. }) => { + options.lighting = Some(lighting); + options.environment = None; + options.hdr = None; + false + } + _ => return Err(bad(command, "authored rigs require an explicit CPU or GPU raytrace setup")), + }; + if needs_indirect { + if !input.enable_indirect { + return Err(bad(command, "this CPU Sun rig requires explicit Enable indirect lighting and apply consent")); + } + adopt_studio_indirect(&mut setup); + } setup.validate().map_err(|e| bad(command, e.to_string()))?; let mut scene = crate::product_scene::extract(s)?; super::staging::apply(&mut scene, &setup, command)?; diff --git a/crates/engine/src/cmd/render/library_tests.rs b/crates/engine/src/cmd/render/library_tests.rs index 90e857973..2fdebb700 100644 --- a/crates/engine/src/cmd/render/library_tests.rs +++ b/crates/engine/src/cmd/render/library_tests.rs @@ -209,7 +209,7 @@ fn builtin_hdr_capture_is_atomic_undoable_deduplicated_and_path_independent() { assert_eq!(reply["source_sha256"], reply["resource"]); assert_eq!(reply["native_rotation_rad"], std::f64::consts::PI); assert_eq!(reply["self_contained"], true); - let Some(RenderJob::CpuRaytrace { options }) = &s.doc.render.setups["Library CPU"].job else { + let Some(RenderJob::CpuRaytrace { options, .. }) = &s.doc.render.setups["Library CPU"].job else { panic!("CPU intent"); }; let id = options.hdr.unwrap().resource; @@ -526,6 +526,10 @@ fn saved_surface_rejects_changed_feature_and_hidden_target_and_can_be_removed_of let before = s.doc.to_json(); assert!(s.execute("render.settings.set", &json!({"name":"P","set":{"job":{"method":"raster"}}})).is_err()); assert_eq!(s.doc.to_json(), before); + let bindings = s.doc.render.setups["P"].surfaces.clone(); + s.execute("render.settings.set", &json!({"name":"P","set":{"job":{"method":"cpu_raytrace","options":{}}}})).unwrap(); + assert_eq!(s.doc.render.setups["P"].surfaces, bindings, "supported CPU method changes preserve saved bindings, even offline"); + assert!(s.render_job_host().is_none()); } #[test] @@ -633,3 +637,266 @@ fn omitted_optional_pack_keeps_discovery_but_refuses_resource_mutation() { assert_eq!(session.doc, before); assert_eq!((session.revision, session.undo.len()), history); } + +#[cfg(feature = "bundled-render-library")] +#[test] +fn cpu_saved_surface_binding_is_offline_undoable_portable_and_preserves_geometry_and_unsupported_intent() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Coupon"})).unwrap(); + let before = s.doc.clone(); + let undo = s.undo.len(); + let camera = solidcraft_render::Camera::default(); + let set = json!({"camera":camera,"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":9},"output":{"linear_exr":true}}}}); + let input = json!({"name":"CPU maps","set":set,"surface":{"id":"SURF-001","body_index":0,"body_name":"Coupon"}}); + assert!(s.render_job_host().is_none()); + s.execute("render.library.surface.bind", &input).unwrap(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.doc.features, before.features); + assert_eq!(s.doc.materials, before.materials); + assert_eq!(s.doc.appearances, before.appearances); + let setup = s.doc.render.setups["CPU maps"].clone(); + assert_eq!(setup.surfaces.len(), 1); + assert_eq!(setup.camera, camera); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened, *s.doc); + let snapshot = s.doc.clone(); + let history = (s.revision, s.undo.len(), s.redo.len()); + for options in [ + json!({"reflections":{"bodies":[{"body":"Coupon","mode":"mirror"}],"samples":1,"max_bounces":2}}), + json!({"budget":"studio","progressive":{"samples_per_pixel":3,"seed":9},"path":{"max_depth":2},"shadows":false}), + ] { + let mut hostile = input.clone(); + hostile["name"] = json!("Unsupported"); + hostile["set"]["job"]["options"] = options; + assert!(s.execute("render.library.surface.bind", &hostile).is_err()); + assert!(Arc::ptr_eq(&s.doc, &snapshot)); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), history); + } + let mut stale = setup.clone(); + let mut binding = stale.surfaces.iter().next().unwrap().clone(); + let solidcraft_doc::render_surface::SurfaceSource::Builtin(source) = &mut binding.source else { panic!("built-in fixture") }; + source.normal_sha256 = HdrId::of(b"changed"); + stale.surfaces.set(binding, true).unwrap(); + assert!(super::super::surface_bindings::resolve(&s, &crate::product_scene::extract(&s).unwrap(), &stale.surfaces, "test").is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc.render.setups["CPU maps"], setup); + s.execute("render.library.surface.unbind", &json!({"name":"CPU maps","target":setup.surfaces.iter().next().unwrap().target})).unwrap(); + assert!(s.doc.render.setups["CPU maps"].surfaces.is_empty()); + assert!(s.render_job_host().is_none()); +} + +#[cfg(feature = "bundled-render-library")] +#[test] +fn cpu_path_maps_bind_beside_saved_glass_and_targeted_aging_without_weakening_target_or_legacy_guards() { + let mut s = Session::default(); + for (name, corner) in [("Glass", [0, 0, 0]), ("Panel", [20, 0, 0])] { + s.execute("solid.box", &json!({"body_name":name,"length":10,"width":10,"height":5,"corner":corner,"operation":"new"})).unwrap(); + } + let targets = s.execute("render.library.targets", &json!({})).unwrap(); + let glass = targets["items"].as_array().unwrap().iter().find(|target| target["name"] == "Glass").unwrap().clone(); + let panel = targets["items"].as_array().unwrap().iter().find(|target| target["name"] == "Panel").unwrap().clone(); + assert_eq!(panel["stable_target"]["definition"], "Panel"); + assert_ne!(glass["stable_target"], panel["stable_target"]); + s.execute( + "render.settings.set", + &json!({"name":"Mixed","set":{"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{ + "progressive":{"samples_per_pixel":4,"seed":9},"path":{"max_depth":4}, + "aging":[{"kind":"dust","target":panel["stable_target"]}] + }}}}), + ) + .unwrap(); + s.execute( + "render.optics.bind", + &json!({"name":"Mixed","body_index":glass["ordinal"],"body_name":"Glass","expected_revision":s.revision, + "optics":{"ior":1.5,"boundary":"closed_mesh"}}), + ) + .unwrap(); + let before = s.doc.clone(); + let history = (s.revision, s.undo.len(), s.redo.len()); + assert!(s.render_job_host().is_none(), "authoring does not require an image producer"); + let input = |target: &Value| json!({"name":"Mixed","surface":{"id":"SURF-001","body_index":target["ordinal"],"body_name":target["name"]}}); + let error = s.execute("render.library.surface.bind", &input(&glass)).unwrap_err().to_string(); + assert!(error.contains("cannot share a target"), "{error}"); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), history); + let mut legacy = input(&panel); + legacy["set"] = json!({"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":4,"seed":9}}}}); + assert!(s.execute("render.library.surface.bind", &legacy).unwrap_err().to_string().contains("require Indirect lighting")); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), history); + s.execute("render.library.surface.bind", &input(&panel)).unwrap(); + assert_eq!(s.undo.len(), history.1 + 1); + let saved = s.doc.clone(); + let setup = &saved.render.setups["Mixed"]; + assert_eq!(setup.surfaces.len(), 1); + assert_eq!(setup.optics, before.render.setups["Mixed"].optics); + let solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. } = setup.job.as_ref().unwrap() else { panic!("CPU intent changed") }; + assert!(options.path.is_some()); + assert_eq!(options.aging.iter().next().unwrap().target.as_ref().unwrap(), &setup.surfaces.iter().next().unwrap().target); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + assert_eq!(saved.appearances, before.appearances); + assert_eq!(solidcraft_doc::Document::from_json(&saved.to_json()).unwrap(), *saved); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + assert!(s.render_job_host().is_none()); +} + +#[test] +fn cpu_authored_rig_domain_is_exact_and_preserves_dormant_sampling_without_implicit_lights() { + use solidcraft_doc::render_settings::CpuJob; + let mut s = Session::default(); + let mut accepted = Vec::new(); + let mut over_domain = Vec::new(); + for index in 1..=24 { + let id = format!("RIG-{index:03}"); + let rig = json!({"id":id,"variant":"complete","center_mm":[0,0,0],"subject_extent_mm":100}); + if s.execute("render.library.studio.prepare", &rig).is_err() { + continue; + } + let mut prepare = rig.clone(); + prepare["name"] = json!("Rig"); + prepare["set"] = json!({"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"area_samples":64,"seed":731}}}); + let before = s.doc.clone(); + let history = s.undo.len(); + let result = s.execute("render.library.studio.prepare", &prepare); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, s.undo.len()); + match result { + Ok(plan) => { + accepted.push(id.clone()); + let options: CpuJob = serde_json::from_value(plan["setup"]["job"]["options"].clone()).unwrap(); + assert_eq!(options.lights, Some(vec![])); + assert_eq!(options.punctual_lights, Some(vec![])); + assert_eq!((options.area_samples, options.seed), (Some(64), Some(731))); + assert!(options.environment.is_none() && options.sky.is_none() && options.hdr.is_none()); + assert_eq!(plan["requires_indirect"], id == "RIG-020"); + } + Err(error) => { + assert!(error.to_string().contains("exceeds CPU area intensity 0..64"), "{id}: {error}"); + over_domain.push(id); + let err = s + .execute( + "render.library.studio.apply", + &json!({"rig":rig,"name":"Rig","set":prepare["set"],"replace_lighting_and_environment":true}), + ) + .unwrap_err(); + assert!(err.to_string().contains("exceeds CPU area intensity 0..64")); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, s.undo.len()); + } + } + } + assert_eq!(accepted, vec!["RIG-007", "RIG-020", "RIG-022"]); + assert_eq!(over_domain.len(), 16); + let mut options = CpuJob { area_samples: Some(64), seed: Some(731), ..Default::default() }; + let before = options.clone(); + let light = AreaLight { center: [0., 0., 10.], u: [1., 0., 0.], v: [0., -1., 0.], radiance: [1., 0.5, 0.25] }; + let lighting = StudioLighting { area_lights: AreaLights::new(&[light]).unwrap(), ..Default::default() }; + assert!(cpu_studio_lighting(&mut options, &lighting, "test").unwrap_err().to_string().contains("lossless CPU colour/intensity projection")); + assert_eq!(options, before, "no lossy colour decomposition"); +} + +#[test] +fn cpu_sun_rig_adoption_is_explicit_complete_atomic_and_one_undo() { + let mut s = Session::default(); + s.execute("render.settings.set",&json!({"name":"Rig","set":{"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"primary_samples":4,"shadows":false,"area_samples":64,"seed":731}}}})).unwrap(); + let rig = json!({"id":"RIG-020","variant":"complete","center_mm":[0,0,0],"subject_extent_mm":100}); + let mut prepare = rig.clone(); + prepare["name"] = json!("Rig"); + let before = s.doc.clone(); + let undo = s.undo.len(); + let plan = s.execute("render.library.studio.prepare", &prepare).unwrap(); + assert_eq!(plan["requires_indirect"], true); + assert!(Arc::ptr_eq(&before, &s.doc)); + let mut apply = json!({"name":"Rig","rig":rig,"replace_lighting_and_environment":true,"expected_revision":s.revision}); + assert!(s.execute("render.library.studio.apply", &apply).unwrap_err().to_string().contains("Enable indirect lighting")); + assert_eq!(s.doc, before); + assert_eq!(s.undo.len(), undo); + apply["enable_indirect"] = json!(true); + s.execute("render.library.studio.apply", &apply).unwrap(); + assert_eq!(s.undo.len(), undo + 1); + let Some(RenderJob::CpuRaytrace { options, .. }) = &s.doc.render.setups["Rig"].job else { panic!() }; + assert_eq!(options.path.unwrap().max_depth, 8); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!((options.primary_samples, options.shadows, options.area_samples, options.seed), (1, true, Some(64), Some(731))); + assert!(options.sun.is_some()); + assert_eq!(options.area_lights, Some(vec![])); + let saved = s.doc.to_json(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc.to_json(), saved); + let before = s.doc.clone(); + assert!(s.execute("render.library.studio.apply", &apply).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc)); + let mut large = Session::default(); + let fixed = json!({"width":2048,"height":2048,"job":{"method":"cpu_raytrace","options":{}}}); + // This is an admitted fixed Compact image. Only explicit adoption of the + // complete progressive16 Sun request crosses Compact's1,048,576-pixel bound. + // Upstream's shared setup refusal names the admitting Studio profile rather + // than repeating the current Compact name, so assert the actual size proof. + use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions}; + let adopted = Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }); + assert!(CpuBudget::Compact.validate_image(2048, 2048, None).is_ok()); + assert_eq!(CpuBudget::Compact.limits().max_progressive_pixels, 1_048_576); + assert!(CpuBudget::Compact.validate_image(2048, 2048, adopted).is_err()); + assert!(CpuBudget::Studio.validate_image(2048, 2048, adopted).is_ok()); + let authored = super::super::patched_settings(&large, "Rig", &fixed, "render.library.studio.prepare").unwrap(); + assert_eq!((authored.width, authored.height), (2048, 2048)); + let Some(RenderJob::CpuRaytrace { options, .. }) = &authored.job else { panic!("typed fixed CPU setup") }; + assert_eq!(options.budget, CpuBudget::Compact); + assert!(options.progressive.is_none() && options.path.is_none()); + let mut oversized = prepare; + oversized["set"] = fixed.clone(); + let before = large.doc.clone(); + let state = (large.revision, large.evaluations, large.is_dirty(), large.undo.len(), large.redo.len(), large.camera); + let check_size_error = |error: String| { + assert!(error.contains("render output 2048 × 2048 exceeds the image limits"), "{error}"); + assert!(error.contains("1048576 pixels in all"), "{error}"); + assert!(error.contains("largest image at this aspect is 1024 × 1024"), "{error}"); + assert!(error.contains("choose the Studio CPU resource profile, or a smaller size"), "{error}"); + eprintln!("complete CPU Sun adoption refused without mutation: {error}"); + }; + check_size_error(large.execute("render.library.studio.prepare", &oversized).unwrap_err().to_string()); + assert!(Arc::ptr_eq(&before, &large.doc)); + assert_eq!((large.revision, large.evaluations, large.is_dirty(), large.undo.len(), large.redo.len(), large.camera), state); + let mut oversized = apply; + oversized.as_object_mut().unwrap().remove("expected_revision"); + oversized["set"] = fixed; + check_size_error(large.execute("render.library.studio.apply", &oversized).unwrap_err().to_string()); + assert!(Arc::ptr_eq(&before, &large.doc)); + assert_eq!((large.revision, large.evaluations, large.is_dirty(), large.undo.len(), large.redo.len(), large.camera), state); + assert!(large.undo.is_empty()); +} + +#[test] +fn cpu_sun_rig_keeps_existing_path_adaptive_seed_and_profile_and_rejects_unknown_context() { + let mut s = Session::default(); + let options = json!({"budget":"studio","progressive":{"samples_per_pixel":64,"seed":947},"adaptive":{"pilot_samples":32,"min_samples":32},"path":{"max_depth":5},"area_samples":4,"seed":731}); + s.execute("render.settings.set", &json!({"name":"Rig","set":{"width":96,"height":64,"job":{"method":"cpu_raytrace","options":options}}})) + .unwrap(); + let rig = json!({"id":"RIG-020","variant":"complete","center_mm":[0,0,0],"subject_extent_mm":100}); + let mut prepare = rig.clone(); + prepare["name"] = json!("Rig"); + let plan = s.execute("render.library.studio.prepare", &prepare).unwrap(); + assert_eq!(plan["requires_indirect"], false); + let old = s.doc.render.setups["Rig"].clone(); + s.execute("render.library.studio.apply", &json!({"name":"Rig","rig":rig,"replace_lighting_and_environment":true})).unwrap(); + let Some(RenderJob::CpuRaytrace { options: before, .. }) = old.job else { panic!() }; + let Some(RenderJob::CpuRaytrace { options: after, .. }) = &s.doc.render.setups["Rig"].job else { panic!() }; + assert_eq!( + (after.budget, after.progressive, after.adaptive, after.path, after.area_samples, after.seed), + (before.budget, before.progressive, before.adaptive, before.path, before.area_samples, before.seed) + ); + let doc = s.doc.clone(); + let undo = s.undo.len(); + prepare["extra"] = json!(true); + assert!(s.execute("render.library.studio.prepare", &prepare).is_err()); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(s.undo.len(), undo); +} diff --git a/crates/engine/src/cmd/render/light_union_tests.rs b/crates/engine/src/cmd/render/light_union_tests.rs index 5bea6f393..4d8f7adc7 100644 --- a/crates/engine/src/cmd/render/light_union_tests.rs +++ b/crates/engine/src/cmd/render/light_union_tests.rs @@ -39,7 +39,15 @@ fn normalized_twenty_source_preflight_has_one_metadata_authority_and_no_reservat assert_eq!(options.primary_samples, 16); assert_eq!(options.area_lights.as_ref().unwrap().len(), 4); assert_eq!(options.punctual_lights.as_ref().unwrap().len(), 8); - assert_eq!(reply["retained_request_bytes"], json!(options.retained_bytes().unwrap())); + assert_eq!( + reply["retained_request_bytes"], + json!( + options.retained_bytes().unwrap() + + serde_json::from_value::(reply["request"].clone()) + .unwrap() + .retained_resource_metadata_bytes() + ) + ); assert_eq!(host.admitted_bytes(), 0); assert_eq!(input, unchanged); assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); @@ -76,3 +84,63 @@ fn invalid_or_unavailable_union_preserves_stale_scene_before_capture_or_replacem assert_eq!(host.admitted_bytes(), 0); } } + +#[test] +fn cpu_finite_sun_common_edit_keeps_raw_radiance_identity_and_undo() { + let mut s = Session::default(); + let sun = json!({"direction":[0.2,-0.3,0.9],"angular_radius_rad":0.02,"radiance":[301.25,202.5,103.75]}); + s.execute("render.settings.set",&json!({"name":"CPU Sun","set":{"width":16,"height":12,"job":{"method":"cpu_raytrace","options":{ + "path":{"max_depth":4},"progressive":{"samples_per_pixel":3,"seed":81},"sun":sun,"punctual_lights":[],"area_lights":[],"lights":[{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}]}}}})).unwrap(); + let before = s.doc.render.setups["CPU Sun"].clone(); + let rows = crate::render_lights::inspect(&before).unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].id, "directional:0"); + assert_eq!(rows[1].id, "directional:1"); + let mut exact = before.clone(); + crate::render_lights::write(&mut exact, &rows).unwrap(); + assert_eq!(exact, before); + let undo = s.undo.len(); + s.execute("render.lights.set", &json!({"name":"CPU Sun","id":"directional:1","set":{"intensity_ev":2.0}})).unwrap(); + let changed = s.doc.render.setups["CPU Sun"].clone(); + assert_eq!(serde_json::to_value(&changed).unwrap()["job"]["options"]["sun"], sun); + let edited = crate::render_lights::inspect(&changed).unwrap(); + assert_eq!((edited[1].intensity, edited[1].colour), (4.0, [1.0, 0.5, 0.25])); + assert_eq!(edited[1].geometry, rows[1].geometry); + assert_eq!(s.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc.render.setups["CPU Sun"], before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc.render.setups["CPU Sun"], changed); + let document = s.doc.clone(); + let history = (s.undo.len(), s.redo.len(), s.revision); + let mut without_path = serde_json::to_value(&changed).unwrap(); + without_path["job"]["options"]["path"] = Value::Null; + assert!(s.execute("render.settings.set", &json!({"name":"CPU Sun","set":without_path})).is_err()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(history, (s.undo.len(), s.redo.len(), s.revision)); + // Radius zero retains the pre-existing hard-source representation without Path. + s.execute("render.settings.set",&json!({"name":"CPU hard","set":{"job":{"method":"cpu_raytrace","options":{"lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":1}]}}}})).unwrap(); + let hard = crate::render_lights::inspect(&s.doc.render.setups["CPU hard"]).unwrap(); + assert!(matches!(hard[0].geometry, crate::schema::render_lights::Geometry::Directional { angular_radius_rad: None, .. })); +} + +#[test] +fn cpu_sun_add_remove_returns_actual_canonical_addresses_and_preserves_other_sources() { + let mut s = Session::default(); + s.execute("render.settings.set",&json!({"name":"CPU rig","set":{"width":16,"height":12,"job":{"method":"cpu_raytrace","options":{ + "path":{"max_depth":4},"progressive":{"samples_per_pixel":3,"seed":81},"punctual_lights":[],"area_lights":[],"lights":[{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}]}}}})).unwrap(); + let before = s.doc.render.setups["CPU rig"].clone(); + let reply = s.execute("render.lights.add", &json!({"name":"CPU rig","set":{"kind":"directional","softness":0.1}})).unwrap(); + assert_eq!(reply["id"], "directional:0"); + let rows = crate::render_lights::inspect(&s.doc.render.setups["CPU rig"]).unwrap(); + assert_eq!(rows[1].id, "directional:1"); + assert_eq!(reply["id_remap"][0]["after_id"], "directional:1"); + let mut filtered = s.doc.render.setups["CPU rig"].clone(); + let visibility: crate::schema::render_lights::Visibility = serde_json::from_value(json!({"muted":["directional:0"]})).unwrap(); + crate::render_lights::filter(&mut filtered, &visibility).unwrap(); + let Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = filtered.job else { panic!("CPU expected") }; + assert_eq!(options.sun.unwrap().radiance, [0.0; 3]); + assert_eq!(options.lights.as_ref().unwrap()[0].intensity, 2.0); + s.execute("render.lights.remove", &json!({"name":"CPU rig","id":"directional:0"})).unwrap(); + assert_eq!(s.doc.render.setups["CPU rig"], before); +} diff --git a/crates/engine/src/cmd/render/lights.rs b/crates/engine/src/cmd/render/lights.rs index d323c5a5f..8a949d737 100644 --- a/crates/engine/src/cmd/render/lights.rs +++ b/crates/engine/src/cmd/render/lights.rs @@ -4,7 +4,7 @@ use serde_json::Value; use solidcraft_doc::render_settings::{RenderSettings, RenderSetup}; use crate::params::bad; -use crate::schema::render_lights::{EditParams, EditResult, Geometry, Light}; +use crate::schema::render_lights::{EditParams, EditResult, Geometry, Light, LightIdRemap}; use crate::schema::render_lights::{ListParams, ListResult}; use crate::{Result, Session}; @@ -35,6 +35,33 @@ pub(super) fn list(s: &mut Session, params: &Value) -> Result { serde_json::to_value(ListResult { lights: crate::render_lights::inspect(&setup).map_err(|e| bad(cmd, e))? }).map_err(|e| bad(cmd, e.to_string())) } +fn canonical_id(setup: &RenderSetup, lights: &[Light], index: usize) -> Option { + lights.get(index).map(|light| { + let kind = light.geometry.kind(); + let finite_directional = matches!( + setup.job, + Some(solidcraft_doc::render_settings::RenderJob::GpuPath { .. } | solidcraft_doc::render_settings::RenderJob::CpuRaytrace { .. }) + ) && kind == "directional"; + let slot = if finite_directional { + if matches!(light.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. }) { + 0 + } else { + usize::from(lights.iter().any(|l| matches!(l.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. }))) + + lights.iter().take(index).filter(|l| matches!(l.geometry, Geometry::Directional { angular_radius_rad: None, .. })).count() + } + } else { + lights + .iter() + .take(index) + .filter(|prior| { + if matches!(kind, "point" | "spot") { matches!(prior.geometry.kind(), "point" | "spot") } else { prior.geometry.kind() == kind } + }) + .count() + }; + format!("{kind}:{slot}") + }) +} + fn change(s: &mut Session, params: &Value, operation: &str) -> Result { let command = format!("render.lights.{operation}"); if !params.is_object() { @@ -51,6 +78,7 @@ fn change(s: &mut Session, params: &Value, operation: &str) -> Result { None => s.doc.render.setups.get(&input.name).cloned().unwrap_or_default(), }; let mut lights = crate::render_lights::inspect(&setup).map_err(|e| bad(&command, e))?; + let original_lights = lights.clone(); let target = [setup.camera.target.x, setup.camera.target.y, setup.camera.target.z]; let mut selected = None; match operation { @@ -90,13 +118,15 @@ fn change(s: &mut Session, params: &Value, operation: &str) -> Result { if input.set.is_some() { return Err(bad(&command, "duplicate does not accept set")); } - let light = lights.get(index).cloned().ok_or_else(|| bad(&command, "missing light"))?; + let mut light = lights.get(index).cloned().ok_or_else(|| bad(&command, "missing light"))?; + // A new source, even when every numerical value equals its parent. + light.id.clear(); lights.push(light); selected = lights.len().checked_sub(1); } else { let patch = input.set.ok_or_else(|| bad(&command, "set is required"))?; let light = lights.get_mut(index).ok_or_else(|| bad(&command, "missing light"))?; - if matches!(setup.job, Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { .. })) + if matches!(&setup.job, Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options, .. }) if options.path.is_none()) && light.geometry.kind() == "directional" && patch.softness.is_some() { @@ -108,19 +138,17 @@ fn change(s: &mut Session, params: &Value, operation: &str) -> Result { } _ => return Err(bad(&command, "unknown light operation")), } - let id = selected.and_then(|index| { - lights.get(index).map(|light| { - let kind = light.geometry.kind(); - let slot = lights + let id = selected.and_then(|index| canonical_id(&setup, &lights, index)); + let id_remap = lights + .iter() + .enumerate() + .filter_map(|(index, light)| { + original_lights .iter() - .take(index) - .filter(|prior| { - if matches!(kind, "point" | "spot") { matches!(prior.geometry.kind(), "point" | "spot") } else { prior.geometry.kind() == kind } - }) - .count(); - format!("{kind}:{slot}") + .find(|before| !light.id.is_empty() && before.id == light.id) + .and_then(|before| canonical_id(&setup, &lights, index).map(|after_id| LightIdRemap { before: before.clone(), after_id })) }) - }); + .collect(); crate::render_lights::write(&mut setup, &lights).map_err(|e| bad(&command, e))?; let mut settings = (*s.doc.render).clone(); settings.setups.insert(input.name.clone(), setup.clone()); @@ -128,7 +156,7 @@ fn change(s: &mut Session, params: &Value, operation: &str) -> Result { if *s.doc.render != settings { s.doc_mut().render = std::sync::Arc::new(settings); } - serde_json::to_value(EditResult { id, name: input.name, setup: serde_json::to_value(setup).map_err(|e| bad(&command, e.to_string()))? }) + serde_json::to_value(EditResult { id, id_remap, name: input.name, setup: serde_json::to_value(setup).map_err(|e| bad(&command, e.to_string()))? }) .map_err(|e| bad(&command, e.to_string())) } diff --git a/crates/engine/src/cmd/render/optical_bindings.rs b/crates/engine/src/cmd/render/optical_bindings.rs index 3908e68ad..7353f3660 100644 --- a/crates/engine/src/cmd/render/optical_bindings.rs +++ b/crates/engine/src/cmd/render/optical_bindings.rs @@ -11,7 +11,13 @@ use solidcraft_doc::{ use solidcraft_render::ProductScene; use std::{collections::BTreeMap, sync::Arc}; -pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &OpticalBindings, command: &str) -> Result> { +fn resolve_each( + s: &Session, + scene: &ProductScene, + bindings: &OpticalBindings, + command: &str, + convert: impl Fn(usize, &str, OpticalMaterial) -> Result, +) -> Result> { bindings.validate().map_err(|e| bad(command, e.to_string()))?; let identities = super::surface_bindings::targets(s, command)?; let visible: BTreeMap<_, _> = scene.meshes.iter().enumerate().map(|(i, b)| (b.name.as_str(), i)).collect(); @@ -20,13 +26,42 @@ pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &OpticalBindi for binding in bindings.iter() { let name = identities.get(&binding.target).ok_or_else(|| bad(command, "saved optical target changed; explicit rebinding required"))?; let index = visible.get(name.as_str()).ok_or_else(|| bad(command, "saved optical target is hidden or absent"))?; - let mut value = serde_json::to_value(binding.optics).map_err(|e| bad(command, e.to_string()))?; - value["body_index"] = json!(index); - value["body_name"] = json!(name); - result.push(serde_json::from_value(value).map_err(|e| bad(command, e.to_string()))?); + result.push(convert(*index, name, binding.optics)?); } Ok(result) } + +pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &OpticalBindings, command: &str) -> Result> { + resolve_each(s, scene, bindings, command, |index, name, optics| { + let mut value = serde_json::to_value(optics).map_err(|e| bad(command, e.to_string()))?; + value["body_index"] = json!(index); + value["body_name"] = json!(name); + serde_json::from_value(value).map_err(|e| bad(command, e.to_string())) + }) +} + +#[cfg(test)] +pub(super) fn resolve_cpu( + s: &Session, + scene: &ProductScene, + bindings: &OpticalBindings, + command: &str, +) -> Result> { + resolve_cpu_path(s, scene, bindings, false, command) +} +pub(super) fn resolve_cpu_path( + s: &Session, + scene: &ProductScene, + bindings: &OpticalBindings, + path: bool, + command: &str, +) -> Result> { + bindings.validate_for_cpu_path(path).map_err(|e| bad(command, e.to_string()))?; + resolve_each(s, scene, bindings, command, |index, name, optics| { + optics.to_cpu_for_path(index, name, path).map_err(|e| bad(command, e.to_string())) + }) +} + fn empty() -> Value { json!({}) } @@ -54,8 +89,8 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result { if s.doc.render.setups.get(&input.name).is_some_and(|old| old.optics != setup.optics) { return Err(bad(command, "setup patch cannot erase or replace saved optics; use explicit bind/unbind")); } - if !matches!(setup.job, Some(RenderJob::GpuPath { .. })) { - return Err(bad(command, "portable optics require an explicit GPU setup")); + if !matches!(setup.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) { + return Err(bad(command, "portable optics require an explicit CPU or GPU raytrace setup")); } let mut scene = crate::product_scene::extract(s)?; let name = &scene @@ -72,8 +107,15 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result { } setup.optics.set(SavedOptics { target, optics: input.optics }, input.replace).map_err(|e| bad(command, e.to_string()))?; setup.validate().map_err(|e| bad(command, e.to_string()))?; - let resolved = resolve(s, &scene, &setup.optics, command)?; - super::transmission::apply(&mut scene, &resolved, command)?; + if matches!(setup.job, Some(RenderJob::CpuRaytrace { .. })) { + // Offline saving resolves identity and numerical compatibility. The selected + // CPU image producer still certifies actual geometry before any transport. + let path = matches!(&setup.job,Some(RenderJob::CpuRaytrace{options,..}) if options.path.is_some()); + resolve_cpu_path(s, &scene, &setup.optics, path, command)?; + } else { + let resolved = resolve(s, &scene, &setup.optics, command)?; + super::transmission::apply(&mut scene, &resolved, command)?; + } let mut settings = (*s.doc.render).clone(); settings.setups.insert(input.name.clone(), setup.clone()); settings.validate().map_err(|e| bad(command, e.to_string()))?; @@ -146,4 +188,49 @@ mod tests { s.execute("render.optics.unbind", &json!({"name":"Studio","target":target,"expected_revision":s.revision})).unwrap(); assert!(s.doc.render.setups["Studio"].optics.is_empty()); } + + #[test] + fn cpu_saved_optics_are_offline_undoable_and_keep_stable_identity_and_mass() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + s.execute("material.assign", &json!({"bodies":["Optics"],"material":"Steel"})).unwrap(); + s.execute("render.settings.set",&json!({"name":"CPU glass","set":{"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81}}}}})).unwrap(); + assert!(s.render_job_host().is_none()); + let physical = s.execute("component.properties", &json!({"component":"root"})).unwrap(); + assert!(physical["total"]["mass_g"].as_f64().unwrap() > 0.0); + let before = s.doc.clone(); + let undo = s.undo.len(); + let evaluations = s.evaluations; + s.execute( + "render.optics.bind", + &json!({"name":"CPU glass","body_index":0,"body_name":"Optics","expected_revision":s.revision, + "optics":{"ior":1.51,"absorption_per_mm":[0.1,0.02,0.0],"boundary":"closed_mesh"}}), + ) + .unwrap(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.evaluations, evaluations); + assert_eq!(s.doc.features, before.features); + assert_eq!(s.doc.materials, before.materials); + assert_eq!(s.execute("component.properties", &json!({"component":"root"})).unwrap(), physical); + let saved = s.doc.clone(); + let scene = crate::product_scene::extract(&s).unwrap(); + let cpu = resolve_cpu(&s, &scene, &s.doc.render.setups["CPU glass"].optics, "check").unwrap(); + assert_eq!(cpu[0].body_name, "Optics"); + assert_eq!(cpu[0].ior, 1.51); + assert_eq!(cpu[0].boundary, solidcraft_render::job::DielectricBoundary::ClosedBox); + assert_eq!( + s.doc.render.setups["CPU glass"].optics.iter().next().unwrap().optics.boundary, + solidcraft_doc::render_optics::OpticalBoundary::ClosedMesh + ); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.render, s.doc.render); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc, *before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(*s.doc, *saved); + s.execute("browser.visibility", &json!({"items":["Optics"],"visible":false})).unwrap(); + let hidden = crate::product_scene::extract(&s).unwrap(); + assert!(resolve_cpu(&s, &hidden, &s.doc.render.setups["CPU glass"].optics, "check").unwrap_err().to_string().contains("hidden or absent")); + s.execute("edit.undo", &json!({})).unwrap(); + } } diff --git a/crates/engine/src/cmd/render/resources.rs b/crates/engine/src/cmd/render/resources.rs index c579a53b3..55f92fe37 100644 --- a/crates/engine/src/cmd/render/resources.rs +++ b/crates/engine/src/cmd/render/resources.rs @@ -51,9 +51,12 @@ pub(super) fn capture_settings(s: &mut Session, params: &Value) -> Result let mut setup = super::patched_settings(s, &input.name, &input.set, command)?; // Every numerical and method-dependent rejection happens before touching the source. match &setup.job { - Some(RenderJob::CpuRaytrace { options }) => { - if options.hdr.is_some() || options.environment.is_some() || params.get("assume_linear_srgb").is_some() { - return Err(bad(command, "CPU HDR capture requires hdr/environment unset and declared primaries; assume_linear_srgb is GPU-only")); + Some(RenderJob::CpuRaytrace { options, .. }) => { + if options.hdr.is_some() || options.environment.is_some() || options.sky.is_some() || params.get("assume_linear_srgb").is_some() { + return Err(bad( + command, + "CPU HDR capture requires hdr/environment/sky unset and declared primaries; assume_linear_srgb is GPU-only", + )); } CpuHdrEnvironment::check_controls(input.rotation_rad, input.intensity, input.samples.unwrap_or(16)) .map_err(|e| bad(command, e.to_string()))?; @@ -73,7 +76,7 @@ pub(super) fn capture_settings(s: &mut Session, params: &Value) -> Result let info = metadata(&resource); let id = settings.resources.insert(resource).map_err(|e| bad(command, e.to_string()))?; match &mut setup.job { - Some(RenderJob::CpuRaytrace { options }) => { + Some(RenderJob::CpuRaytrace { options, .. }) => { options.hdr = Some(CpuHdrEnvironment { resource: id, rotation_rad: input.rotation_rad, diff --git a/crates/engine/src/cmd/render/settings_tests.rs b/crates/engine/src/cmd/render/settings_tests.rs index de1a59acc..2c84e8d5c 100644 --- a/crates/engine/src/cmd/render/settings_tests.rs +++ b/crates/engine/src/cmd/render/settings_tests.rs @@ -6,6 +6,64 @@ fn save(s: &mut Session, patch: Value) { s.execute("render.settings.set", &json!({"name":"Studio", "set":patch})).unwrap(); } +#[test] +fn complete_shot_patch_accepts_all_known_fields_and_refuses_unknowns_without_mutation() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); + save(&mut s, json!({"width":8,"height":8})); + let before = s.doc.clone(); + let model = s.model.state(); + let camera = s.camera; + let evaluations = s.evaluations; + let undo = s.undo.len(); + let mut complete = json!(RenderSetup::default()); + complete["width"] = json!(16); + complete["height"] = json!(12); + complete["camera"] = json!(solidcraft_render::Camera { distance: 80.0, fov: 0.6, ..Default::default() }); + complete["job"] = json!({"method":"cpu_raytrace","options":{"path":{"max_depth":4}, + "progressive":{"samples_per_pixel":4,"seed":17},"lens":{"aperture_radius_mm":0.02,"focus_distance_mm":80.0}, + "output":{"linear_exr":true}}}); + for field in ["surfaces", "optics", "coats", "stage"] { + complete[field] = json!([]); + } + assert_eq!(complete.as_object().unwrap().len(), 15); + let expected: RenderSetup = serde_json::from_value(complete.clone()).unwrap(); + expected.validate().unwrap(); + let input = json!({"name":"Studio","set":complete}); + let original = input.clone(); + s.execute("render.settings.set", &input).unwrap(); + assert_eq!(s.doc.render.setups["Studio"], expected); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.evaluations, evaluations); + assert_eq!(s.camera, camera); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(s.doc.features, before.features); + assert_eq!(s.doc.materials, before.materials); + assert_eq!(input, original); + let saved = s.doc.clone(); + s.execute("render.settings.set", &input).unwrap(); + assert!(Arc::ptr_eq(&saved, &s.doc)); + assert_eq!(s.undo.len(), undo + 1); + for set in [json!({"unknown":true}), { + let mut over_schema = complete; + over_schema["unknown"] = json!(true); + over_schema + }] { + let history = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + assert!(s.execute("render.settings.set", &json!({"name":"Studio","set":set})).is_err()); + assert!(Arc::ptr_eq(&saved, &s.doc)); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(history, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); + assert_eq!(s.camera, camera); + } + assert_eq!(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(), *s.doc); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc, saved); + assert_eq!(s.camera, camera); +} + #[test] fn environment_editor_rotation_wraps_and_each_edit_is_one_undo() { let mut s = Session::default(); @@ -280,11 +338,14 @@ fn render_lights_edit_refusals_are_atomic_for_hostile_numbers_ids_stale_reviews_ assert_eq!(before, (s.undo.len(), s.revision)); } light_fixture(&mut s, "gpu_path"); - s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"directional"}})).unwrap(); + s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"directional","softness":0.5}})).unwrap(); let document = s.doc.clone(); for command in ["render.lights.add", "render.lights.duplicate"] { - let params = - if command.ends_with("add") { json!({"name":"Studio","set":{"kind":"point"}}) } else { json!({"name":"Studio","id":"directional:0"}) }; + let params = if command.ends_with("add") { + json!({"name":"Studio","set":{"kind":"directional","softness":0.5}}) + } else { + json!({"name":"Studio","id":"directional:0"}) + }; assert!(s.execute(command, ¶ms).is_err()); assert!(Arc::ptr_eq(&document, &s.doc)); } @@ -709,7 +770,7 @@ fn portable_job_save_is_host_independent_atomic_and_undoable_without_geometry_ch save(&mut s, json!({"job":{"method":"cpu_raytrace"}})); assert_eq!( s.doc.render.setups["Studio"].job, - Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { options: solidcraft_doc::render_settings::CpuJob::default() }) + Some(solidcraft_doc::render_settings::RenderJob::CpuRaytrace { transparent_background: false, options: Box::default() }) ); assert_eq!(s.doc.render.setups["Studio"].exposure_ev, 2.5); assert!(Arc::ptr_eq(&model, &s.model.state())); @@ -967,12 +1028,219 @@ fn render_lights_removing_last_area_clears_area_only_sampling_settings() { light_fixture(&mut s, "cpu_raytrace"); s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"area"}})).unwrap(); let mut setup = s.doc.render.setups["Studio"].clone(); - if let Some(RenderJob::CpuRaytrace { options }) = &mut setup.job { + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job { options.area_samples = Some(64); options.seed = Some(123); } s.execute("render.lights.remove", &json!({"name":"Studio","id":"area:0","settings":setup})).unwrap(); - let Some(RenderJob::CpuRaytrace { options }) = &s.doc.render.setups["Studio"].job else { panic!("CPU") }; + let Some(RenderJob::CpuRaytrace { options, .. }) = &s.doc.render.setups["Studio"].job else { panic!("CPU") }; assert!(options.area_samples.is_none() && options.seed.is_none()); assert!(options.area_lights.as_ref().unwrap().is_empty()); } + +#[test] +fn gpu_hard_directional_commands_materialize_defaults_and_keep_sun_distinct() { + use crate::schema::render_lights::{Geometry, Visibility}; + let mut s = Session::default(); + save(&mut s, json!({"job":{"method":"gpu_path","options":{}}})); + let implicit = crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap(); + assert_eq!(implicit.len(), 3); + let before = s.doc.clone(); + let duplicate = s.execute("render.lights.duplicate", &json!({"name":"Studio","id":"directional:1"})).unwrap(); + assert_eq!(duplicate["id"], "directional:3"); + let actual = crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap(); + assert_eq!(actual.len(), 4); + for (a, b) in actual.iter().take(3).zip(&implicit) { + assert_eq!((a.intensity, a.colour), (b.intensity, b.colour)); + let (Geometry::Directional { direction: a, angular_radius_rad: None }, Geometry::Directional { direction: b, angular_radius_rad: None }) = + (a.geometry, b.geometry) + else { + panic!("hard directions") + }; + assert_eq!(a, b); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + let sun = s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"directional","softness":0.25}})).unwrap(); + assert_eq!(sun["id"], "directional:0", "finite Sun is canonical first source"); + let original = s.doc.render.setups["Studio"].clone(); + let mut render_copy = original.clone(); + let visibility = Visibility { solo: Some("directional:3".into()), ..Default::default() }; + assert_eq!(crate::render_lights::filter(&mut render_copy, &visibility).unwrap(), None); + let filtered = crate::render_lights::inspect(&render_copy).unwrap(); + for (i, light) in filtered.iter().enumerate() { + assert_eq!(light.intensity > 0.0, i == 3); + } + assert_eq!(s.doc.render.setups["Studio"], original); + for _ in 5..8 { + s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"directional"}})).unwrap(); + } + let before = s.doc.clone(); + for (cmd, input) in [ + ("render.lights.add", json!({"name":"Studio","set":{"kind":"directional"}})), + ("render.lights.duplicate", json!({"name":"Studio","id":"directional:1"})), + ("render.lights.duplicate", json!({"name":"Studio","id":"directional:0"})), + ] { + assert!(s.execute(cmd, &input).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc)); + } + // Punctual sources have their own unchanged8-slot envelope. Filling the + // directional envelope does not make the new point-light family unavailable. + let point = s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"point"}})).unwrap(); + assert_eq!(point["id"], "point:0"); + let with_point = crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap(); + let original_rows = crate::render_lights::inspect(&before.render.setups["Studio"]).unwrap(); + assert_eq!(with_point.len(), 9); + assert_eq!(&with_point[..8], original_rows.as_slice()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before, "one Undo restores the complete original8-directional setup"); + s.execute("render.lights.remove", &json!({"name":"Studio","id":"directional:7"})).unwrap(); + assert_eq!(crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap().len(), 7); + assert_eq!(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(), *s.doc); +} + +#[test] +fn gpu_light_id_remap_uses_original_identity_even_when_values_are_identical() { + use crate::schema::render_lights::LightIdRemap; + let mut s = Session::default(); + let hard = json!({"direction":[0,0,1],"color":[0.25,0.5,1],"intensity":2}); + save(&mut s, json!({"job":{"method":"gpu_path","options":{"lighting":{"directional_lights":[hard.clone(),hard]}}}})); + let duplicated = s.execute("render.lights.duplicate", &json!({"name":"Studio","id":"directional:0"})).unwrap(); + let map: Vec = serde_json::from_value(duplicated["id_remap"].clone()).unwrap(); + assert_eq!(map.len(), 2); + assert_eq!(duplicated["id"], "directional:2"); + assert_eq!( + map.iter().map(|m| (m.before.id.as_str(), m.after_id.as_str())).collect::>(), + [("directional:0", "directional:0"), ("directional:1", "directional:1")] + ); + let added = s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"directional","softness":0.25}})).unwrap(); + let map: Vec = serde_json::from_value(added["id_remap"].clone()).unwrap(); + assert_eq!(map.len(), 3); + assert_eq!(added["id"], "directional:0"); + for (index, entry) in map.iter().enumerate() { + assert_eq!(entry.before.id, format!("directional:{index}")); + assert_eq!(entry.after_id, format!("directional:{}", index + 1)); + } + let removed = s.execute("render.lights.remove", &json!({"name":"Studio","id":"directional:0"})).unwrap(); + let map: Vec = serde_json::from_value(removed["id_remap"].clone()).unwrap(); + assert_eq!(map.len(), 3); + for (index, entry) in map.iter().enumerate() { + assert_eq!(entry.before.id, format!("directional:{}", index + 1)); + assert_eq!(entry.after_id, format!("directional:{index}")); + } + assert!(removed["id"].is_null()); +} + +#[test] +fn gpu_light_edits_preserve_untouched_original_sun_and_area_radiance_bits() { + let mut s = Session::default(); + let rgb = [0.7_f64, 1.0, 9.1]; + save( + &mut s, + json!({"job":{"method":"gpu_path","options":{"lighting":{ + "sun":{"direction":[1,2,3],"angular_radius_rad":0.02,"radiance":rgb}, + "area_lights":[{"center":[0,0,10],"u":[1,0,0],"v":[0,-1,0],"radiance":rgb}], + "directional_lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":1}] + }}}}), + ); + let lighting = |s: &Session| { + let Some(RenderJob::GpuPath { options, .. }) = &s.doc.render.setups["Studio"].job else { panic!("gpu") }; + options.lighting.unwrap() + }; + let original = lighting(&s); + let bits = |a: [f64; 3]| a.map(f64::to_bits); + for (command, params) in [ + ("render.lights.add", json!({"name":"Studio","set":{"kind":"directional"}})), + ("render.lights.set", json!({"name":"Studio","id":"directional:1","set":{"direction":[2,3,4]}})), + ("render.lights.remove", json!({"name":"Studio","id":"directional:2"})), + ] { + s.execute(command, ¶ms).unwrap(); + let actual = lighting(&s); + assert_eq!(bits(actual.sun.unwrap().radiance), bits(original.sun.unwrap().radiance)); + assert_eq!(bits(actual.area_lights.iter().next().unwrap().radiance), bits(rgb)); + } + s.execute("render.lights.remove", &json!({"name":"Studio","id":"directional:0"})).unwrap(); + assert!(lighting(&s).sun.is_none()); + assert_eq!(bits(lighting(&s).area_lights.iter().next().unwrap().radiance), bits(rgb)); + s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"directional","softness":0.5}})).unwrap(); + assert_eq!(bits(lighting(&s).area_lights.iter().next().unwrap().radiance), bits(rgb)); +} + +#[test] +fn gpu_point_spot_commands_keep_cones_ranges_undo_visibility_identity_and_portable_reload() { + use crate::schema::render_lights::{Geometry, Visibility}; + let mut s = Session::default(); + save(&mut s, json!({"job":{"method":"gpu_path","options":{}}})); + let implicit = crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap(); + let add=s.execute("render.lights.add",&json!({"name":"Studio","set":{"kind":"spot","position_mm":[4,5,6],"emitted_axis":[-4,-5,-6],"inner_half_angle_radians":0.2,"outer_half_angle_radians":0.7,"reference_distance_mm":7.25,"minimum_distance_mm":0.002}})).unwrap(); + assert_eq!(add["id"], "spot:0"); + let authored = s.doc.clone(); + let all = crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap(); + for (a, b) in all.iter().take(3).zip(&implicit) { + assert_eq!((a.geometry, a.intensity, a.colour), (b.geometry, b.intensity, b.colour)); + assert!(!a.implicit); + } + let Geometry::Spot { position_mm, emitted_axis, inner_half_angle_radians, outer_half_angle_radians, reference_distance_mm, minimum_distance_mm } = + all[3].geometry + else { + panic!("spot") + }; + assert_eq!((position_mm, emitted_axis), ([4.0, 5.0, 6.0], [-4.0, -5.0, -6.0])); + assert_eq!((inner_half_angle_radians, outer_half_angle_radians, reference_distance_mm, minimum_distance_mm), (0.2, 0.7, 7.25, 0.002)); + let undo = s.undo.len(); + let point = s.execute("render.lights.set", &json!({"name":"Studio","id":"spot:0","set":{"kind":"point"}})).unwrap(); + assert_eq!(point["id"], "point:0"); + assert_eq!(s.undo.len(), undo + 1); + let rows = crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap(); + assert_eq!(rows[3].geometry, Geometry::Point { position_mm, reference_distance_mm, minimum_distance_mm }); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, authored); + let dup = s.execute("render.lights.duplicate", &json!({"name":"Studio","id":"spot:0"})).unwrap(); + assert_eq!(dup["id"], "spot:1"); + assert!(dup["id_remap"].as_array().unwrap().iter().any(|m| m["before"]["id"] == "spot:0" && m["after_id"] == "spot:0")); + let before = s.doc.clone(); + let mut filtered = s.doc.render.setups["Studio"].clone(); + crate::render_lights::filter(&mut filtered, &Visibility { solo: Some("spot:1".into()), ..Default::default() }).unwrap(); + let rows = crate::render_lights::inspect(&filtered).unwrap(); + assert!(rows.iter().all(|l| (l.intensity > 0.0) == (l.id == "spot:1"))); + assert_eq!(s.doc, before); + for _ in 2..8 { + s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"point"}})).unwrap(); + } + let before = s.doc.clone(); + let undo = s.undo.len(); + for command in ["render.lights.add", "render.lights.duplicate"] { + let params = if command.ends_with("add") { json!({"name":"Studio","set":{"kind":"spot"}}) } else { json!({"name":"Studio","id":"spot:0"}) }; + assert!(s.execute(command, ¶ms).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(s.undo.len(), undo); + } + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened, *s.doc); + assert_eq!( + crate::render_lights::inspect(&reopened.render.setups["Studio"]).unwrap(), + crate::render_lights::inspect(&s.doc.render.setups["Studio"]).unwrap() + ); +} +#[test] +fn gpu_spot_cone_hostile_edits_refuse_atomically_without_widening_or_ignoring_intent() { + let mut s = Session::default(); + light_fixture(&mut s, "gpu_path"); + s.execute("render.lights.add", &json!({"name":"Studio","set":{"kind":"spot"}})).unwrap(); + for set in [ + json!({"inner_half_angle_radians":0.5,"outer_half_angle_radians":0.5}), + json!({"inner_half_angle_radians":0.2,"outer_half_angle_radians":0.2000000001}), + json!({"emitted_axis":[0,0,0]}), + json!({"outer_half_angle_radians":2}), + json!({"emitted_axis":[0,0,-1],"aim_at":[1,2,3]}), + ] { + let doc = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + assert!(s.execute("render.lights.set", &json!({"name":"Studio","id":"spot:0","set":set})).is_err()); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); + } + s.execute("render.lights.set", &json!({"name":"Studio","id":"spot:0","set":{"kind":"point"}})).unwrap(); + assert!(s.execute("render.lights.set", &json!({"name":"Studio","id":"point:0","set":{"inner_half_angle_radians":0.1}})).is_err()); +} diff --git a/crates/engine/src/cmd/render/studio_presets.rs b/crates/engine/src/cmd/render/studio_presets.rs index 1995f94e3..8b9a135de 100644 --- a/crates/engine/src/cmd/render/studio_presets.rs +++ b/crates/engine/src/cmd/render/studio_presets.rs @@ -1,11 +1,14 @@ //! Original native studio compositions. Independent of unbound SCENE-* concepts. //! Resolution is read-only; publication validates a complete candidate before one undo. use crate::schema::TypedContract; -use crate::schema::render_presets::{PresetParams, QualityOptions, QualityParams, QualityPlan, QualitySize, StudioComposition}; +use crate::schema::render_presets::{ + CpuProgressive, CpuQualityContext, CpuQualityOptions, CpuQualityPlan, PresetParams, QualityOptions, QualityParams, QualityPlan, QualityResult, + QualitySize, StudioComposition, +}; use crate::{Result, Session, params::bad}; use serde_json::{Value, json}; use solidcraft_doc::{ - render_resources::GpuHdrEnvironment, + render_resources::{CpuHdrEnvironment, GpuHdrEnvironment}, render_settings::{RenderJob, RenderSettings}, }; use solidcraft_render::{ @@ -64,8 +67,8 @@ fn candidate(s: &Session, input: &PresetParams, command: &str) -> Result Result Result { + let hdr_samples = options.hdr.map_or(16, |hdr| hdr.samples); + super::library::cpu_studio_lighting(options, &lighting, command)?; + options.hdr = Some(CpuHdrEnvironment { + resource: resource_id, + rotation_rad: super::library::hdr_rotation(0.35, command)?, + intensity: source["intensity"].as_f64().ok_or_else(|| bad(command, "native composition intensity missing"))?, + samples: hdr_samples, + }); + "cpu-raytrace" + } + Some(RenderJob::GpuPath { options, .. }) => { + options.environment = None; + options.hdr = Some(GpuHdrEnvironment { + resource: resource_id, + rotation_rad: super::library::hdr_rotation(0.35, command)?, + intensity: source["intensity"].as_f64().ok_or_else(|| bad(command, "native composition intensity missing"))?, + assume_linear_srgb: false, + }); + options.lighting = Some(lighting); + "gpu-path" + } + _ => return Err(bad(command, "choose CPU or GPU ray tracing")), + }; setup.validate().map_err(|e| bad(command, e.to_string()))?; super::staging::apply(&mut product, &setup, command)?; super::library::rig_clearance(&product, &lighting, command)?; @@ -148,7 +172,7 @@ fn candidate(s: &Session, input: &PresetParams, command: &str) -> Result Result { pub(super) fn quality(s: &mut Session, params: &Value) -> Result { let command = "render.quality.prepare"; let input: QualityParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; - if input.variant != "fixed_samples_png" || !input.acknowledge_omissions { + if !matches!(input.variant.as_str(), "fixed_samples_png" | "cpu_progressive_png") || !input.acknowledge_omissions { return Err(bad( command, - "explicit fixed_samples_png projection and omission acknowledgement are required; full Q-* requirements remain unbound", + "an explicit fixed_samples_png or cpu_progressive_png projection and omission acknowledgement are required; full Q-* requirements remain unbound", )); } + if input.variant == "fixed_samples_png" && input.cpu.is_some() { + return Err(bad(command, "CPU budget context requires the cpu_progressive_png projection")); + } let source = super::library::item("quality", &input.id, command)?; let number = |path: &[&str]| -> Result { let mut field = source; @@ -220,6 +247,81 @@ pub(super) fn quality(s: &mut Session, params: &Value) -> Result { field.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(command, "quality field is not a bounded unsigned integer")) }; let (width, height) = (number(&["resolution", "width"])?, number(&["resolution", "height"])?); + if input.variant == "cpu_progressive_png" { + if !matches!(input.id.as_str(), "Q-001" | "Q-002" | "Q-003") || source["motion"]["enabled"] != false { + return Err(bad( + command, + "only the three canonical still-image CPU cost budgets are bound; optical/convergence concepts are not CPU presets", + )); + } + let samples = number(&["sampling", "minimum_samples"])?.max(16); + let seed = number(&["seed"])?; + let context = input.cpu.unwrap_or_default(); + let production = Some(solidcraft_render::job::CpuProgressiveOptions { samples_per_pixel: samples, seed }); + let mut eligible = false; + let mut selected = None; + let mut refusal = None; + for budget in solidcraft_render::job::CpuBudget::ALL { + eligible |= budget == context.minimum_budget; + if !eligible { + continue; + } + let admitted = solidcraft_render::job::cpu_camera_sampling(production, context.adaptive, budget) + .and_then(|sampling| budget.validate_image(width, height, sampling)); + match admitted { + Ok(()) => { + selected = Some(budget); + break; + } + Err(error) => refusal = Some(error), + } + } + let budget = selected + .ok_or_else(|| bad(command, refusal.map_or_else(|| "no existing CPU profile admits this budget".to_string(), |e| e.to_string())))?; + let plan = CpuQualityPlan { + id: input.id, + name: source["name"].as_str().map(str::to_owned), + variant: input.variant, + status: "cpu_cost_budget_projection_not_full_quality_profile".into(), + revision: s.revision, + document_changed: false, + source_unchanged: true, + settings: QualitySize { width, height }, + cpu_options: CpuQualityOptions { progressive: CpuProgressive { samples_per_pixel: samples, seed }, budget }, + cpu_context: CpuQualityContext { minimum_budget: context.minimum_budget, adaptive: context.adaptive }, + requires_progressive: true, + changed_fields: strings(&["width", "height", "progressive.samples_per_pixel", "progressive.seed", "budget"]), + preserves: strings(&[ + "executor", + "camera", + "lens", + "lighting", + "environment", + "stage", + "optical_bindings", + "surface_maps", + "aging", + "exposure", + "tone_map", + "finishing", + "raw_master", + "denoise", + "path", + "adaptive", + ]), + omitted: strings(&[ + "catalog_maximum_samples", + "catalog_transport_depth", + "catalog_denoise_choice", + "adaptive_stopping_and_error_target", + "convergence_certification", + "time_guarantee", + ]), + source: source.as_object().cloned().unwrap_or_default(), + param_warnings: Vec::new(), + }; + return reply(command, QualityResult::Cpu(plan)); + } let (samples, depth) = (number(&["sampling", "maximum_samples"])?, number(&["transport", "maximum_depth"])?); let seed = number(&["seed"])?; if solidcraft_render::job::GPU_PATH_LIMITS.fit(u64::from(width), u64::from(height), None) != Some((u64::from(width), u64::from(height))) @@ -256,7 +358,7 @@ pub(super) fn quality(s: &mut Session, params: &Value) -> Result { source: source.as_object().cloned().unwrap_or_default(), param_warnings: Vec::new(), }; - reply(command, plan) + reply(command, QualityResult::Gpu(plan)) } #[cfg(test)] diff --git a/crates/engine/src/cmd/render/studio_presets_tests.rs b/crates/engine/src/cmd/render/studio_presets_tests.rs index 7cb224f5a..b397d5285 100644 --- a/crates/engine/src/cmd/render/studio_presets_tests.rs +++ b/crates/engine/src/cmd/render/studio_presets_tests.rs @@ -210,3 +210,261 @@ fn finishing_and_linear_master_saved_intent_survive_reopen_without_host_and_reje s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc.to_json(), before); } + +#[test] +fn cpu_quality_projects_exact_catalog_costs_with_existing_admissible_profiles_without_mutation() { + use solidcraft_render::job::{CpuBudget, CpuProgressiveOptions}; + let mut s = subject(); + let before = s.doc.clone(); + let history = (s.revision, s.undo.len(), s.redo.len()); + for (id, width, height, samples, profile) in + [("Q-001", 960, 540, 16, CpuBudget::Compact), ("Q-002", 1600, 900, 32, CpuBudget::Studio), ("Q-003", 2560, 1440, 64, CpuBudget::Studio)] + { + let plan = s.execute("render.quality.prepare", &json!({"id":id,"variant":"cpu_progressive_png","acknowledge_omissions":true})).unwrap(); + assert_eq!(plan["settings"], json!({"width":width,"height":height})); + assert_eq!(plan["cpu_options"], json!({"budget":profile,"progressive":{"samples_per_pixel":samples,"seed":21026}})); + assert_eq!(plan["changed_fields"], json!(["width", "height", "progressive.samples_per_pixel", "progressive.seed", "budget"])); + assert!(plan.get("gpu_options").is_none()); + assert!(plan["cpu_options"].get("path").is_none()); + assert!(plan["cpu_options"].get("denoise").is_none()); + assert_eq!(plan["status"], "cpu_cost_budget_projection_not_full_quality_profile"); + assert_eq!(plan["document_changed"], false); + let pixels = u64::from(width) * u64::from(height); + assert!(pixels * u64::from(samples) <= profile.limits().max_camera_samples); + profile.validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 21026 })).unwrap(); + for larger in [CpuBudget::Studio, CpuBudget::Workstation] { + let kept = s + .execute( + "render.quality.prepare", + &json!({"id":id,"variant":"cpu_progressive_png","acknowledge_omissions":true,"cpu":{"minimum_budget":larger}}), + ) + .unwrap(); + assert_eq!(kept["cpu_options"]["budget"], json!(larger), "an explicitly chosen larger profile must not be lowered"); + } + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, (s.revision, s.undo.len(), s.redo.len())); + } + let pilot = s + .execute( + "render.quality.prepare", + &json!({"id":"Q-001","variant":"cpu_progressive_png","acknowledge_omissions":true, + "cpu":{"adaptive":{"pilot_samples":256,"min_samples":16}}}), + ) + .unwrap(); + assert_eq!(pilot["cpu_options"]["budget"], "studio", "Draft must budget272total passes, not hide pilots outside Compact64"); + let first_pixels = 960_u64 * 540; + assert!(first_pixels * 272 < CpuBudget::Studio.limits().max_camera_samples); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, (s.revision, s.undo.len(), s.redo.len())); +} + +#[test] +fn cpu_quality_rejects_unbound_ids_hostile_context_and_incompatible_adaptive_without_silent_substitution() { + let mut s = subject(); + let doc = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len()); + for value in [ + json!({"id":"Q-004","variant":"cpu_progressive_png","acknowledge_omissions":true}), + json!({"id":"Q-999","variant":"cpu_progressive_png","acknowledge_omissions":true}), + json!({"id":"Q-001","variant":"cpu_progressive_png","acknowledge_omissions":false}), + json!({"id":"Q-001","variant":"cpu_progressive_png","acknowledge_omissions":true,"cpu":{"minimum_budget":"unlimited"}}), + json!({"id":"Q-001","variant":"cpu_progressive_png","acknowledge_omissions":true,"cpu":{"enable_gi":true}}), + json!({"id":"Q-001","variant":"fixed_samples_png","acknowledge_omissions":true,"cpu":{}}), + json!({"id":"Q-001","variant":"cpu_progressive_png","acknowledge_omissions":true,"cpu":{"adaptive":{"pilot_samples":16,"min_samples":32}}}), + json!({"id":"Q-003","variant":"cpu_progressive_png","acknowledge_omissions":true,"cpu":{"adaptive":{"pilot_samples":16,"min_samples":128}}}), + ] { + assert!(s.execute("render.quality.prepare", &value).is_err(), "{value}"); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len())); + } +} + +#[cfg(feature = "bundled-render-library")] +#[test] +fn cpu_native_studios_preserve_full_job_and_exact_hdr_rig_authority_for_all_twenty_five() { + use solidcraft_doc::render_settings::CpuJob; + use solidcraft_render::job::{CpuBudget, CpuPathOptions, CpuProgressiveOptions, ThinLens, adaptive::AdaptiveSampling}; + for entry in entries().as_array().unwrap() { + let id = entry["id"].as_str().unwrap(); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + let camera = solidcraft_render::Camera { fov: 0.5, ..Default::default() }; + let options = CpuJob { + budget: CpuBudget::Studio, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 947 }), + adaptive: Some(AdaptiveSampling::default()), + path: Some(CpuPathOptions { max_depth: 5 }), + denoise: true, + lens: Some(ThinLens { aperture_radius_mm: 0.2, focus_distance_mm: 100.0 }), + output: Some(Box::new(solidcraft_render::job::OutputOptions { linear_exr: true, ..Default::default() })), + area_samples: Some(64), + seed: Some(731), + volume: Some(solidcraft_render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }), + ..Default::default() + }; + s.execute("render.settings.set", &json!({"name":"Shot","set":{"width":96,"height":64,"camera":camera,"job":{"method":"cpu_raytrace","transparent_background":true,"options":options}}})).unwrap(); + s.execute("render.library.environment.apply", &json!({"id":"HDR-001","name":"Shot","samples":64})).unwrap(); + let before = s.doc.clone(); + let undo = s.undo.len(); + let revision = s.revision; + let old = s.doc.render.setups["Shot"].clone(); + let plan = s.execute("render.preset.resolve", &json!({"id":id,"name":"Shot","expected_revision":revision})).unwrap(); + assert!(Arc::ptr_eq(&s.doc, &before)); + assert_eq!(s.undo.len(), undo); + assert_eq!(plan["executor"], "cpu-raytrace"); + let applied = s + .execute("render.preset.apply", &json!({"id":id,"name":"Shot","expected_revision":revision,"replace_lighting_and_environment":true})) + .unwrap(); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(applied["setup"], plan["setup"]); + let saved = &s.doc.render.setups["Shot"]; + assert_eq!((saved.camera, saved.width, saved.height), (old.camera, old.width, old.height)); + assert_eq!((&saved.optics, &saved.coats, &saved.surfaces), (&old.optics, &old.coats, &old.surfaces)); + let Some(RenderJob::CpuRaytrace { options, transparent_background }) = &saved.job else { panic!("CPU method lost") }; + assert!(*transparent_background); + let Some(RenderJob::CpuRaytrace { options: old_options, .. }) = &old.job else { + panic!("the captured original setup must retain its CPU method") + }; + let mut expected = (**old_options).clone(); + expected.preset = None; + expected.lights = Some(vec![]); + expected.punctual_lights = Some(vec![]); + expected.environment = None; + expected.sky = None; + expected.sun = None; + expected.hdr = Some(CpuHdrEnvironment { + resource: serde_json::from_value(plan["resource_sha256"].clone()).unwrap(), + rotation_rad: 0.35 + std::f64::consts::PI, + intensity: entry["intensity"].as_f64().unwrap(), + samples: 64, + }); + expected.area_lights = Some(vec![]); + if entry["rig"] == "RIG-002" { + let bounds = crate::product_scene::extract(&s).unwrap().bounds; + let size = bounds.max - bounds.min; + let c = bounds.center(); + let (lighting, _) = super::super::library::rig_lighting( + &super::super::library::RigInput { + id: "RIG-002".into(), + variant: "complete".into(), + center_mm: [c.x, c.y, c.z], + subject_extent_mm: size.x.max(size.y).max(size.z), + }, + "test", + ) + .unwrap(); + expected.area_lights = Some( + lighting + .area_lights + .iter() + .map(|light| solidcraft_render::job::RectangleLightOptions { + center_mm: light.center, + edge_u_mm: light.u.map(|x| x * 2.0), + edge_v_mm: light.v.map(|x| x * 2.0), + color: [1.0; 3], + intensity: light.radiance[0] / 16.0, + }) + .collect(), + ); + assert_eq!(expected.area_lights.as_ref().unwrap().iter().map(|a| a.intensity).fold(0.0, f64::max), 29.691586369625); + } + assert_eq!(**options, expected, "all unrelated CPU intent survives {id}"); + let hdr = options.hdr.unwrap(); + assert_eq!( + s.doc.render.resources.required(&hdr.resource).unwrap().bytes(), + super::super::library_data::asset(entry["hdr"].as_str().unwrap()).unwrap().0 + ); + assert_eq!(s.doc.features, before.features); + assert_eq!(s.doc.materials, before.materials); + let saved_json = s.doc.to_json(); + let reopened = solidcraft_doc::Document::from_json(&saved_json).unwrap(); + assert_eq!(reopened.render.setups["Shot"], *saved); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc.to_json(), saved_json); + } +} + +#[cfg(all(feature = "bundled-render-library", feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn cpu_native_studio_cold_capture_matches_typed_source_every_prefix_and_raw_master() { + use solidcraft_render::job::{CancelToken, CpuHost, ImageRequest, Integrator, JobId, Phase}; + use solidcraft_render::lighting::environment_input::EnvironmentInput; + use solidcraft_render::raytrace::image::{ImagePoll, ImageTask}; + for id in ["NATIVE-STUDIO-001", "NATIVE-STUDIO-004", "RIG-020"] { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + let camera = solidcraft_render::Camera { target: solidcore_record::Vec3::new(10.0, 7.5, 5.0), distance: 35.0, ..Default::default() }; + s.execute("render.settings.set",&json!({"name":"Shot","set":{"width":8,"height":8,"camera":camera,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":47},"area_samples":1,"seed":731,"output":{"linear_exr":true}}}}})).unwrap(); + s.execute("render.library.environment.apply", &json!({"id":"HDR-001","name":"Shot","samples":1})).unwrap(); + if id == "RIG-020" { + s.execute("render.library.studio.apply", &json!({"name":"Shot","rig":{"id":id,"variant":"complete","center_mm":[10,7.5,5],"subject_extent_mm":20},"expected_revision":s.revision,"replace_lighting_and_environment":true,"enable_indirect":true})).unwrap(); + } else { + s.execute("render.preset.apply", &json!({"id":id,"name":"Shot","expected_revision":s.revision,"replace_lighting_and_environment":true})) + .unwrap(); + } + let bytes = solidcraft_io::write_design_container(&s.doc).unwrap(); + s = Session::new(solidcraft_io::read_design(&bytes).unwrap()); + s.execute("render.scene", &json!({})).unwrap(); + let setup = s.doc.render.setups["Shot"].clone(); + let Some(RenderJob::CpuRaytrace { options, transparent_background }) = &setup.job else { panic!() }; + let hdr = options.hdr; + if id == "RIG-020" { + assert!(hdr.is_none()); + assert!(options.sun.is_some()); + } else { + assert_eq!(hdr.unwrap().samples, 1); + } + let runtime = options.to_runtime(setup.exposure_ev).unwrap(); + let mut scene = crate::product_scene::extract(&s).unwrap(); + super::super::staging::apply(&mut scene, &setup, "test").unwrap(); + let render = |quantum| { + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(runtime.clone()), + camera: setup.camera, + width: setup.width, + height: setup.height, + background: setup.background, + transparent_background: *transparent_background, + studio_weights: None, + environment: None, + textures: None, + }; + let input = hdr.map(|hdr| { + EnvironmentInput::new(s.doc.render.resources.required(&hdr.resource).unwrap().source(), hdr.rotation_rad, hdr.intensity, hdr.samples) + .unwrap() + }); + let mut task = ImageTask::new_with_environment(scene.clone(), request, CancelToken::default(), runtime.clone(), input).unwrap(); + let mut prefixes = Vec::new(); + for _ in 0..2_000_000 { + match task.step_with_previews(quantum).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => prefixes.push((samples_per_pixel, png)), + ImagePoll::Complete(png) => return (prefixes, png, task.take_linear_exr().unwrap()), + } + } + panic!("bounded native studio source failed to finish") + }; + let expected = render(1); + assert_eq!(expected.0.iter().map(|(sample, _)| *sample).collect::>(), [1, 2]); + assert!(expected.0.iter().all(|(_, png)| png.starts_with(b"\x89PNG\r\n\x1a\n"))); + assert_eq!(expected, render(4096), "every complete prefix, final PNG and raw master is independent of work quantum"); + let host = CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host)).unwrap(); + let doc = s.doc.clone(); + let history = (s.revision, s.undo.len(), s.redo.len()); + s.execute("render.preflight", &json!({"settings":setup})).unwrap(); + let reply = s.execute("render.start", &json!({"settings":setup})).unwrap(); + let job: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = s.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.png(), expected.1.as_slice()); + assert_eq!(frame.linear_exr().unwrap(), expected.2.as_slice()); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), history); + } +} diff --git a/crates/engine/src/cmd/render/surface_bindings.rs b/crates/engine/src/cmd/render/surface_bindings.rs index 369372974..7a6a3cec4 100644 --- a/crates/engine/src/cmd/render/surface_bindings.rs +++ b/crates/engine/src/cmd/render/surface_bindings.rs @@ -166,6 +166,14 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result { if !matches!(setup.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) { return Err(bad(command, "persistent authored maps require an explicit CPU raytrace or GPU path setup")); } + if let Some(RenderJob::CpuRaytrace { options, .. }) = &setup.job { + if !setup.optics.is_empty() && options.path.is_none() { + return Err(bad(command, "CPU maps with Glass require Indirect lighting and separate targets")); + } + // Saving validates portable intent; capture later resolves stable aging + // targets. The final setup validator still forbids maps on a Glass target. + options.validate_surface_maps(setup.exposure_ev).map_err(|e| bad(command, e.to_string()))?; + } let prepared = super::library::prepare_surface(s, &input.surface)?; let id = prepared["id"].as_str().ok_or_else(|| bad(command, "missing prepared surface identifier"))?; let name = prepared["texture"]["body_name"].as_str().ok_or_else(|| bad(command, "missing prepared body identity"))?; diff --git a/crates/engine/src/cmd/render_ui.rs b/crates/engine/src/cmd/render_ui.rs index 261ee48d1..d6123ef05 100644 --- a/crates/engine/src/cmd/render_ui.rs +++ b/crates/engine/src/cmd/render_ui.rs @@ -154,7 +154,7 @@ fn divider(_: &mut Session, params: &Value) -> Result { Ok(json!({"position":input.position.clamp(0.05,0.95)})) } -fn batch(s: &mut Session, params: &Value) -> Result { +pub(crate) fn batch_request(s: &Session, params: &Value) -> Result { let input: BatchParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.batch", e.to_string()))?; s.render_batch_ready().map_err(|reason| bad("render.batch", reason))?; if s.model.is_stale() { @@ -187,7 +187,11 @@ fn batch(s: &mut Session, params: &Value) -> Result { return Err(bad("render.batch", "replace must be false or omitted")); } request.insert("settings".into(), json!(settings)); - let request = std::sync::Arc::new(Value::Object(request)); + Ok(Value::Object(request)) +} + +fn batch(s: &mut Session, params: &Value) -> Result { + let request = std::sync::Arc::new(batch_request(s, params)?); let shots = s .doc .render diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index c8b6d4356..2b62ebeed 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -6,8 +6,8 @@ use solidcraft_render::{Camera, StandardView}; use super::CommandSpec; use crate::params::{bad, num, req_vec2, req_vec3, vec3}; use crate::schema::view_navigation::{ - CameraReply, NavigatorParams, NormalToParams, RenderBrowser, RenderFocus, RenderSelect, RibbonTabsOnly, RibbonTabsOnlyParams, StandardViewParams, - TabStep, TabStepParams, ZoomTool, + CameraReply, NavigatorParams, NormalToParams, RenderBrowser, RenderFocus, RenderLive, RenderSelect, RibbonTabsOnly, RibbonTabsOnlyParams, + StandardViewParams, TabStep, TabStepParams, ZoomTool, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Sel, Session}; @@ -15,6 +15,7 @@ use crate::{Result, Sel, Session}; const ZOOM_TOOL_CONTRACT: TypedContract = TypedContract::new(); const FOCUS_CONTRACT: TypedContract = TypedContract::new(); const NAVIGATOR_CONTRACT: TypedContract = TypedContract::new(); +const RENDER_LIVE_CONTRACT: TypedContract = TypedContract::new(); const BROWSER_CONTRACT: TypedContract = TypedContract::new(); const TAB_STEP_CONTRACT: TypedContract = TypedContract::new(); const STANDARD_VIEW_CONTRACT: TypedContract = TypedContract::new(); @@ -95,6 +96,10 @@ CommandSpec::new("view.render_browser", "Render Browser", crate::checked!("view. CommandSpec::new("view.render_inspector", "Render Inspector", render_inspector) .icon("inspect").noundo().doc_only() .params("visible: bool → {visible}; per-document Inspector visibility; never edits the design or opens a dialog"), +CommandSpec::new("view.render_live", "Pause or Resume Live Render", crate::checked!("view.render_live", render_live)) + .icon("render_image").noundo().doc_only() + .contract(&RENDER_LIVE_CONTRACT).output(output_schema_for::) + .params("paused: bool → {paused}; pause or resume this document's live Render preview; headless validation only, never saves settings or changes a final image"), CommandSpec::new("view.render_select", "Render selection", crate::checked!("view.render_select", render_select)) .contract(&RENDER_SELECT).output(output_schema_for::) .icon("select").noundo().doc_only() @@ -371,6 +376,11 @@ fn render_focus(_s: &mut Session, p: &Value) -> Result { Ok(json!(request)) } +fn render_live(_s: &mut Session, p: &Value) -> Result { + let request: RenderLive = serde_json::from_value(p.clone()).map_err(|e| bad("view.render_live", e.to_string()))?; + Ok(json!(request)) +} + fn render_select(s: &mut Session, p: &Value) -> Result { let request: RenderSelect = serde_json::from_value(p.clone()).map_err(|e| bad("view.render_select", e.to_string()))?; let result = serde_json::to_value(request).map_err(|e| bad("view.render_select", e.to_string()))?; @@ -1198,7 +1208,7 @@ fn render_workspace_focus_and_browser_validate_without_side_effects() { let camera = session.camera; let document = session.doc.clone(); let before = (session.undo.len(), session.redo.len(), session.revision, session.evaluations, session.is_dirty()); - for (id, field) in [("view.render_focus", "on"), ("view.render_browser", "open")] { + for (id, field) in [("view.render_focus", "on"), ("view.render_browser", "open"), ("view.render_live", "paused")] { let command = crate::find_command(id).unwrap(); assert!(command.contract.is_some() && command.output.is_some()); for on in [true, false] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 21a52ce72..3d949d039 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,6 +27,7 @@ pub mod product_scene; pub mod recovery; pub mod render_jobs; pub mod render_lights; +pub mod render_preparation; pub mod sample; pub mod schema; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/render_jobs.rs b/crates/engine/src/render_jobs.rs index b7d0d801a..dacd5ef1f 100644 --- a/crates/engine/src/render_jobs.rs +++ b/crates/engine/src/render_jobs.rs @@ -32,13 +32,6 @@ fn owner() -> u64 { } } -pub(crate) struct Execution { - pub executor: solidcraft_render::ExecutorId, - pub options: solidcraft_render::job::JobOptions, - pub environment: Option, - pub shot: Option, -} - struct LiveJob { handle: JobHandle, shot: Option, @@ -68,6 +61,9 @@ pub(crate) struct BatchShot { pub struct RenderQueueState { pub running: usize, pub waiting: usize, + /// A real native preparation claim, separate from an invented running job. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub preparing: bool, pub job: Option, pub shot: Option, pub error: Option, @@ -85,8 +81,10 @@ pub(crate) struct Jobs { completed: VecDeque, selected: Option, waiting: VecDeque, - batch_job: Option, - batch_error: Option, + pub(crate) batch_job: Option, + pub(crate) batch_error: Option, + pub(crate) native_batch: Option, + pub(crate) native_epoch: u64, comparison: Option<[Option; 2]>, } @@ -106,6 +104,8 @@ impl Default for Jobs { waiting: VecDeque::new(), batch_job: None, batch_error: None, + native_batch: None, + native_epoch: 0, comparison: None, } } @@ -113,6 +113,9 @@ impl Default for Jobs { impl Drop for Jobs { fn drop(&mut self) { + if let Some(native) = &self.native_batch { + native.cancel.cancel(); + } for job in &self.live { let _ = job.handle.cancel(); } @@ -120,6 +123,9 @@ impl Drop for Jobs { } impl Jobs { + pub(crate) fn owner_key(&self) -> u64 { + self.owner + } pub(crate) fn set_comparison(&mut self, sides: Option<[Option; 2]>) { self.comparison = sides; if let Some([left, right]) = sides { @@ -187,24 +193,66 @@ impl Jobs { Ok(()) } - pub(crate) fn start_with_environment( + pub(crate) fn start_prepared( &mut self, revision: u64, - scene: solidcraft_render::ProductScene, - request: solidcraft_render::job::ImageRequest, + prepared: solidcraft_render::job::PreparedSubmission, replace: bool, - execution: Execution, + shot: Option, ) -> Result { - let Execution { executor, options, environment, shot } = execution; - if self.batch_job.is_some() { + self.try_start_prepared(revision, &mut Some(prepared), replace, shot) + } + + pub(crate) fn try_start_prepared( + &mut self, + revision: u64, + slot: &mut Option, + replace: bool, + shot: Option, + ) -> Result { + self.try_start_prepared_inner(revision, slot, replace, shot, None) + } + pub(crate) fn try_start_prepared_inner( + &mut self, + revision: u64, + slot: &mut Option, + replace: bool, + shot: Option, + ticket: Option, + ) -> Result { + let prepared = slot.as_ref().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "prepared render was already consumed"))?; + let batch_next = if let Some(ticket) = ticket { + let native = self + .native_batch + .as_ref() + .filter(|n| n.ticket == ticket && n.claimed && !n.cancel.is_cancelled()) + .ok_or_else(|| JobError::new(ErrorCode::Cancelled, "native shot queue claim is no longer current"))?; + if replace || native.next >= native.total { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid native shot queue front")); + } + Some(native.next + 1) + } else { + None + }; + if ticket.is_none() && (self.batch_job.is_some() || self.native_batch.is_some()) { if !replace { return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before starting another render")); } self.waiting.clear(); self.batch_job = None; + if let Some(native) = self.native_batch.take() { + native.cancel.cancel(); + } } self.collect()?; - let host = self.host_for(&executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone(); + let host = self + .host_for(prepared.executor()) + .ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))? + .clone(); + if !host.same_host(prepared.host()) { + return Err(JobError::new(ErrorCode::WrongOwner, "prepared render host changed before enqueue")); + } + prepared.check_cancel()?; if replace { for job in self.live.drain(..) { let mut status = job.handle.cancel()?; @@ -228,18 +276,18 @@ impl Jobs { } let serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render job identity exhausted"))?; let generation = self.generation.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render generation exhausted"))?; - let handle = host.submit_with_environment_and_options( - JobId { session: self.owner, serial, generation }, - revision, - scene, - request, - options, - environment, - )?; + let handle = host.try_submit_prepared(JobId { session: self.owner, serial, generation }, revision, slot)?; let status = handle.status()?; self.serial = serial; self.generation = generation; self.live.push(LiveJob { handle, shot }); + if let Some(next) = batch_next { + if let Some(native) = &mut self.native_batch { + native.next = next; + native.claimed = false; + } + self.batch_job = Some(status.job); + } Ok(status) } @@ -248,7 +296,7 @@ impl Jobs { source_id: JobId, presentation: solidcraft_render::job::presentation::Presentation, ) -> Result { - if self.batch_job.is_some() { + if self.batch_job.is_some() || self.native_batch.is_some() { return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before regrading")); } self.collect()?; @@ -294,6 +342,38 @@ impl Jobs { .ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) } + /// Metadata-only identity validation for deferred native cancellation. + /// Do not collect terminal work, clone a handle/frame or advance a queue on + /// this read path. Actual cancellation still uses its ordinary handler. + pub(crate) fn check_retained_or_historical_job(&self, id: JobId) -> Result<(), JobError> { + self.check_owner(id)?; + if self.live.iter().any(|job| job.handle.id() == id) + || self.completed.iter().any(|result| result.handle.id() == id) + || self.history.iter().any(|status| status.job == id) + { + Ok(()) + } else { + Err(JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) + } + } + + /// Snapshot existing status without collecting or evicting registry owners. + /// Native queue polling uses this path; ordinary status/result APIs retain + /// their existing explicit collection semantics. + pub(crate) fn peek_status(&self, id: JobId) -> Result { + self.check_owner(id)?; + if let Some(handle) = + self.live.iter().map(|job| &job.handle).chain(self.completed.iter().map(|result| &result.handle)).find(|handle| handle.id() == id) + { + return handle.status(); + } + self.history + .iter() + .find(|status| status.job == id) + .cloned() + .ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) + } + pub(crate) fn status(&mut self, id: JobId) -> Result { self.check_owner(id)?; self.collect()?; @@ -348,7 +428,12 @@ impl crate::Session { let active = self.render_jobs.batch_job.and_then(|id| self.render_jobs.live.iter().find(|job| job.handle.id() == id)); RenderQueueState { running: self.render_jobs.live.iter().filter(|job| job.handle.status().is_ok_and(|status| !status.progress.phase.terminal())).count(), - waiting: self.render_jobs.waiting.len(), + waiting: self + .render_jobs + .native_batch + .as_ref() + .map_or(self.render_jobs.waiting.len(), |n| n.total.saturating_sub(n.next + usize::from(n.claimed))), + preparing: self.render_jobs.native_batch.as_ref().is_some_and(|n| n.claimed), job: self.render_jobs.batch_job, shot: active.and_then(|job| job.shot.clone()), error: self.render_jobs.batch_error.clone(), @@ -356,13 +441,29 @@ impl crate::Session { } pub fn render_batch_ready(&self) -> std::result::Result<(), String> { + self.render_batch_ready_with_claim(false) + } + + /// Recheck ordinary Batch enablement without treating this exact first + /// preparation's own fixed claim as a competing queue. + pub(crate) fn render_batch_ready_for_first(&self, ticket: crate::render_preparation::batch::Ticket) -> std::result::Result<(), String> { + if !ticket.matches(self) || !self.render_jobs.native_batch.as_ref().is_some_and(|n| n.ticket == ticket && n.claimed && n.next == 0) { + return Err("native first shot claim is no longer current".into()); + } + self.render_batch_ready_with_claim(true) + } + + fn render_batch_ready_with_claim(&self, own_first_claim: bool) -> std::result::Result<(), String> { if self.doc.render.setups.is_empty() { return Err("no saved shots to render".into()); } if self.doc.render.setups.len() > 32 { return Err("render all shots is limited to 32 shots".into()); } - if self.render_jobs.batch_job.is_some() || self.render_queue_state().running != 0 { + if (!own_first_claim && self.render_jobs.native_batch.is_some()) + || self.render_jobs.batch_job.is_some() + || self.render_queue_state().running != 0 + { return Err("a render or shot queue is already active".into()); } Ok(()) @@ -405,6 +506,42 @@ impl crate::Session { /// Non-blocking queue scheduling. The existing host still owns all render work. pub fn advance_render_batch(&mut self) -> crate::Result<()> { + // Native foreground/background status polling never captures a shot. + if self.render_jobs.native_batch.is_some() { + if self.render_jobs.native_batch.as_ref().is_some_and(|n| !n.ticket.matches(self)) { + if let Some(native) = self.render_jobs.native_batch.take() { + native.cancel.cancel(); + } + self.render_jobs.batch_job = None; + self.render_jobs.batch_error = Some("native shot queue belongs to a previous document owner".into()); + return Ok(()); + } + if self.render_jobs.native_batch.as_ref().is_some_and(|n| n.cancel.is_cancelled()) { + self.render_jobs.native_batch = None; + self.render_jobs.batch_job = None; + self.render_jobs.batch_error = Some("native shot queue was cancelled".into()); + return Ok(()); + } + if let Some(job) = self.render_jobs.batch_job { + let status = self.render_jobs.peek_status(job).map_err(job_error)?; + if status.progress.phase.terminal() { + let failed = status.progress.phase != Phase::Completed; + let finished = self.render_jobs.native_batch.as_ref().is_some_and(|n| n.next == n.total && !n.claimed); + if failed || finished { + if let Some(native) = self.render_jobs.native_batch.take() + && failed + { + native.cancel.cancel(); + } + self.render_jobs.batch_job = None; + if failed { + self.render_jobs.batch_error = status.error.map(|e| e.to_string()); + } + } + } + } + return Ok(()); + } let Some(job) = self.render_jobs.batch_job else { return Ok(()) }; let status = self.render_jobs.status(job).map_err(job_error)?; if !status.progress.phase.terminal() { @@ -421,11 +558,25 @@ impl crate::Session { pub(crate) fn cancel_render_batch(&mut self, job: JobId) { if self.render_jobs.batch_job == Some(job) { + if let Some(native) = self.render_jobs.native_batch.take() { + native.cancel.cancel(); + } self.render_jobs.waiting.clear(); self.render_jobs.batch_job = None; } } + pub(crate) fn cancel_native_preparation(&mut self) -> bool { + if self.render_jobs.batch_job.is_none() && self.render_jobs.native_batch.as_ref().is_some_and(|n| n.claimed) { + if let Some(native) = self.render_jobs.native_batch.take() { + native.cancel.cancel(); + } + true + } else { + false + } + } + /// Capture the UI draft's label alongside an unnamed active request, never in the design. pub fn label_render_job(&mut self, id: JobId, shot: &str) -> crate::Result<()> { solidcraft_doc::render_settings::RenderSettings::validate_name(shot).map_err(|error| crate::EngineError::Other(error.to_string()))?; @@ -594,4 +745,291 @@ mod displayed_result_tests { let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); assert!(s.execute("render.result.pin", &json!({"job":reply["job"]})).is_err(), "a pending result is never exportable"); } + #[cfg(not(target_arch = "wasm32"))] + fn first_native_plan(s: &mut crate::Session) -> (crate::render_preparation::batch::Plan, JobId) { + use crate::render_preparation::batch; + use solidcraft_render::job::CancelToken; + let mut params = Some(json!({})); + let claim = batch::claim(s, &mut params, &mut None, CancelToken::default()).unwrap(); + let (ready, receiver) = std::sync::mpsc::sync_channel(1); + let (returning, returned) = std::sync::mpsc::sync_channel(1); + let thread = std::thread::spawn(move || { + batch::with_scope(claim, |claim| { + ready.send(batch::prepare(claim)).unwrap(); + drop(returned.recv().unwrap()); + }); + }); + let mut prepared = receiver.recv().unwrap(); + assert_eq!(batch::finish_retained(s, &mut prepared).unwrap(), json!({"queued":2})); + let plan = batch::take_plan(&mut prepared).unwrap().unwrap(); + returning.send(prepared).unwrap(); + thread.join().unwrap(); + (plan, s.render_queue_state().job.unwrap()) + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_next_discard_uses_cached_status_but_hostile_missing_status_fails_only_its_exact_ticket() { + use crate::render_preparation::batch; + use solidcraft_render::job::CancelToken; + for hostile_missing_status in [false, true] { + let mut s = crate::Session::default(); + let host = CpuHost::cooperative(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let old = complete(&mut s, [11, 23, 37]); + let old_handle = s.render_job_handle(old).unwrap(); + let old_frame = old_handle.frame().unwrap().unwrap(); + let old_png = old_frame.png().to_vec(); + for name in ["A", "B"] { + s.execute("render.settings.set", &json!({"name":name,"set":{"width":2,"height":1,"job":{"method":"raster"}}})).unwrap(); + } + let (plan, first) = first_native_plan(&mut s); + for _ in 0..10_000 { + if s.render_job_handle(first).unwrap().status().unwrap().progress.phase.terminal() { + break; + } + host.pump(4096).unwrap(); + } + assert_eq!(s.render_job_handle(first).unwrap().status().unwrap().progress.phase, Phase::Completed); + let retained = s.render_retained_results().unwrap(); + let index = retained.iter().position(|r| r.frame.job == first).unwrap(); + s.execute("render.result.discard", &json!({"index":index})).unwrap(); + assert!(s.render_job_handle(first).is_err()); + assert_eq!( + s.render_jobs.status(first).unwrap().progress.phase, + Phase::Completed, + "ordinary Discard preserves the recent status cache and is not an UnknownJob reproducer" + ); + if hostile_missing_status { + // Defensive hostile registry-state injection, not an ordinary + // UI Discard claim: public regrade/replace cannot rotate this + // status while preserving the same native ticket. + s.render_jobs.history.retain(|status| status.job != first); + } + let bytes = plan.retained_bytes(); + let held = host.admitted_bytes(); + let mut slot = Some(plan); + let result = batch::claim_next(&mut s, &mut slot, CancelToken::default()); + if hostile_missing_status { + let error = match result { + Err(error) => error, + Ok(_) => panic!("missing current status must refuse"), + }; + let message = error.to_string(); + assert!(message.contains("render job is no longer retained")); + assert_eq!(s.render_queue_state().error.as_deref(), Some(message.as_str())); + assert_eq!((s.render_queue_state().waiting, s.render_queue_state().preparing), (0, false)); + assert!(s.render_queue_state().job.is_none()); + assert!(slot.is_some()); + assert_eq!(host.admitted_bytes(), held, "metadata failure cannot release the retained Plan backing"); + assert_eq!(old_frame.png(), old_png); + assert_eq!(s.render_jobs.status(old).unwrap().progress.phase, Phase::Completed); + let token = CancelToken::default(); + let replacement = batch::claim(&mut s, &mut Some(json!({})), &mut None, token.clone()).unwrap(); + let current = json!(s.render_queue_state()); + assert!(batch::claim_next(&mut s, &mut slot, CancelToken::default()).is_err()); + assert_eq!(json!(s.render_queue_state()), current, "stale Plan refusal cannot fail a replacement epoch"); + assert!(!token.is_cancelled()); + let before = host.admitted_bytes(); + let retired = slot.take().unwrap(); + std::thread::spawn(move || batch::retire_plan(retired)).join().unwrap(); + assert_eq!(host.admitted_bytes(), before - bytes, "only actual worker retirement releases Plan credit"); + batch::cancel(&mut s).unwrap(); + std::thread::spawn(move || batch::with_scope(replacement, drop)).join().unwrap(); + } else { + let claim = result.unwrap().unwrap(); + assert!(slot.is_none()); + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().preparing); + assert_eq!(host.admitted_bytes(), held); + batch::cancel(&mut s).unwrap(); + std::thread::spawn(move || batch::with_scope(claim, drop)).join().unwrap(); + assert_eq!(host.admitted_bytes(), held - bytes); + } + assert_eq!(old_frame.png(), old_png); + assert_eq!(old_handle.status().unwrap().progress.phase, Phase::Completed); + } + } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn immutable_native_cancel_identity_checks_live_completed_and_discarded_history_without_collecting_or_advancing() { + use crate::render_preparation::batch; + let mut s = crate::Session::default(); + let host = CpuHost::cooperative(); + s.set_render_job_host(Some(host.clone())).unwrap(); + for name in ["A", "B"] { + s.execute("render.settings.set", &json!({"name":name,"set":{"width":2,"height":1,"job":{"method":"raster"}}})).unwrap(); + } + let (plan, job) = first_native_plan(&mut s); + let document = s.doc.clone(); + let model = s.model.state(); + let handle = s.render_job_handle(job).unwrap(); + let check = |s: &crate::Session| { + let identities = || { + ( + s.render_jobs.live.iter().map(|job| job.handle.id()).collect::>(), + s.render_jobs.completed.iter().map(|result| result.handle.id()).collect::>(), + s.render_jobs.history.iter().map(|status| status.job).collect::>(), + s.render_jobs.serial, + s.render_jobs.generation, + json!(s.render_queue_state()), + ) + }; + let before = identities(); + let bytes = host.admitted_bytes(); + let owners = (Arc::strong_count(&document), Arc::strong_count(&model)); + let history = (s.revision, s.undo.len(), s.redo.len()); + assert_eq!(batch::check_cancel(s, &json!({"job":job})).unwrap(), Some(job)); + assert_eq!(batch::check_cancel(s, &json!({})).unwrap(), None); + assert_eq!(identities(), before, "pure cancel validation cannot collect or advance a native shot front"); + assert_eq!(host.admitted_bytes(), bytes, "validation neither reserves nor drops renderer/plan backing"); + assert_eq!((Arc::strong_count(&document), Arc::strong_count(&model)), owners, "no source clone or retirement"); + assert!(Arc::ptr_eq(&s.doc, &document)); + assert!(Arc::ptr_eq(&s.model.state(), &model)); + assert_eq!((s.revision, s.undo.len(), s.redo.len()), history); + }; + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + check(&s); + for _ in 0..10_000 { + if !host.pump(4096).unwrap() { + break; + } + } + assert_eq!(handle.status().unwrap().progress.phase, Phase::Completed); + assert_eq!((s.render_jobs.live.len(), s.render_jobs.completed.len(), s.render_jobs.history.len()), (1, 0, 0)); + check(&s); + assert_eq!( + (s.render_jobs.live.len(), s.render_jobs.completed.len(), s.render_jobs.history.len()), + (1, 0, 0), + "a completed-but-uncollected handle remains in live metadata" + ); + s.render_jobs.collect().unwrap(); + assert_eq!((s.render_jobs.live.len(), s.render_jobs.completed.len(), s.render_jobs.history.len()), (0, 1, 1)); + check(&s); + let frame = handle.frame().unwrap().unwrap(); + let png = frame.png().to_vec(); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!((s.render_jobs.live.len(), s.render_jobs.completed.len(), s.render_jobs.history.len()), (0, 0, 1)); + assert!(s.render_job_handle(job).is_err()); + check(&s); + assert_eq!(frame.png(), png, "checking an actual discarded result uses history, not a replacement image"); + let unknown = JobId { serial: u64::MAX, generation: u64::MAX, ..job }; + let foreign = JobId { session: job.session + 1, ..job }; + for (id, code) in [(unknown, ErrorCode::UnknownJob), (foreign, ErrorCode::WrongOwner)] { + let before = json!(s.render_queue_state()); + let bytes = host.admitted_bytes(); + assert_eq!(s.render_jobs.check_retained_or_historical_job(id).unwrap_err().code, code); + assert!(batch::check_cancel(&s, &json!({"job":id})).is_err()); + assert_eq!(json!(s.render_queue_state()), before); + assert_eq!(host.admitted_bytes(), bytes); + } + assert_eq!((s.render_queue_state().waiting, s.render_queue_state().preparing), (1, false)); + let held = host.admitted_bytes(); + let plan_bytes = plan.retained_bytes(); + assert!(batch::cancel(&mut s).unwrap(), "terminal history is sufficient to cancel the remaining native queue"); + assert_eq!((s.render_queue_state().waiting, s.render_queue_state().preparing, s.render_queue_state().job), (0, false, None)); + assert_eq!((s.render_jobs.live.len(), s.render_jobs.completed.len(), s.render_jobs.history.len()), (0, 0, 1)); + assert_eq!(host.admitted_bytes(), held, "metadata cancellation retains the Plan lease until its worker retires it"); + assert_eq!(frame.png(), png); + assert!(Arc::ptr_eq(&s.doc, &document) && Arc::ptr_eq(&s.model.state(), &model)); + std::thread::spawn(move || batch::retire_plan(plan)).join().unwrap(); + assert_eq!(host.admitted_bytes(), held - plan_bytes); + } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_queue_status_and_next_claim_keep_eight_results_and_terminal_live_backing_until_explicit_collection() { + use crate::render_preparation::batch; + use solidcraft_render::job::CancelToken; + for cancelled in [false, true] { + let mut s = crate::Session::default(); + let host = CpuHost::cooperative(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let mut old_ids = Vec::new(); + let mut oldest_frame = None; + for index in 0..8 { + let id = complete(&mut s, [index, 31, 63]); + s.render_retained_results().unwrap(); + old_ids.push(id); + if index == 0 { + oldest_frame = Some(Arc::downgrade(&s.render_job_handle(id).unwrap().frame().unwrap().unwrap())); + } + } + let oldest_frame = oldest_frame.unwrap(); + assert_eq!(s.render_jobs.completed.len(), 8); + for name in ["A", "B"] { + s.execute("render.settings.set", &json!({"name":name,"set":{"width":2,"height":1,"job":{"method":"raster"}}})).unwrap(); + } + let (plan, job) = first_native_plan(&mut s); + let handle = s.render_job_handle(job).unwrap(); + if cancelled { + assert_eq!(handle.cancel().unwrap().progress.phase, Phase::Cancelled); + } else { + for _ in 0..10_000 { + if !host.pump(4096).unwrap() { + break; + } + } + assert_eq!(handle.status().unwrap().progress.phase, Phase::Completed); + } + let actual = handle.status().unwrap(); + let peek = s.render_jobs.peek_status(job).unwrap(); + assert_eq!((peek.job, peek.progress.phase), (job, actual.progress.phase)); + assert_eq!(peek.error.as_ref().map(|e| (e.code, e.message.as_str())), actual.error.as_ref().map(|e| (e.code, e.message.as_str()))); + let foreign = JobId { session: job.session + 1, ..job }; + let unknown = JobId { serial: u64::MAX, generation: u64::MAX, ..job }; + assert_eq!(s.render_jobs.peek_status(foreign).unwrap_err().code, ErrorCode::WrongOwner); + assert_eq!(s.render_jobs.peek_status(unknown).unwrap_err().code, ErrorCode::UnknownJob); + let held = host.admitted_bytes(); + let membership = |s: &crate::Session| { + ( + s.render_jobs.live.iter().map(|j| j.handle.id()).collect::>(), + s.render_jobs.completed.iter().map(|j| j.handle.id()).collect::>(), + s.render_jobs.history.iter().map(|j| j.job).collect::>(), + ) + }; + let before = membership(&s); + assert_eq!(before.0, vec![job]); + assert_eq!(before.1, old_ids); + assert!(oldest_frame.upgrade().is_some()); + s.advance_render_batch().unwrap(); + assert_eq!(membership(&s), before, "native status polling cannot collect a terminal live job or evict result0"); + assert_eq!(host.admitted_bytes(), held); + assert!(oldest_frame.upgrade().is_some()); + let mut slot = Some(plan); + let claim = batch::claim_next(&mut s, &mut slot, CancelToken::default()); + assert_eq!(membership(&s), before, "metadata-only next-front claim cannot drive ordinary result retention"); + assert_eq!(host.admitted_bytes(), held); + assert!(oldest_frame.upgrade().is_some()); + if cancelled { + assert!(claim.is_err()); + assert!(slot.is_some()); + assert_eq!((s.render_queue_state().waiting, s.render_queue_state().preparing), (0, false)); + assert!(s.render_queue_state().job.is_none()); + assert_eq!(s.render_queue_state().error.as_deref(), Some("native shot queue was cancelled")); + let bytes = slot.as_ref().unwrap().retained_bytes(); + let retired = slot.take().unwrap(); + std::thread::spawn(move || batch::retire_plan(retired)).join().unwrap(); + assert_eq!(host.admitted_bytes(), held - bytes); + let rows = s.render_retained_results().unwrap(); + assert_eq!(rows.iter().map(|r| r.frame.job).collect::>(), old_ids); + assert!(s.render_jobs.live.is_empty()); + assert!(oldest_frame.upgrade().is_some()); + } else { + let claim = claim.unwrap().unwrap(); + assert!(slot.is_none()); + assert_eq!((s.render_queue_state().waiting, s.render_queue_state().preparing), (0, true)); + assert_eq!(s.render_queue_state().job, Some(job), "keep the last real job while preparing the next camera"); + // Ordinary explicit result collection still applies its existing8-row policy. + let rows = s.render_retained_results().unwrap(); + let mut expected = old_ids[1..].to_vec(); + expected.push(job); + assert_eq!(rows.iter().map(|r| r.frame.job).collect::>(), expected); + assert!(s.render_jobs.live.is_empty()); + assert!(oldest_frame.upgrade().is_none(), "only explicit ordinary collection evicts the oldest completed frame"); + assert!(host.admitted_bytes() < held); + batch::cancel(&mut s).unwrap(); + std::thread::spawn(move || batch::with_scope(claim, drop)).join().unwrap(); + } + } + } } diff --git a/crates/engine/src/render_lights.rs b/crates/engine/src/render_lights.rs index fa48f4135..aafe6e7bd 100644 --- a/crates/engine/src/render_lights.rs +++ b/crates/engine/src/render_lights.rs @@ -4,7 +4,10 @@ use solidcore_record::Vec3; use solidcraft_doc::render_settings::{RenderJob, RenderSetup}; use solidcraft_geom::prelude::*; use solidcraft_render::job::LightingPreset; -use solidcraft_render::job::{AreaLight, AreaLights, DirectionalLightOptions, PunctualLightOptions, RectangleLightOptions, SpotConeOptions, Sun}; +use solidcraft_render::job::{ + AreaLight, AreaLights, DirectionalLightOptions, DirectionalLights, PunctualLightOptions, PunctualLights, RectangleLightOptions, SpotConeOptions, + Sun, +}; pub fn parse_id(id: &str) -> Result<(&str, usize), String> { if id.len() > 16 { @@ -82,6 +85,8 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, (edit.height_mm, 0.000002, 2e6), (edit.reference_distance_mm, 0.001, 1e6), (edit.minimum_distance_mm, 0.001, 1e6), + (edit.inner_half_angle_radians, 0.0, std::f64::consts::FRAC_PI_2), + (edit.outer_half_angle_radians, 0.0, std::f64::consts::FRAC_PI_2), ] { if value.is_some_and(|v| !v.is_finite() || !(low..=high).contains(&v)) { return Err("light edit exceeds finite numerical bounds".into()); @@ -90,6 +95,7 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, for (value, low, high) in [ (edit.position_mm, -1e12, 1e12), (edit.direction, -1e6, 1e6), + (edit.emitted_axis, -1e9, 1e9), (edit.edge_u_mm, -2e6, 2e6), (edit.edge_v_mm, -2e6, 2e6), (edit.radiance, 0.0, 1e8), @@ -116,15 +122,25 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, Geometry::Area { edge_u_mm, .. } => vector(edge_u_mm).len(), _ => 10.0, }; + let old_punctual = match light.geometry { + Geometry::Point { position_mm, reference_distance_mm, minimum_distance_mm } + | Geometry::Spot { position_mm, reference_distance_mm, minimum_distance_mm, .. } => { + Some((position_mm, reference_distance_mm, minimum_distance_mm)) + } + _ => None, + }; + let (punctual_position, punctual_reference, punctual_minimum) = old_punctual.unwrap_or((array(point), distance, 0.001)); let type_changed = edit.kind.as_ref().is_some_and(|kind| kind != light.geometry.kind()); if let Some(kind) = edit.kind.as_ref().filter(|_| type_changed) { light.geometry = match kind.as_str() { "directional" => Geometry::Directional { direction: array(direction), angular_radius_rad: None }, - "point" => Geometry::Point { position_mm: array(point), reference_distance_mm: distance, minimum_distance_mm: 0.001 }, + "point" => { + Geometry::Point { position_mm: punctual_position, reference_distance_mm: punctual_reference, minimum_distance_mm: punctual_minimum } + } "spot" => Geometry::Spot { - position_mm: array(point), - reference_distance_mm: distance, - minimum_distance_mm: 0.001, + position_mm: punctual_position, + reference_distance_mm: punctual_reference, + minimum_distance_mm: punctual_minimum, emitted_axis: array(-direction), inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5, @@ -144,7 +160,7 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, } if let Some(rgb) = edit.radiance { if !matches!(light.geometry, Geometry::Area { .. } | Geometry::Directional { angular_radius_rad: Some(_), .. }) { - return Err("radiance requires an area light or GPU sun".into()); + return Err("radiance requires an area light or finite Sun".into()); } (light.intensity, light.colour) = radiance(rgb); } @@ -161,6 +177,14 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, if !matches!(light.geometry, Geometry::Directional { .. }) && edit.direction.is_some() { return Err("direction requires a directional light".into()); } + if !matches!(light.geometry, Geometry::Spot { .. }) + && (edit.emitted_axis.is_some() || edit.inner_half_angle_radians.is_some() || edit.outer_half_angle_radians.is_some()) + { + return Err("cone angles and emitted axis require a spot light".into()); + } + if edit.emitted_axis.is_some() && edit.aim_at.is_some() { + return Err("choose a spot emitted axis or an aim point, not both".into()); + } let moved = type_changed || edit.azimuth_deg.is_some() || edit.elevation_deg.is_some() || edit.distance_mm.is_some() || edit.aim_at.is_some(); match &mut light.geometry { Geometry::Directional { direction: axis, angular_radius_rad } => { @@ -182,7 +206,14 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, if edit.softness.is_some() || edit.size_mm.is_some() { return Err("point/spot lights have no finite emitter size or soft shadows".into()); } - if moved { + if moved + && !(type_changed + && old_punctual.is_some() + && edit.azimuth_deg.is_none() + && edit.elevation_deg.is_none() + && edit.distance_mm.is_none() + && edit.aim_at.is_none()) + { *position_mm = array(point); } if let Some(position) = edit.position_mm { @@ -236,9 +267,62 @@ pub fn patch(light: &mut Light, edit: &crate::schema::render_lights::LightPatch, { *emitted_axis = array(solidcraft_render::surface::unit_direction(vector(aim) - vector(*position_mm)).unwrap_or(-Vec3::Z)); } + if let Geometry::Spot { emitted_axis, inner_half_angle_radians, outer_half_angle_radians, .. } = &mut light.geometry { + if let Some(axis) = edit.emitted_axis { + *emitted_axis = axis; + } + if let Some(inner) = edit.inner_half_angle_radians { + *inner_half_angle_radians = inner; + } + if let Some(outer) = edit.outer_half_angle_radians { + *outer_half_angle_radians = outer; + } + } Ok(()) } +fn same_vector_bits(a: [f64; 3], b: [f64; 3]) -> bool { + a.into_iter().zip(b).all(|(a, b)| a.to_bits() == b.to_bits()) +} + +// IDs refer to the original family slots until write publishes the new order. +// Preserve an untouched authored source's raw radiance rather than performing an +// unrelated divide/multiply round trip through the common intensity/colour UI. +fn original_sun(lighting: solidcraft_render::job::StudioLighting, light: &Light) -> Option { + original_sun_value(lighting.sun?, light) +} +fn original_sun_value(original: Sun, light: &Light) -> Option { + if light.id != "directional:0" { + return None; + } + let Geometry::Directional { direction, angular_radius_rad: Some(radius) } = light.geometry else { + return None; + }; + let (intensity, colour) = radiance(original.radiance); + (same_vector_bits(direction, original.direction) + && radius.to_bits() == original.angular_radius_rad.to_bits() + && light.intensity.to_bits() == intensity.to_bits() + && same_vector_bits(light.colour, colour)) + .then_some(original) +} +fn original_area(lighting: solidcraft_render::job::StudioLighting, light: &Light) -> Option { + let (kind, index) = parse_id(&light.id).ok()?; + if kind != "area" { + return None; + } + let original = *lighting.area_lights.iter().nth(index)?; + let Geometry::Area { position_mm, edge_u_mm, edge_v_mm } = light.geometry else { + return None; + }; + let (intensity, colour) = radiance(original.radiance); + (same_vector_bits(position_mm, original.center) + && same_vector_bits(edge_u_mm, original.u.map(|x| x * 2.0)) + && same_vector_bits(edge_v_mm, original.v.map(|x| x * 2.0)) + && light.intensity.to_bits() == intensity.to_bits() + && same_vector_bits(light.colour, colour)) + .then_some(original) +} + /// Materializes a canonical rig in a cloned setup. Caller validates and publishes /// atomically. Unsupported backend families are refused, never silently dropped. pub fn write(setup: &mut RenderSetup, lights: &[Light]) -> Result<(), String> { @@ -252,23 +336,28 @@ pub fn write(setup: &mut RenderSetup, lights: &[Light]) -> Result<(), String> { return Err("light family limit exceeded (8 directional, 8 punctual, 4 area)".into()); } match setup.job.as_mut() { - Some(RenderJob::CpuRaytrace { options }) => { - if directional.iter().any(|light| matches!(light.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. })) { - return Err("CPU directional lights have hard shadows; softness is not supported".into()); + Some(RenderJob::CpuRaytrace { options, .. }) => { + let mut sun = None; + let mut hard = Vec::new(); + for light in directional { + if let Geometry::Directional { direction, angular_radius_rad } = light.geometry { + if let Some(angular_radius_rad) = angular_radius_rad { + if sun.is_some() { + return Err("lighting supports one finite Sun; use hard directionals for additional distant sources".into()); + } + sun = Some(options.sun.and_then(|sun| original_sun_value(sun, light)).unwrap_or(Sun { + direction, + angular_radius_rad, + radiance: light.colour.map(|value| value * light.intensity), + })); + } else { + hard.push(DirectionalLightOptions { direction, color: light.colour, intensity: light.intensity }); + } + } } + options.sun = sun; options.preset = None; - options.lights = Some( - directional - .into_iter() - .map(|l| { - let direction = match l.geometry { - Geometry::Directional { direction, .. } => direction, - _ => [0.0, 0.0, 1.0], - }; - DirectionalLightOptions { direction, color: l.colour, intensity: l.intensity } - }) - .collect(), - ); + options.lights = Some(hard); options.punctual_lights = Some( punctual .into_iter() @@ -319,25 +408,69 @@ pub fn write(setup: &mut RenderSetup, lights: &[Light]) -> Result<(), String> { } } Some(RenderJob::GpuPath { options, .. }) => { - if !punctual.is_empty() || directional.len() > 1 { - return Err("GPU lighting supports one Sun and four Areas; choose an explicit studio before editing legacy default lights".into()); - } let mut lighting = options.lighting.unwrap_or_default(); - lighting.sun = directional.first().and_then(|l| match l.geometry { - Geometry::Directional { direction, angular_radius_rad } => { - Some(Sun { direction, angular_radius_rad: angular_radius_rad.unwrap_or(0.02), radiance: l.colour.map(|c| c * l.intensity) }) + let mut sun = None; + let mut hard = Vec::new(); + for light in directional { + if let Geometry::Directional { direction, angular_radius_rad } = light.geometry { + if let Some(angular_radius_rad) = angular_radius_rad { + if sun.is_some() { + return Err("GPU lighting supports one finite Sun; use hard directional lights for additional distant sources".into()); + } + sun = Some(original_sun(lighting, light).unwrap_or(Sun { + direction, + angular_radius_rad, + radiance: light.colour.map(|c| c * light.intensity), + })); + } else { + hard.push(DirectionalLightOptions { direction, color: light.colour, intensity: light.intensity }); + } } - _ => None, - }); + } + let punctual: Vec<_> = punctual + .into_iter() + .filter_map(|light| { + let (position_mm, reference_distance_mm, minimum_distance_mm, cone) = match light.geometry { + Geometry::Point { position_mm, reference_distance_mm, minimum_distance_mm } => { + (position_mm, reference_distance_mm, minimum_distance_mm, None) + } + Geometry::Spot { + position_mm, + reference_distance_mm, + minimum_distance_mm, + emitted_axis, + inner_half_angle_radians, + outer_half_angle_radians, + } => ( + position_mm, + reference_distance_mm, + minimum_distance_mm, + Some(SpotConeOptions { emitted_axis, inner_half_angle_radians, outer_half_angle_radians }), + ), + _ => return None, + }; + Some(PunctualLightOptions { + position_mm, + reference_distance_mm, + minimum_distance_mm, + cone, + color: light.colour, + intensity: light.intensity, + }) + }) + .collect(); + lighting.punctual_lights = PunctualLights::new(&punctual).map_err(|e| e.to_string())?; + lighting.sun = sun; + lighting.directional_lights = DirectionalLights::new(&hard).map_err(|e| e.to_string())?; let areas: Vec<_> = area .into_iter() .filter_map(|l| match l.geometry { - Geometry::Area { position_mm, edge_u_mm, edge_v_mm } => Some(AreaLight { + Geometry::Area { position_mm, edge_u_mm, edge_v_mm } => Some(original_area(lighting, l).unwrap_or(AreaLight { center: position_mm, u: edge_u_mm.map(|v| v * 0.5), v: edge_v_mm.map(|v| v * 0.5), radiance: l.colour.map(|c| c * l.intensity), - }), + })), _ => None, }) .collect(); @@ -381,7 +514,7 @@ pub fn inspect(setup: &RenderSetup) -> Result, String> { setup.validate().map_err(|e| e.to_string())?; let mut lights = Vec::new(); match &setup.job { - Some(RenderJob::CpuRaytrace { options }) => { + Some(RenderJob::CpuRaytrace { options, .. }) => { let implicit = options.lights.is_none(); let defaults; let directional = match &options.lights { @@ -391,10 +524,21 @@ pub fn inspect(setup: &RenderSetup) -> Result, String> { &defaults } }; + if let Some(sun) = options.sun { + let (intensity, colour) = radiance(sun.radiance); + push( + &mut lights, + 0, + false, + intensity, + colour, + Geometry::Directional { direction: sun.direction, angular_radius_rad: Some(sun.angular_radius_rad) }, + ); + } for (index, light) in directional.iter().enumerate() { push( &mut lights, - index, + index + usize::from(options.sun.is_some()), implicit, light.intensity, light.color, @@ -443,6 +587,34 @@ pub fn inspect(setup: &RenderSetup) -> Result, String> { Geometry::Directional { direction: sun.direction, angular_radius_rad: Some(sun.angular_radius_rad) }, ); } + for (index, light) in lighting.directional_lights.iter().enumerate() { + push( + &mut lights, + index + usize::from(lighting.sun.is_some()), + false, + light.intensity, + light.color, + Geometry::Directional { direction: light.direction, angular_radius_rad: None }, + ); + } + for (index, light) in lighting.punctual_lights.iter().enumerate() { + let geometry = match light.cone { + Some(cone) => Geometry::Spot { + position_mm: light.position_mm, + reference_distance_mm: light.reference_distance_mm, + minimum_distance_mm: light.minimum_distance_mm, + emitted_axis: cone.emitted_axis, + inner_half_angle_radians: cone.inner_half_angle_radians, + outer_half_angle_radians: cone.outer_half_angle_radians, + }, + None => Geometry::Point { + position_mm: light.position_mm, + reference_distance_mm: light.reference_distance_mm, + minimum_distance_mm: light.minimum_distance_mm, + }, + }; + push(&mut lights, index, false, light.intensity, light.color, geometry); + } for (index, light) in lighting.area_lights.iter().enumerate() { let (intensity, colour) = radiance(light.radiance); push( diff --git a/crates/engine/src/render_preparation.rs b/crates/engine/src/render_preparation.rs new file mode 100644 index 000000000..8aa9999ab --- /dev/null +++ b/crates/engine/src/render_preparation.rs @@ -0,0 +1,159 @@ +//! Native UI preparation of the same strict Check/Start commands beside the +//! window. No job starts in the scratch owner; commit uses the real registry. +pub mod batch; +pub(crate) mod batch_payload; + +use crate::{Result, Session, cmd::PreparedCapture}; +use serde_json::{Value, json}; +use solidcraft_render::job::CancelToken; +use std::{collections::BTreeMap, sync::Arc}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Check, + Start, +} +impl Kind { + fn command(self) -> &'static str { + match self { + Self::Check => "render.preflight", + Self::Start => "render.start", + } + } +} + +/// Move-only, fully proved capture. The already-created scratch owner provides +/// exact source provenance without a second CAD snapshot or a cache-pointer guess. +/// Renderer resources/leases drop before that temporary CAD owner. +pub struct Prepared { + capture: PreparedCapture, + source: Session, + kind: Kind, + shot: Option, + params: Value, + completed: bool, +} +impl Prepared { + pub fn kind(&self) -> Kind { + self.kind + } +} + +/// Consumes Session::scratch, not the live window Session. The caller carries its +/// VFS scope and cancellation token onto its native preparation worker. +pub fn prepare(snapshot: Session, kind: Kind, params: Value, cancel: CancelToken) -> Result { + prepare_with_metadata(snapshot, kind, params, cancel, None) +} +fn prepare_with_metadata( + snapshot: Session, + kind: Kind, + params: Value, + cancel: CancelToken, + retained: Option<&solidcraft_render::job::RetainedMetadata>, +) -> Result { + cancel.check().map_err(crate::render_jobs::job_error)?; + let params = if params.is_null() { Value::Object(Default::default()) } else { params }; + validate_command(&snapshot, kind, ¶ms)?; + let shot = params.get("setup").and_then(Value::as_str).map(str::to_owned); + let capture = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + crate::cmd::prepare_capture_with_metadata(&snapshot, ¶ms, kind.command(), &cancel, retained) + })) { + Ok(result) => result?, + Err(cause) => { + let message = + cause.downcast_ref::<&str>().map(|value| value.to_string()).or_else(|| cause.downcast_ref::().cloned()).unwrap_or_default(); + return Err(crate::EngineError::Internal(kind.command().into(), message)); + } + }; + submission(&capture)?.check_cancel().map_err(crate::render_jobs::job_error)?; + Ok(Prepared { capture, source: snapshot, kind, shot, params, completed: false }) +} + +// Keep the existing engine command enablement and embedding-host refusal. +// UI/control schema Off/Warn/Strict remains its ordinary dispatch policy. +fn validate_command(session: &Session, kind: Kind, params: &Value) -> Result<()> { + validate_command_id(session, kind.command(), params) +} +fn validate_command_id(session: &Session, id: &str, params: &Value) -> Result<()> { + let spec = crate::find_command(id).ok_or_else(|| crate::EngineError::UnknownCommand(id.into()))?; + (spec.enabled)(session).map_err(|why| crate::EngineError::Disabled(spec.id.into(), why))?; + session.check_command(spec, params) +} + +fn submission(capture: &PreparedCapture) -> Result<&solidcraft_render::job::PreparedSubmission> { + capture.submission.as_ref().ok_or_else(|| crate::EngineError::Other("prepared render was already consumed".into())) +} + +fn same_moves(a: &BTreeMap, b: &BTreeMap) -> bool { + a.len() == b.len() + && a.iter().zip(b).all(|((ka, a), (kb, b))| ka == kb && a.iter().flatten().zip(b.iter().flatten()).all(|(a, b)| a.to_bits() == b.to_bits())) +} +fn camera_bits(camera: Option) -> Option<(solidcraft_render::UpAxis, [u64; 8])> { + camera.map(|camera| { + ( + camera.up, + [camera.target.x, camera.target.y, camera.target.z, camera.yaw, camera.pitch, camera.roll, camera.distance, camera.fov].map(f64::to_bits), + ) + }) +} +fn current(source: &Session, session: &Session) -> bool { + source.uid == session.uid + && source.revision == session.revision + && Arc::ptr_eq(&source.doc, &session.doc) + && Arc::ptr_eq(&source.model.state(), &session.model.state()) + && !session.model.is_stale() + && source.active_sketch == session.active_sketch + && source.feature_edit_sketch == session.feature_edit_sketch + && source.active_component == session.active_component + && source.active_occurrence_path == session.active_occurrence_path + && source.visibility == session.visibility + && same_moves(&source.pending_moves, &session.pending_moves) + && same_moves(&source.exploded, &session.exploded) + && camera_bits(source.camera) == camera_bits(session.camera) +} + +/// Strict synchronous owner wrapper. Native UI completion uses finish_retained +/// and returns the retained owner to its preparation worker for disposal. +pub fn finish(session: &mut Session, mut prepared: Prepared) -> Result { + finish_retained(session, &mut prepared) +} + +/// Revalidate and commit without destroying the large captured source on the +/// caller. Every error retains the capsule and its leases; success retains its +/// scratch source. The native caller returns this owner to the same worker and +/// waits for retirement acknowledgement before reporting resources released. +pub fn finish_retained(session: &mut Session, prepared: &mut Prepared) -> Result { + finish_inner(session, prepared, None) +} +fn finish_inner(session: &mut Session, prepared: &mut Prepared, ticket: Option) -> Result { + if prepared.completed { + return Err(crate::EngineError::Other("prepared render was already completed".into())); + } + if !current(&prepared.source, session) { + return Err(crate::EngineError::Other("render source changed while preparing; check again".into())); + } + validate_command(session, prepared.kind, &prepared.params)?; + let captured = submission(&prepared.capture)?; + let installed = session + .render_jobs + .host_for(captured.executor()) + .ok_or_else(|| crate::EngineError::Other("prepared render host is no longer installed".into()))?; + if !installed.same_host(captured.host()) || !installed.is_available() { + return Err(crate::EngineError::Other("prepared render host changed before completion".into())); + } + captured.check_cancel().map_err(crate::render_jobs::job_error)?; + if prepared.kind == Kind::Check { + prepared.completed = true; + return Ok(std::mem::take(&mut prepared.capture.reply)); + } + let status = session + .render_jobs + .try_start_prepared_inner(session.revision, &mut prepared.capture.submission, prepared.capture.replace, prepared.shot.clone(), ticket) + .map_err(crate::render_jobs::job_error)?; + prepared.completed = true; + let mut status = json!(status); + if let (Some(out), Some(ignored)) = (status.as_object_mut(), prepared.capture.reply.get("ignored_controls")) { + out.insert("ignored_controls".into(), ignored.clone()); + } + Ok(status) +} diff --git a/crates/engine/src/render_preparation/batch.rs b/crates/engine/src/render_preparation/batch.rs new file mode 100644 index 000000000..10ccaf60f --- /dev/null +++ b/crates/engine/src/render_preparation/batch.rs @@ -0,0 +1,428 @@ +//! Native camera queue preparation. Runtime command metadata is distinct from +//! funded renderer storage: the long-lived shared request is an exact Vec arena. +use super::{ + Kind, + batch_payload::{self, Payload}, +}; +use crate::{EngineError, Result, Session}; +use serde_json::{Value, json}; +use solidcraft_io::vfs::PathScope; +use solidcraft_render::{ + Camera, + job::{CancelToken, Phase, RetainedMetadata}, +}; +use std::mem::size_of; + +fn bad(message: &str) -> EngineError { + EngineError::Other(message.into()) +} +fn check(cancel: &CancelToken) -> Result<()> { + cancel.check().map_err(crate::render_jobs::job_error) +} +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct Ticket { + uid: u64, + owner: u64, + epoch: u64, +} +impl Ticket { + pub(crate) fn matches(self, s: &Session) -> bool { + self.uid == s.uid && self.owner == s.render_jobs.owner_key() + } +} +pub(crate) struct NativeState { + pub ticket: Ticket, + pub next: usize, + pub total: usize, + pub claimed: bool, + pub cancel: CancelToken, +} +struct Row { + name: String, + camera: Camera, +} +/// Opaque persistent shared request. Backing precedes its independent lease. +pub struct Plan { + ticket: Ticket, + payload: Payload, + rows: Vec, + scope: Option, + next: usize, + lease: RetainedMetadata, +} +impl Plan { + pub fn owner_matches(&self, s: &Session) -> bool { + self.ticket.matches(s) + } + pub fn retained_bytes(&self) -> u64 { + self.lease.bytes() + } +} +/// One exact source/front claim; a failed channel delivery retains this owner. +pub struct Claim { + ticket: Ticket, + front: usize, + first: bool, + total: usize, + source: Session, + params: Option, + scope: Option, + plan: Option, + cancel: CancelToken, +} +impl Claim { + pub fn owner_matches(&self, s: &Session) -> bool { + self.ticket.matches(s) + } + pub fn is_first(&self) -> bool { + self.first + } +} +/// Success or failure owns its complete retirement path. There is no heavy Err +/// payload implicitly destroyed on the window. +pub struct Prepared { + ticket: Ticket, + front: usize, + first: bool, + total: usize, + plan: Option, + inner: Option, + // Exact first caller input is command metadata, not persistent Plan backing. + // Keep it through current-owner policy validation and worker retirement. + first_params: Option, + error: Option, + cancel: CancelToken, + committed: bool, + finished: bool, +} +impl Prepared { + pub fn owner_matches(&self, s: &Session) -> bool { + self.ticket.matches(s) + } + pub fn is_first(&self) -> bool { + self.first + } + pub fn committed(&self) -> bool { + self.committed + } +} + +/// Caller starts its empty bounded worker first. Metadata refusal takes neither +/// owned input nor scope. No source capture, resource IO or job starts here. +pub fn claim(s: &mut Session, params: &mut Option, scope: &mut Option, cancel: CancelToken) -> Result { + check(&cancel)?; + let input = params.as_ref().ok_or_else(|| bad("batch request was already claimed"))?; + solidcraft_io::vfs::scoped(scope.clone(), || super::validate_command_id(s, "render.batch", input))?; + s.render_batch_ready().map_err(EngineError::Other)?; + if s.model.is_stale() { + return Err(bad("finish the modelling gesture before rendering shots")); + } + let epoch = s.render_jobs.native_epoch.checked_add(1).ok_or_else(|| bad("native shot queue identity exhausted"))?; + let owner = s.render_jobs.owner_key(); + if owner == 0 { + return Err(bad("render session identity exhausted")); + } + let ticket = Ticket { uid: s.uid, owner, epoch }; + let total = s.doc.render.setups.len(); + let source = s.scratch(); + let params = params.take().ok_or_else(|| bad("batch request vanished before claim"))?; + s.render_jobs.native_epoch = epoch; + s.render_jobs.batch_error = None; + s.render_jobs.native_batch = Some(NativeState { ticket, next: 0, total, claimed: true, cancel: cancel.clone() }); + Ok(Claim { ticket, front: 0, first: true, total, source, params: Some(params), scope: scope.take(), plan: None, cancel }) +} +/// None means the actual current job is still running or its front is claimed. +/// Refusal preserves the plan; the consumer retires it on its worker. +pub fn claim_next(s: &mut Session, slot: &mut Option, cancel: CancelToken) -> Result> { + check(&cancel)?; + let plan = slot.as_ref().ok_or_else(|| bad("batch plan was already claimed"))?; + if !plan.owner_matches(s) { + return Err(bad("batch plan belongs to another real session owner")); + } + // Verify the exact real owner/epoch/front before metadata errors may fail + // this queue. A stale Plan is not authority to alter a replacement ticket. + let native = + s.render_jobs.native_batch.as_ref().filter(|n| n.ticket == plan.ticket).ok_or_else(|| bad("native shot queue is no longer current"))?; + if native.claimed { + return Ok(None); + } + if native.next != plan.next || native.total != plan.rows.len() || native.next >= native.total { + return Err(bad("native shot queue front changed")); + } + let ticket = plan.ticket; + let ready = (|| { + s.advance_render_batch()?; + if !s.render_jobs.native_batch.as_ref().is_some_and(|n| n.ticket == ticket) { + return Err(bad("native shot queue is no longer current")); + } + if let Some(job) = s.render_jobs.batch_job { + let status = s.render_jobs.peek_status(job).map_err(crate::render_jobs::job_error)?; + if !status.progress.phase.terminal() { + return Ok(false); + } + if status.progress.phase != Phase::Completed { + return Err(bad("previous native shot did not complete")); + } + } + Ok(true) + })(); + match ready { + Ok(true) => {} + Ok(false) => return Ok(None), + Err(error) => { + // Fixed metadata only: retain Plan/source backing for its original + // worker retirement and never touch a newer queue on this owner. + fail(s, ticket, &error.to_string()); + return Err(error); + } + } + let source = s.scratch(); + let front = plan.next; + let total = plan.rows.len(); + let ticket = plan.ticket; + let plan = slot.take().ok_or_else(|| bad("batch plan vanished before claim"))?; + if let Some(native) = &mut s.render_jobs.native_batch { + native.claimed = true; + native.cancel = cancel.clone(); + } + Ok(Some(Claim { ticket, front, first: false, total, source, params: None, scope: None, plan: Some(plan), cancel })) +} + +fn shot_params(mut value: Value, camera: Camera) -> Result { + value + .get_mut("settings") + .and_then(Value::as_object_mut) + .ok_or_else(|| bad("queued render settings are missing"))? + .insert("camera".into(), json!(camera)); + Ok(value) +} +fn plan_bytes(source: &Session, payload: batch_payload::Counts, scope: Option<&PathScope>) -> Result { + let rows = source.doc.render.setups.len(); + let mut bytes = (size_of::() as u64).checked_add(payload.bytes()?).ok_or_else(|| bad("batch plan byte overflow"))?; + bytes = bytes + .checked_add(rows.checked_mul(size_of::()).ok_or_else(|| bad("batch row byte overflow"))? as u64) + .ok_or_else(|| bad("batch plan byte overflow"))?; + for name in source.doc.render.setups.keys() { + bytes = bytes.checked_add(name.len() as u64).ok_or_else(|| bad("batch name byte overflow"))?; + } + bytes + .checked_add(scope.map_or(Ok(0), PathScope::retained_heap_bytes).map_err(|e| bad(&e.to_string()))?) + .ok_or_else(|| bad("batch scope byte overflow")) +} +fn first(claim: Claim, out: &mut Prepared) -> Result<()> { + out.first_params = claim.params; + let input = out.first_params.as_ref().ok_or_else(|| bad("initial batch input missing"))?; + let empty = Value::Object(Default::default()); + let input = if input.is_null() { &empty } else { input }; + // Both the original Batch and every nested Start retain their exact guard + // inputs for current-owner validation before the first real enqueue. + let common = crate::cmd::batch_request(&claim.source, input)?; + let (name, camera) = claim.source.doc.render.setups.iter().next().map(|(n, s)| (n.clone(), s.camera)).ok_or_else(|| bad("no saved shots"))?; + let params = shot_params(common.clone(), camera)?; + let mut inner = super::prepare(claim.source, Kind::Start, params, claim.cancel.clone())?; + inner.shot = Some(name); + out.inner = Some(inner); + let counts = batch_payload::count(&common, &claim.cancel)?; + let source = &out.inner.as_ref().ok_or_else(|| bad("missing first prepared owner"))?.source; + let bytes = plan_bytes(source, counts, claim.scope.as_ref())?; + let lease = super::submission(&out.inner.as_ref().ok_or_else(|| bad("missing first preparation"))?.capture)? + .reserve_retained_metadata(bytes) + .map_err(crate::render_jobs::job_error)?; + let mut rows = Vec::new(); + rows.try_reserve_exact(claim.total).map_err(|_| bad("could not allocate batch rows"))?; + if rows.capacity() != claim.total { + return Err(bad("batch row capacity exceeds reservation")); + } + for (name, setup) in &source.doc.render.setups { + check(&claim.cancel)?; + let mut copied = String::new(); + copied.try_reserve_exact(name.len()).map_err(|_| bad("could not retain batch name"))?; + if copied.capacity() != name.len() { + return Err(bad("batch name capacity exceeds reservation")); + } + copied.push_str(name); + rows.push(Row { name: copied, camera: setup.camera }); + } + let payload = Payload::new(common, counts, &claim.cancel)?; + // No normalized Arc remains alongside this arena. The exact original + // Batch input belongs only to this first Prepared command metadata owner, + // never to the persistent Plan, and retires on the same worker after finish. + let plan = Plan { ticket: claim.ticket, payload, rows, scope: claim.scope, next: 0, lease }; + if plan.actual_bytes()? != plan.lease.bytes() { + return Err(bad("batch arena actual backing disagrees with reservation")); + } + out.plan = Some(plan); + Ok(()) +} +fn next(mut claim: Claim, out: &mut Prepared) -> Result<()> { + out.plan = claim.plan.take(); + let plan = out.plan.as_ref().ok_or_else(|| bad("missing next-shot plan"))?; + let row = plan.rows.get(claim.front).ok_or_else(|| bad("batch camera row missing"))?; + let params = shot_params(plan.payload.value(&claim.cancel)?, row.camera)?; + let mut inner = super::prepare_with_metadata(claim.source, Kind::Start, params, claim.cancel.clone(), Some(&plan.lease))?; + inner.shot = Some(row.name.clone()); + out.inner = Some(inner); + Ok(()) +} +impl Plan { + fn actual_bytes(&self) -> Result { + let mut bytes = (size_of::() as u64).checked_add(self.payload.heap_bytes()?).ok_or_else(|| bad("batch actual byte overflow"))?; + bytes = bytes + .checked_add(self.rows.capacity().checked_mul(size_of::()).ok_or_else(|| bad("batch actual row overflow"))? as u64) + .ok_or_else(|| bad("batch actual row overflow"))?; + for row in &self.rows { + bytes = bytes.checked_add(row.name.capacity() as u64).ok_or_else(|| bad("batch actual name overflow"))?; + } + bytes + .checked_add(self.scope.as_ref().map_or(Ok(0), PathScope::retained_heap_bytes).map_err(|e| bad(&e.to_string()))?) + .ok_or_else(|| bad("batch actual scope overflow")) + } +} +/// Always returns the exact owner, including failures. Caller must retire it on +/// this same worker after finish/stale/cancel, and wait for acknowledgement. +pub fn prepare(claim: Claim) -> Prepared { + let mut out = Prepared { + ticket: claim.ticket, + front: claim.front, + first: claim.first, + total: claim.total, + plan: None, + inner: None, + first_params: None, + error: None, + cancel: claim.cancel.clone(), + committed: false, + finished: false, + }; + let scope = claim.scope.clone().or_else(|| claim.plan.as_ref().and_then(|p| p.scope.clone())); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + solidcraft_io::vfs::scoped(scope, || { + check(&claim.cancel)?; + if claim.first { first(claim, &mut out) } else { next(claim, &mut out) } + }) + })); + out.error = match result { + Ok(Ok(())) => None, + Ok(Err(error)) => Some(error.to_string()), + Err(_) => Some("native batch preparation failed internally".into()), + }; + out +} +fn fail(s: &mut Session, ticket: Ticket, message: &str) { + if s.render_jobs.native_batch.as_ref().is_some_and(|n| n.ticket == ticket) { + if let Some(native) = s.render_jobs.native_batch.take() { + native.cancel.cancel(); + } + s.render_jobs.batch_job = None; + s.render_jobs.batch_error = Some(message.into()); + } +} +/// The real owner commits; a different current tab cannot adopt its jobs. All +/// error and successful source backing remains in `out` for worker retirement. +pub fn finish_retained(s: &mut Session, out: &mut Prepared) -> Result { + if !out.owner_matches(s) { + return Err(bad("batch completion belongs to another real session owner")); + } + if out.finished { + return Err(bad("batch preparation was already completed")); + } + let native = s + .render_jobs + .native_batch + .as_ref() + .filter(|n| n.ticket == out.ticket && n.claimed && n.next == out.front && n.total == out.total) + .ok_or_else(|| bad("native shot queue claim is no longer current"))?; + if let Err(error) = check(&native.cancel) { + out.finished = true; + fail(s, out.ticket, &error.to_string()); + return Err(error); + } + let result = (|| { + check(&out.cancel)?; + if let Some(error) = &out.error { + return Err(bad(error)); + } + let scope = out.plan.as_ref().and_then(|p| p.scope.clone()); + let inner = out.inner.as_mut().ok_or_else(|| bad("batch preparation has no proved job"))?; + let reply = solidcraft_io::vfs::scoped(scope, || { + if out.first { + let input = out.first_params.as_ref().ok_or_else(|| bad("first batch guard input missing"))?; + let spec = crate::find_command("render.batch").ok_or_else(|| EngineError::UnknownCommand("render.batch".into()))?; + // The ordinary enablement shares this readiness predicate. Only + // this exact first claimed front is exempt from its own busy bit. + s.render_batch_ready_for_first(out.ticket).map_err(|why| EngineError::Disabled(spec.id.into(), why))?; + s.check_command(spec, input)?; + } + super::finish_inner(s, inner, Some(out.ticket)) + })?; + out.committed = true; + let plan = out.plan.as_mut().ok_or_else(|| bad("batch completion has no plan"))?; + plan.next = out.front + 1; + Ok(if out.first { json!({"queued":out.total}) } else { reply }) + })(); + out.finished = true; + if let Err(error) = &result + && !out.committed + { + fail(s, out.ticket, &error.to_string()); + } + result +} +pub fn take_plan(out: &mut Prepared) -> Result> { + if !out.committed { + return Err(bad("batch plan cannot advance before its actual job")); + } + if out.plan.as_ref().is_some_and(|p| p.next < p.rows.len()) { Ok(out.plan.take()) } else { Ok(None) } +} +/// Metadata-only cancellation, including a first claim which has no fabricated +/// job ID. Idle/closed plans still require their separate worker retirement. +pub fn cancel(s: &mut Session) -> Result { + let Some(native) = s.render_jobs.native_batch.take() else { return Ok(false) }; + native.cancel.cancel(); + if let Some(job) = s.render_jobs.batch_job.take() { + // A discarded completed front can survive only in the bounded status + // history. It needs no live handle or additional cancellation; looking + // it up must not collect or evict another retained result here. + let status = s.render_jobs.peek_status(job).map_err(crate::render_jobs::job_error)?; + if !status.progress.phase.terminal() { + let _ = s.render_jobs.handle(job).map_err(crate::render_jobs::job_error)?.cancel().map_err(crate::render_jobs::job_error)?; + } + } + Ok(true) +} + +/// Cleanup for a particular idle plan. Owner equality alone is deliberately +/// insufficient: an identical replacement queue has a different epoch. +pub fn cancel_plan(s: &mut Session, plan: &Plan) -> Result { + if !plan.owner_matches(s) || !s.render_jobs.native_batch.as_ref().is_some_and(|n| n.ticket == plan.ticket) { + return Ok(false); + } + cancel(s) +} + +/// The native worker wraps its entire send/return/drop lifecycle here. Send the +/// release acknowledgement only after this returns, so both captured backing +/// and its temporary caller permission context have really retired. The plan +/// itself still owns/funds exactly one persistent scope between jobs. +pub fn with_scope(claim: Claim, f: impl FnOnce(Claim) -> T) -> T { + let scope = claim.scope.clone().or_else(|| claim.plan.as_ref().and_then(|p| p.scope.clone())); + solidcraft_io::vfs::scoped(scope, || f(claim)) +} +/// Idle, closed or rejected plan-only messages need no second stored scope. +/// Hold the lease until original scope storage and all backing have dropped. +pub fn retire_plan(plan: Plan) { + let Plan { payload, rows, scope, lease, .. } = plan; + solidcraft_io::vfs::scoped(scope, || drop((payload, rows))); + drop(lease); +} +/// Pure ordinary cancellation enablement/policy/typed-argument check. A pending +/// UI input has no invented job: None may cancel that input; Some must follow +/// the ordinary actual-job cancellation route, including ownership validation. +pub fn check_cancel(s: &Session, params: &Value) -> Result> { + super::validate_command_id(s, "render.cancel", params)?; + let job = crate::cmd::render_cancel_params(params)?; + if let Some(job) = job { + s.render_jobs.check_retained_or_historical_job(job).map_err(crate::render_jobs::job_error)?; + } + Ok(job) +} diff --git a/crates/engine/src/render_preparation/batch_payload.rs b/crates/engine/src/render_preparation/batch_payload.rs new file mode 100644 index 000000000..8b7086e96 --- /dev/null +++ b/crates/engine/src/render_preparation/batch_payload.rs @@ -0,0 +1,258 @@ +//! Owned shared command data. Only public Vec/String capacities are retained; +//! no serde_json object allocation survives conversion into the plan. +use crate::{EngineError, Result}; +use serde_json::{Number, Value}; +use solidcraft_render::job::CancelToken; +use std::mem::size_of; + +fn bad(message: &str) -> EngineError { + EngineError::Other(message.into()) +} +fn add(a: u64, b: usize) -> Result { + a.checked_add(u64::try_from(b).map_err(|_| bad("batch payload byte overflow"))?).ok_or_else(|| bad("batch payload byte overflow")) +} +#[derive(Clone, Copy)] +enum Numeric { + Signed(i64), + Unsigned(u64), + Float(u64), +} +impl Numeric { + fn capture(value: Number) -> Result { + if value.is_i64() { + return value.as_i64().map(Self::Signed).ok_or_else(|| bad("batch signed number")); + } + if value.is_u64() { + return value.as_u64().map(Self::Unsigned).ok_or_else(|| bad("batch unsigned number")); + } + if value.is_f64() { + return value.as_f64().filter(|n| n.is_finite()).map(|n| Self::Float(n.to_bits())).ok_or_else(|| bad("batch finite number")); + } + Err(bad("batch command number is not representable without changing its value")) + } + fn value(self) -> Result { + Ok(Value::Number(match self { + Self::Signed(v) => v.into(), + Self::Unsigned(v) => v.into(), + Self::Float(v) => Number::from_f64(f64::from_bits(v)).ok_or_else(|| bad("batch stored number"))?, + })) + } +} +enum Node { + Pending(Value), + Null, + Bool(bool), + Number(Numeric), + String(String), + Array { begin: usize, end: usize }, + Object { begin: usize, end: usize }, +} +struct Edge { + key: Option, + child: usize, +} +#[derive(Clone, Copy)] +pub(crate) struct Counts { + nodes: usize, + edges: usize, + strings: u64, +} +impl Counts { + pub(crate) fn bytes(self) -> Result { + let bytes = self + .nodes + .checked_mul(size_of::()) + .and_then(|n| self.edges.checked_mul(size_of::()).and_then(|e| n.checked_add(e))) + .ok_or_else(|| bad("batch arena storage overflow"))?; + add(self.strings, bytes) + } +} + +// This is the existing serde_json command parser nesting envelope, not a +// material/light/shot count. Valid typed rendering commands are shallower. +const JSON_DEPTH: usize = 128; +enum Frame<'a> { + Array(std::slice::Iter<'a, Value>), + Object(serde_json::map::Iter<'a>), +} +fn cancelled(cancel: &CancelToken) -> Result<()> { + cancel.check().map_err(crate::render_jobs::job_error) +} +pub(crate) fn count(value: &Value, cancel: &CancelToken) -> Result { + let mut counts = Counts { nodes: 0, edges: 0, strings: 0 }; + let mut stack: [Option>; JSON_DEPTH] = std::array::from_fn(|_| None); + let mut depth = 0; + let mut next = Some(value); + loop { + cancelled(cancel)?; + if let Some(value) = next.take() { + counts.nodes = counts.nodes.checked_add(1).ok_or_else(|| bad("batch arena node overflow"))?; + match value { + Value::String(v) => counts.strings = add(counts.strings, v.capacity())?, + Value::Array(v) => { + counts.edges = counts.edges.checked_add(v.len()).ok_or_else(|| bad("batch arena edge overflow"))?; + *stack.get_mut(depth).ok_or_else(|| bad("batch request exceeds the existing JSON nesting envelope"))? = + Some(Frame::Array(v.iter())); + depth += 1; + } + Value::Object(v) => { + counts.edges = counts.edges.checked_add(v.len()).ok_or_else(|| bad("batch arena edge overflow"))?; + *stack.get_mut(depth).ok_or_else(|| bad("batch request exceeds the existing JSON nesting envelope"))? = + Some(Frame::Object(v.iter())); + depth += 1; + } + _ => {} + } + } + while depth != 0 && next.is_none() { + match stack.get_mut(depth - 1).and_then(Option::as_mut).ok_or_else(|| bad("batch arena traversal"))? { + Frame::Array(iter) => next = iter.next(), + Frame::Object(iter) => { + if let Some((key, value)) = iter.next() { + counts.strings = add(counts.strings, key.capacity())?; + next = Some(value); + } + } + } + if next.is_none() { + *stack.get_mut(depth - 1).ok_or_else(|| bad("batch arena traversal pop"))? = None; + depth -= 1; + } + } + if next.is_none() { + return Ok(counts); + } + } +} + +pub(crate) struct Payload { + nodes: Vec, + edges: Vec, + strings: u64, +} +impl Payload { + /// Caller reserves Counts::bytes plus its fixed plan/rows/scope backing + /// before this new bulk allocation. The old command Value is caller-owned + /// metadata and is dismantled here on the preparation worker. + pub(crate) fn new(value: Value, counts: Counts, cancel: &CancelToken) -> Result { + cancelled(cancel)?; + let mut nodes = Vec::new(); + let mut edges = Vec::new(); + nodes.try_reserve_exact(counts.nodes).map_err(|_| bad("could not allocate batch arena nodes"))?; + edges.try_reserve_exact(counts.edges).map_err(|_| bad("could not allocate batch arena edges"))?; + if nodes.capacity() != counts.nodes || edges.capacity() != counts.edges { + return Err(bad("batch arena capacity exceeds its reservation")); + } + nodes.push(Node::Pending(value)); + let mut at = 0; + while at < nodes.len() { + cancelled(cancel)?; + let slot = nodes.get_mut(at).ok_or_else(|| bad("batch arena pending node"))?; + let Node::Pending(value) = std::mem::replace(slot, Node::Null) else { + return Err(bad("batch arena node already resolved")); + }; + let begin = edges.len(); + let resolved = match value { + Value::Null => Node::Null, + Value::Bool(v) => Node::Bool(v), + Value::Number(v) => Node::Number(Numeric::capture(v)?), + Value::String(v) => Node::String(v), + Value::Array(values) => { + for value in values { + cancelled(cancel)?; + if nodes.len() == nodes.capacity() || edges.len() == edges.capacity() { + return Err(bad("batch arena array exceeds reservation")); + } + let child = nodes.len(); + nodes.push(Node::Pending(value)); + edges.push(Edge { key: None, child }); + } + Node::Array { begin, end: edges.len() } + } + Value::Object(values) => { + for (key, value) in values { + cancelled(cancel)?; + if nodes.len() == nodes.capacity() || edges.len() == edges.capacity() { + return Err(bad("batch arena object exceeds reservation")); + } + let child = nodes.len(); + nodes.push(Node::Pending(value)); + edges.push(Edge { key: Some(key), child }); + } + Node::Object { begin, end: edges.len() } + } + }; + *nodes.get_mut(at).ok_or_else(|| bad("batch arena resolved slot"))? = resolved; + at += 1; + } + if nodes.len() != counts.nodes || edges.len() != counts.edges { + return Err(bad("batch arena accounting disagrees with conversion")); + } + Ok(Self { nodes, edges, strings: counts.strings }) + } + pub(crate) fn heap_bytes(&self) -> Result { + add( + self.strings, + self.nodes + .capacity() + .checked_mul(size_of::()) + .and_then(|n| self.edges.capacity().checked_mul(size_of::()).and_then(|e| n.checked_add(e))) + .ok_or_else(|| bad("batch arena actual capacity overflow"))?, + ) + } + /// Exactly one per-shot raw command Value is reconstructed on the worker. + /// Like individual command metadata it remains caller-owned, is moved into + /// Prepared.params, and retires on that worker. It is not decoded renderer + /// storage or a second retained common batch request. + pub(crate) fn value(&self, cancel: &CancelToken) -> Result { + self.node_value(0, 0, cancel) + } + fn node_value(&self, at: usize, depth: usize, cancel: &CancelToken) -> Result { + cancelled(cancel)?; + if depth > JSON_DEPTH { + return Err(bad("batch arena stored nesting")); + } + let copy = |text: &str| -> Result { + let mut value = String::new(); + value.try_reserve_exact(text.len()).map_err(|_| bad("could not copy batch command text"))?; + value.push_str(text); + Ok(value) + }; + Ok(match self.nodes.get(at).ok_or_else(|| bad("batch arena stored index"))? { + Node::Null => Value::Null, + Node::Bool(v) => Value::Bool(*v), + Node::Number(v) => v.value()?, + Node::String(v) => Value::String(copy(v)?), + Node::Array { begin, end } => { + let entries = self.edges.get(*begin..*end).ok_or_else(|| bad("batch arena array range"))?; + let mut values = Vec::new(); + values.try_reserve_exact(entries.len()).map_err(|_| bad("could not copy batch command array"))?; + for edge in entries { + values.push(self.node_value(edge.child, depth + 1, cancel)?); + } + Value::Array(values) + } + Node::Object { begin, end } => { + let entries = self.edges.get(*begin..*end).ok_or_else(|| bad("batch arena object range"))?; + let mut values = serde_json::Map::new(); + for edge in entries { + let key = edge.key.as_deref().ok_or_else(|| bad("batch arena object key"))?; + values.insert(copy(key)?, self.node_value(edge.child, depth + 1, cancel)?); + } + Value::Object(values) + } + Node::Pending(_) => return Err(bad("batch arena conversion incomplete")), + }) + } +} + +#[cfg(test)] +pub(crate) fn test_element_bytes() -> (usize, usize) { + (size_of::(), size_of::()) +} +#[cfg(test)] +impl Payload { + pub(crate) fn test_capacities(&self) -> (usize, usize, u64) { + (self.nodes.capacity(), self.edges.capacity(), self.strings) + } +} diff --git a/crates/engine/src/schema/render.rs b/crates/engine/src/schema/render.rs index d929fed51..042b9222a 100644 --- a/crates/engine/src/schema/render.rs +++ b/crates/engine/src/schema/render.rs @@ -25,3 +25,57 @@ pub struct EnvironmentResult { pub name: String, pub setup: Value, } + +/// Shared clear-coat numbers; the handler validates the renderer's exact domain. +#[derive(Clone, Copy, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct CoatNumbers { + pub weight: f64, + pub roughness: f64, + pub ior: f64, +} +impl Default for CoatNumbers { + fn default() -> Self { + let coat = solidcraft_doc::render_coat::CoatMaterial::default(); + Self { weight: coat.weight, roughness: coat.roughness, ior: coat.ior } + } +} +impl CoatNumbers { + pub fn material(self) -> solidcraft_doc::render_coat::CoatMaterial { + solidcraft_doc::render_coat::CoatMaterial { weight: self.weight, roughness: self.roughness, ior: self.ior } + } +} +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CoatBindParams { + pub name: String, + /// Numerical shot snapshot; cannot replace existing coat bindings through this patch. + #[serde(default = "empty_patch")] + pub set: Value, + pub body_index: usize, + pub body_name: String, + pub coat: CoatNumbers, + pub expected_revision: u64, + #[serde(default)] + pub replace: bool, +} +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CoatUnbindParams { + pub name: String, + /// Exact saved definition/feature/component/occurrence_path, checked by the document type. + #[schemars(with = "std::collections::BTreeMap")] + pub target: Value, + pub expected_revision: u64, +} +#[derive(Serialize, JsonSchema)] +pub struct CoatBindResult { + pub name: String, + pub setup: Value, + pub geometry_and_engineering_unchanged: bool, +} +#[derive(Serialize, JsonSchema)] +pub struct CoatUnbindResult { + pub name: String, + pub removed: bool, +} diff --git a/crates/engine/src/schema/render_library.rs b/crates/engine/src/schema/render_library.rs index da76f0c16..681cb7e7f 100644 --- a/crates/engine/src/schema/render_library.rs +++ b/crates/engine/src/schema/render_library.rs @@ -322,6 +322,8 @@ pub struct RenderTarget { pub ordinal: usize, /// Its name, with its component's path when it is in one. pub name: String, + /// Its saved definition, feature and occurrence identity; `null` when no stable target exists. + pub stable_target: Option, /// Its colour: red, green and blue, 0 to 255. pub color: [u8; 3], /// How opaque it is: 1 is solid. @@ -330,6 +332,30 @@ pub struct RenderTarget { pub pbr: Option, } +/// A stable body identity accepted by saved surface, optical and clear-coat bindings. +#[derive(Debug, Serialize, JsonSchema)] +pub struct StableRenderTarget { + /// The saved body definition's name. + pub definition: String, + /// The feature that produced the body. + pub feature: u64, + /// The owning component, or 0 for the root definition. + pub component: u64, + /// The ordered occurrence ids from the root; empty for a root definition. + pub occurrence_path: Vec, +} + +impl From<&solidcraft_doc::render_surface::RenderBodyTarget> for StableRenderTarget { + fn from(target: &solidcraft_doc::render_surface::RenderBodyTarget) -> Self { + Self { + definition: target.definition.clone(), + feature: target.feature, + component: target.component, + occurrence_path: target.occurrence_path.clone(), + } + } +} + /// A body's PBR look. #[derive(Debug, Serialize, JsonSchema)] pub struct Pbr { diff --git a/crates/engine/src/schema/render_library_tests.rs b/crates/engine/src/schema/render_library_tests.rs index 6724ba0d1..bad110c6f 100644 --- a/crates/engine/src/schema/render_library_tests.rs +++ b/crates/engine/src/schema/render_library_tests.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use super::{ LibraryDescribeParams, LibraryDescription, LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryTargets, - LibraryTargetsParams, + LibraryTargetsParams, RenderTarget, StableRenderTarget, }; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; @@ -124,7 +124,7 @@ fn render_library_commands_reply_with_their_schemas() { let empty = run(&mut s, "render.library.targets", json!({})); matches(&targets, &empty); assert!(empty["bounds"].is_null(), "{empty}"); - run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 5, "body_name": "Target"})); + let created = run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 5, "body_name": "Target"})); run( &mut s, "appearance.assign", @@ -134,6 +134,35 @@ fn render_library_commands_reply_with_their_schemas() { matches(&targets, &r); assert_eq!((r["total"].as_u64(), r["items"][0]["name"].as_str()), (Some(1), Some("Target")), "{r}"); assert!(r["items"][0]["pbr"].is_object() && r["bounds"].is_object(), "{r}"); + assert_eq!( + r["items"][0]["stable_target"], + json!({"definition":"Target","feature":created["feature"],"component":0,"occurrence_path":[]}), + "the typed reply must preserve the saved root-body identity" + ); + let mut without_stable = r.clone(); + without_stable["items"][0] = serde_json::to_value(RenderTarget { + ordinal: 0, + name: "Unbound".into(), + stable_target: None, + color: [180, 120, 70], + opacity: 1.0, + pbr: None, + }) + .unwrap(); + assert_eq!(without_stable["items"][0].get("stable_target"), Some(&Value::Null), "an unavailable identity stays an explicit null"); + matches(&targets, &without_stable); + let authority = + solidcraft_doc::render_surface::RenderBodyTarget { definition: "Part".into(), feature: 7, component: 3, occurrence_path: vec![11, 3, 6] }; + authority.validate().unwrap(); + let mut nested = r.clone(); + nested["items"][0]["stable_target"] = serde_json::to_value(StableRenderTarget::from(&authority)).unwrap(); + matches(&targets, &nested); + assert_eq!( + serde_json::from_value::(nested["items"][0]["stable_target"].clone()).unwrap(), + authority + ); + nested["items"][0]["stable_target"]["occurrence_path"] = json!([11, "not an occurrence id", 6]); + assert!(!conforms(targets.as_value(), targets.as_value(), &nested), "the reply schema must describe the stable identity's actual fields"); if cfg!(feature = "bundled-render-library") { matches(&preview, &run(&mut s, "render.library.preview", json!({"id": "SURF-001"}))); } diff --git a/crates/engine/src/schema/render_lights.rs b/crates/engine/src/schema/render_lights.rs index af78112f7..3aaab2886 100644 --- a/crates/engine/src/schema/render_lights.rs +++ b/crates/engine/src/schema/render_lights.rs @@ -19,7 +19,7 @@ pub struct ListResult { pub lights: Vec, } -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] pub struct Light { /// Family and zero-based source slot: directional:N, point:N, spot:N or area:N. /// Point and spot share their punctual-list index. Stable across numerical edits, @@ -41,13 +41,13 @@ pub struct Light { pub geometry: Geometry, } -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Geometry { Directional { /// World direction towards the source, as stored; need not be unit length. direction: [f64; 3], - /// Present for the GPU finite-disk sun only, in radians. + /// Present for a finite-disk Sun, in radians. CPU requires explicit Path transport. #[serde(skip_serializing_if = "Option::is_none")] angular_radius_rad: Option, }, @@ -134,6 +134,11 @@ pub struct LightPatch { /// World-space fields, lowered to the existing renderer parameters. pub position_mm: Option<[f64; 3]>, pub direction: Option<[f64; 3]>, + /// Spot-only world emission direction FROM the light. Conflicts with aim_at. + pub emitted_axis: Option<[f64; 3]>, + /// Spot half cones in radians; require 0 <= inner < outer <= pi/2. + pub inner_half_angle_radians: Option, + pub outer_half_angle_radians: Option, pub edge_u_mm: Option<[f64; 3]>, pub edge_v_mm: Option<[f64; 3]>, pub radiance: Option<[f64; 3]>, @@ -154,9 +159,21 @@ pub struct EditParams { pub expected_revision: Option, } +/// A surviving source's address before and after this exact structural edit. +/// `before` verifies the mapping belongs to the caller's draft, not a different +/// settings override. New or duplicated sources never inherit an old identity. +#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LightIdRemap { + pub before: Light, + pub after_id: String, +} + #[derive(Debug, Serialize, JsonSchema)] pub struct EditResult { pub id: Option, + #[schemars(length(max = 20))] + pub id_remap: Vec, pub name: String, pub setup: Value, } diff --git a/crates/engine/src/schema/render_presets.rs b/crates/engine/src/schema/render_presets.rs index 1fa53e696..a88a11477 100644 --- a/crates/engine/src/schema/render_presets.rs +++ b/crates/engine/src/schema/render_presets.rs @@ -13,9 +13,9 @@ fn no_change() -> Value { } /// `set`: changes to the setup, as `render.settings.set` takes them. `patched_settings` in -/// `cmd/render.rs` refuses anything but an object of at most 13 fields, with its own message. +/// `cmd/render.rs` refuses anything but an object of at most 15 fields, with its own message. /// The fields of a render setup, as `render.settings.get` gives them. A `set` patch may give up -/// to 13 of them; `patched_settings` reads the patched setup as a `RenderSetup`, which refuses any +/// to 15 of them; `patched_settings` reads the patched setup as a `RenderSetup`, which refuses any /// other key. const SETUP_FIELDS: &[&str] = &[ "backend", @@ -31,6 +31,7 @@ const SETUP_FIELDS: &[&str] = &[ "job", "surfaces", "optics", + "coats", "stage", ]; @@ -41,11 +42,11 @@ fn setup_properties() -> serde_json::Map { fn set_schema(_: &mut SchemaGenerator) -> Schema { json_schema!({ - "description": "Changes to the setup before the studio is fitted, as `render.settings.set` takes them: at most 13 of the setup's fields. The setup they make must render with the GPU path tracer. Default: none.", + "description": "Changes to the setup before the studio is fitted, as `render.settings.set` takes them: at most 15 of the setup's fields. The setup they make must render with the CPU or GPU path tracer. Default: none.", "type": "object", "properties": setup_properties(), "additionalProperties": false, - "maxProperties": 13, + "maxProperties": 15, "default": {} }) } @@ -90,16 +91,84 @@ pub struct QualityParams { /// The quality profile: `Q-` and its number, as `render.library.list` with `kind: quality` /// gives it. pub id: String, - /// How to use it: only `fixed_samples_png`, a fixed budget for a PNG still. + /// `fixed_samples_png` for GPU or `cpu_progressive_png` for CPU cost budgets. #[schemars(schema_with = "variant_schema")] pub variant: String, /// Agree that the budget leaves out what the profile asks for beyond a fixed budget (see /// `omitted` in the reply). Required as true. pub acknowledge_omissions: bool, + /// Optional CPU budget/adaptive context; refused for the GPU variant. + #[serde(default)] + pub cpu: Option, } fn variant_schema(_: &mut SchemaGenerator) -> Schema { - json_schema!({"type": "string", "enum": ["fixed_samples_png"]}) + json_schema!({"type": "string", "enum": ["fixed_samples_png", "cpu_progressive_png"]}) +} + +/// CPU quality context, deserialized with the renderer's original field types. +#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct CpuQuality { + #[schemars(schema_with = "budget_schema")] + pub minimum_budget: solidcraft_render::job::CpuBudget, + #[schemars(schema_with = "adaptive_schema")] + pub adaptive: Option, +} +fn budget_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type":"string","enum":["compact","studio","workstation"]}) +} +fn adaptive_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"anyOf":[{"type":"null"},{"type":"object","additionalProperties":false, + "properties":{"pilot_samples":{"type":"integer","minimum":0,"maximum":4294967295u64}, + "min_samples":{"type":"integer","minimum":0,"maximum":4294967295u64}, + "relative_error":{"type":"number"},"absolute_error":{"type":"number"},"coverage_error":{"type":"number"}}}]}) +} + +/// Both quality command projections; each serialized branch retains its existing fields. +#[derive(Serialize, JsonSchema)] +#[serde(untagged)] +pub enum QualityResult { + Gpu(QualityPlan), + Cpu(CpuQualityPlan), +} +#[derive(Serialize, JsonSchema)] +pub struct CpuQualityPlan { + pub id: String, + pub name: Option, + pub variant: String, + pub status: String, + pub revision: u64, + pub document_changed: bool, + pub source_unchanged: bool, + pub settings: QualitySize, + pub cpu_options: CpuQualityOptions, + pub cpu_context: CpuQualityContext, + pub requires_progressive: bool, + pub changed_fields: Vec, + pub preserves: Vec, + pub omitted: Vec, + pub source: Map, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} +#[derive(Serialize, JsonSchema)] +pub struct CpuQualityOptions { + pub progressive: CpuProgressive, + #[schemars(schema_with = "budget_schema")] + pub budget: solidcraft_render::job::CpuBudget, +} +#[derive(Serialize, JsonSchema)] +pub struct CpuProgressive { + pub samples_per_pixel: u32, + pub seed: u32, +} +#[derive(Serialize, JsonSchema)] +pub struct CpuQualityContext { + #[schemars(schema_with = "budget_schema")] + pub minimum_budget: solidcraft_render::job::CpuBudget, + #[schemars(schema_with = "adaptive_schema")] + pub adaptive: Option, } /// What `render.preset.resolve` and `render.preset.apply` return: the fitted studio. @@ -126,7 +195,7 @@ pub struct StudioComposition { /// Whether the design changed: always false for resolve; for apply, false when the setup /// already was the studio. pub document_changed: bool, - /// Always `gpu-path`: the studio renders with the GPU path tracer. + /// `cpu-raytrace` or `gpu-path`, matching the selected setup executor. pub executor: String, /// Always true: applying needs `replace_lighting_and_environment`. pub requires_lighting_consent: bool, diff --git a/crates/engine/src/schema/render_presets_tests.rs b/crates/engine/src/schema/render_presets_tests.rs index 166b515e9..737d1f2d0 100644 --- a/crates/engine/src/schema/render_presets_tests.rs +++ b/crates/engine/src/schema/render_presets_tests.rs @@ -1,6 +1,6 @@ use serde_json::{Value, json}; -use super::{PresetParams, QualityParams, QualityPlan, StudioComposition}; +use super::{PresetParams, QualityParams, QualityPlan, QualityResult, StudioComposition}; use crate::Session; use crate::schema::tests::{assert_keys, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -26,7 +26,7 @@ fn budget(id: &str) -> Value { #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["expected_revision", "id", "name", "replace_lighting_and_environment", "replace_stage", "set"]); - assert_keys(input_schema_for::(), &["acknowledge_omissions", "id", "variant"]); + assert_keys(input_schema_for::(), &["acknowledge_omissions", "cpu", "id", "variant"]); } /// The handlers refuse these calls after reading them; strict refuses them with their message. @@ -100,7 +100,7 @@ fn preset_commands_reply_with_their_schemas() { /// `set` names the render setup's fields: `patched_settings` reads the patched setup as a /// `RenderSetup`, which refuses any other key, so the schema refuses a misspelt one too (and -/// more than 13 at once). +/// more than 15 at once). #[test] fn the_set_schema_names_the_setup_fields() { let root = input_schema_for::(); @@ -112,5 +112,36 @@ fn the_set_schema_names_the_setup_fields() { assert_eq!(conforms(root, set, &patch), takes, "{patch}"); } // `conforms` doesn't read `maxProperties`, so the limit is pinned here. - assert_eq!((set["maxProperties"].as_u64(), set["properties"].as_object().map(|p| p.len())), (Some(13), Some(super::SETUP_FIELDS.len())), "{set}"); + assert_eq!((set["maxProperties"].as_u64(), set["properties"].as_object().map(|p| p.len())), (Some(15), Some(super::SETUP_FIELDS.len())), "{set}"); +} + +#[test] +fn cpu_quality_and_studio_contracts_preserve_both_executors() { + let plan_schema = output_schema_for::(); + let composition_schema = output_schema_for::(); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = with_a_shot(level); + for id in ["Q-001", "Q-002", "Q-003"] { + let request = json!({"id":id,"variant":"cpu_progressive_png","acknowledge_omissions":true, + "cpu":{"minimum_budget":"studio"}}); + let before = s.doc.clone(); + let reply = s.execute("render.quality.prepare", &request).unwrap(); + let schema = plan_schema.as_value(); + assert!(conforms(schema, schema, &reply), "{reply} doesn't match {schema}"); + assert!(reply.get("param_warnings").is_none(), "{reply}"); + assert_eq!(reply["variant"], "cpu_progressive_png"); + assert_eq!(reply["cpu_context"]["minimum_budget"], "studio"); + assert_eq!(s.doc, before); + } + if cfg!(feature = "bundled-render-library") { + s.execute("render.settings.set", &json!({"name":"Cpu","set":{"job":{"method":"cpu_raytrace"}}})).unwrap(); + let before = s.doc.clone(); + let reply = s.execute("render.preset.resolve", &json!({"id":"NATIVE-STUDIO-001","name":"Cpu","set":{"coats":[]}})).unwrap(); + let schema = composition_schema.as_value(); + assert!(conforms(schema, schema, &reply), "{reply} doesn't match {schema}"); + assert_eq!(reply["executor"], "cpu-raytrace"); + assert!(reply.get("param_warnings").is_none(), "{reply}"); + assert_eq!(s.doc, before); + } + } } diff --git a/crates/engine/src/schema/view_navigation.rs b/crates/engine/src/schema/view_navigation.rs index 7cbf8ad3e..1213f9a7b 100644 --- a/crates/engine/src/schema/view_navigation.rs +++ b/crates/engine/src/schema/view_navigation.rs @@ -34,6 +34,14 @@ pub struct RenderFocus { pub on: bool, } +/// Pause or resume the current document's live Render preview without saving a setup. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RenderLive { + /// True pauses refinement; false resumes it using the current visual settings. + pub paused: bool, +} + #[derive(Debug, Deserialize, Serialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct RenderBrowser { diff --git a/crates/gpu/src/path/adaptive.rs b/crates/gpu/src/path/adaptive.rs index 73d0d071c..a9ed2148d 100644 --- a/crates/gpu/src/path/adaptive.rs +++ b/crates/gpu/src/path/adaptive.rs @@ -3,6 +3,51 @@ use super::*; use solidcraft_render::job::adaptive::SamplingReport; +fn internal(message: &str) -> JobError { + JobError::new(ErrorCode::Internal, message) +} + +fn production_count(options: &JobOptions, bytes: Option<&[u8]>) -> Result { + let adaptive = options.adaptive.ok_or_else(|| internal("missing adaptive preview options"))?; + let bytes: [u8; 4] = bytes.and_then(|bytes| bytes.try_into().ok()).ok_or_else(|| internal("missing adaptive preview budget"))?; + let value = f32::from_le_bytes(bytes); + if !value.is_finite() || value.fract() != 0.0 || value < adaptive.min_samples as f32 || value > options.samples as f32 { + return Err(internal("invalid adaptive preview production count")); + } + Ok(value as u32) +} +pub(super) fn preview_divisor(options: &JobOptions, completed: u32, budget: Option<&[u8]>) -> Result { + let adaptive = options.adaptive.ok_or_else(|| internal("missing adaptive preview options"))?; + let total = options.samples.checked_add(adaptive.pilot_samples).ok_or_else(|| internal("adaptive preview target overflow"))?; + if completed == 0 || completed > total { + return Err(internal("adaptive preview iteration exceeds its target")); + } + if completed <= adaptive.pilot_samples { + return Ok(1.0); + } + let production = completed - adaptive.pilot_samples; + let target = production_count(options, budget)?; + // The shader divides a finished pixel exactly once, then leaves that mean alone. + Ok(if production < target { production as f32 } else { 1.0 }) +} +pub(super) fn preview_paths(task: &Task, budgets: Option<&[u8]>) -> Result { + let options = task.options.adaptive.ok_or_else(|| internal("missing adaptive preview options"))?; + let pixels = u64::from(task.request.width) * u64::from(task.request.height); + if task.sample <= options.pilot_samples { + return Ok(pixels * u64::from(task.sample)); + } + let production = task.sample - options.pilot_samples; + let mut paths = pixels * u64::from(options.pilot_samples); + let bytes = budgets.ok_or_else(|| internal("missing adaptive preview budgets"))?; + for (index, pixel) in bytes.as_chunks::<16>().0.iter().enumerate() { + if index % 4096 == 0 { + task.cancel.check()?; + } + paths += u64::from(production.min(production_count(&task.options, pixel.get(..4))?)) * u64::from(task.options.transmission_samples); + } + Ok(paths) +} + pub(super) fn report(task: &Task) -> Result { task.cancel.check()?; task.context.ensure_available()?; diff --git a/crates/gpu/src/path/adaptive_preview.wgsl b/crates/gpu/src/path/adaptive_preview.wgsl new file mode 100644 index 000000000..648df5ba9 --- /dev/null +++ b/crates/gpu/src/path/adaptive_preview.wgsl @@ -0,0 +1,20 @@ +// Display copy only: never writes the independently sampled production film. +struct Parameters { image:vec4, work:vec4 }; +@group(0) @binding(0) var u:Parameters; +@group(0) @binding(1) var film:array>; +@group(0) @binding(2) var display:array>; +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid:vec3) { + let pixels=u.image.x*u.image.y; + let pixel=u.image.w+gid.x; + if gid.x>=u.work.x || pixel>=pixels { return; } + if u.image.z<=u.work.y { + display[pixel]=film[pixels+pixel]; + } else { + let completed=u.image.z-u.work.y; + let budget=u32(film[2u*pixels+pixel].x); + // Completed pixels were divided in place by the production shader already. + if completed)>, Vec, Option>); +fn adaptive_output(context: Arc, options: JobOptions, preview: bool) -> AdaptiveOutputs { + let mut task = Task::new(context, sphere_grid(white(), 8, 16), request(8), options, CancelToken::default()).unwrap(); + task.preview_enabled = preview; + let mut images = Vec::new(); + for _ in 0..200_000 { + let poll = task.step(4096).unwrap(); + if let Some(image) = task.take_preview() { + assert!(task.take_linear_exr().is_none(), "pilot/production preview never exposes an export master"); + images.push((image.samples_per_pixel, image.png)); + } + if let TaskPoll::Complete(png) = poll { + return (images, png, task.take_linear_exr()); + } + } + panic!("adaptive presentation must complete within bounded test work"); +} + +#[test] +fn every_adaptive_prefix_is_displayed_and_preview_work_keeps_final_png_exr_identical_with_denoise() { + let Some(executor) = executor() else { return }; + for denoise in [false, true] { + let options = JobOptions { + samples: 32, + max_depth: 3, + seed: 47, + linear_exr: true, + denoise, + adaptive: Some(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }), + finishing: solidcraft_render::job::finishing::Finishing { + rgb_gain: [1.2, 0.9, 1.1], + contrast: 1.1, + bloom: Some(solidcraft_render::job::bloom::Bloom { strength: 0.2, threshold: 0.1, radius: 1 }), + photographic: solidcraft_render::job::photographic::Photographic { grain: 0.01, seed: 17, ..Default::default() }, + ..Default::default() + }, + ..Default::default() + }; + let baseline = adaptive_output(executor.context.clone(), options, false); + let shown = adaptive_output(executor.context.clone(), options, true); + assert_eq!( + shown.0.iter().map(|image| image.0).collect::>(), + (1..options.preview_target().unwrap()).collect::>(), + "every complete pilot and production iteration is a real image" + ); + assert_eq!(shown.1, baseline.1, "display readbacks, normalization, effects and denoise cannot change final PNG bytes"); + assert_eq!(shown.2, baseline.2, "raw final EXR must be byte-identical with preview work enabled"); + assert!(shown.2.is_some()); + for production in [16, 31] { + let prefix = adaptive_output(executor.context.clone(), JobOptions { samples: production, ..options }, false); + let provisional = &shown.0.iter().find(|image| image.0 == 16 + production).unwrap().1; + let a = image::load_from_memory(provisional).unwrap().into_rgba8(); + let b = image::load_from_memory(&prefix.1).unwrap().into_rgba8(); + // In-place GPU final division and the display-only copy may differ by one + // display rounding unit; both represent this exact production prefix. + assert!( + a.as_raw().iter().zip(b.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1), + "the normalized production prefix must match a standalone capped final, denoise={denoise}, production={production}" + ); + } + } +} + +#[test] +fn cancellation_during_adaptive_preview_encoding_cannot_publish_a_preview_or_master() { + let Some(executor) = executor() else { return }; + let options = JobOptions { + samples: 16, + denoise: true, + linear_exr: true, + adaptive: Some(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }), + ..Default::default() + }; + let cancel = CancelToken::default(); + let mut task = Task::new(executor.context.clone(), sphere_grid(white(), 8, 16), request(4), options, cancel.clone()).unwrap(); + task.preview_enabled = true; + for _ in 0..100_000 { + task.step(1).unwrap(); + if task.encoding_preview && task.png.is_some() { + break; + } + } + assert!(task.encoding_preview && task.png.is_some()); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert!(task.take_preview().is_none()); + assert!(task.take_linear_exr().is_none()); +} diff --git a/crates/gpu/src/path/aging.wgsl b/crates/gpu/src/path/aging.wgsl index 63d6ece8b..7cefcf4d4 100644 --- a/crates/gpu/src/path/aging.wgsl +++ b/crates/gpu/src/path/aging.wgsl @@ -3,7 +3,7 @@ struct AgingLayer { identity: vec4, // kind, captured body+1 (zero = all), material class, seed mask: vec4, // strength, coverage, inverse mm scale, upward bias - origin: vec4, // rebased periodic field offset + origin: vec4, // periodic field offset; w: base5 Scratch cell carries x/y/z color: vec4, // linear coat RGB, perceptual roughness finish: vec4, // metallic, reserved }; @@ -25,24 +25,102 @@ fn aging_noise(point: vec3, seed: u32) -> f32 { mix(aging_hash(base+vec3(0,1,1),seed),aging_hash(base+vec3(1,1,1),seed),w.x),w.y); return mix(low,high,w.z); } +// Scratch samples the same periodic noise from bounded cell/fraction parts. +// In particular, multiplying a large q by3 before fract must not discard the +// authored fine phase merely because the camera moved by an integer period. +fn aging_floor_mod4096(value:f32)->u32 { + let bits=bitcast(floor(value)); + let biased=(bits>>23u)&255u; + if biased<127u {return 0u;} + let exponent=biased-127u; + let significand=(bits&0x7fffffu)|0x800000u; + var cell_index=0u; + if exponent<23u { + cell_index=(significand>>(23u-exponent))&4095u; + } else if exponent<35u { + cell_index=(significand<<(exponent-23u))&4095u; + } + if (bits&0x80000000u)!=0u {return (4096u-cell_index)&4095u;} + return cell_index; +} +fn aging_noise_parts(base:vec3,f:vec3,seed:u32)->f32 { + let w=f*f*(vec3(3.0)-2.0*f); + let low=mix(mix(aging_hash(base,seed),aging_hash(base+vec3(1,0,0),seed),w.x), + mix(aging_hash(base+vec3(0,1,0),seed),aging_hash(base+vec3(1,1,0),seed),w.x),w.y); + let high=mix(mix(aging_hash(base+vec3(0,0,1),seed),aging_hash(base+vec3(1,0,1),seed),w.x), + mix(aging_hash(base+vec3(0,1,1),seed),aging_hash(base+vec3(1,1,1),seed),w.x),w.y); + return mix(low,high,w.z); +} +// Exact modulo of the represented f32 integer floor. Avoid i32 saturation +// when admitted world/camera offsets are large compared with the layer scale. +// The ordinary (<2^23) field path uses one shift and remainder, no loop. +fn aging_floor_mod5120(value:f32)->u32 { + let bits=bitcast(floor(value)); + let biased=(bits>>23u)&255u; + if biased<127u {return 0u;} + let exponent=biased-127u; + let significand=(bits&0x7fffffu)|0x800000u; + var cell_index=0u; + if exponent<23u { + cell_index=(significand>>(23u-exponent))%5120u; + } else { + cell_index=significand%5120u; + // A finite f32 has at most104 integer bits beyond its significand. + // The1e7 mm geometry rebase and0.01 mm minimum scale bound + // admitted q near1e9 cells, requiring at most6 iterations. + for(var shift=0u;shift<104u;shift+=1u) { + if shift>=exponent-23u {break;} + cell_index=(cell_index*2u)%5120u; + } + } + if (bits&0x80000000u)!=0u && cell_index!=0u {return 5120u-cell_index;} + return cell_index; +} +fn aging_scratch_band(value:f32, camera_cell:u32)->u32 { + // floor(4*Q/5) repeats every5120 Q cells. Preserve its integer phase + // separately from noise's4096-cell quotient; never form a20480-cell float. + let cell_index=(aging_floor_mod5120(value)+4096u*camera_cell)%5120u; + let numerator=4u*cell_index; + let whole=numerator/5u; + // Remainder0/1 cannot cross a band; the other exact thresholds are + // 3/4,1/2,1/4. Integer/fraction separation avoids 0.8*q rounding a + // value just below a boundary into the next band. + let threshold=f32(5u-numerator%5u)*0.25; + return (whole+select(0u,1u,fract(value)>=threshold))&4095u; +} fn aging_mask(layer: AgingLayer, point:vec3, normal:vec3)->vec2 { let q=point*layer.mask.z+layer.origin.xyz; let seed=u32(layer.identity.w); - let coarse=aging_noise(q,seed); - let fine=aging_noise(q*3.0+vec3(19.0,7.0,3.0),seed+1u); + let kind=u32(layer.identity.x); + var coarse=0.0; + var fine=0.0; + if kind==5u { + let cell=vec3(aging_floor_mod4096(q.x),aging_floor_mod4096(q.y),aging_floor_mod4096(q.z)); + let fraction=fract(q); + let scaled_fraction=fraction*3.0; + let fine_cell=(cell*3u+vec3(floor(scaled_fraction))+vec3(19u,7u,3u))&vec3(4095u); + coarse=aging_noise_parts(vec3(cell),fraction,seed); + fine=aging_noise_parts(vec3(fine_cell),fract(scaled_fraction),seed+1u); + } else { + coarse=aging_noise(q,seed); + fine=aging_noise(q*3.0+vec3(19.0,7.0,3.0),seed+1u); + } let field=coarse*0.75+fine*0.25; let threshold=1.0-layer.mask.y; var coverage=smoothstep(threshold-0.09,threshold+0.09,field); if layer.mask.y>=1.0 {coverage=1.0;} - let kind=u32(layer.identity.x); if kind==5u { // Long shallow visual scratches in a dominant-axis projection. They do // not create grooves, silhouettes, cavity masks or geometric curvature. let n=abs(normal); var uv=q.xy; - if n.x>n.y && n.x>n.z {uv=q.yz;} else if n.y>n.z {uv=q.xz;} - let band=i32(floor(uv.y*0.8)); - let line=abs(fract(uv.x*24.0+aging_hash(vec3(band,0,0),seed)*0.7)-0.5); + let phase_code=u32(layer.origin.w); + var camera_cell=(phase_code/5u)%5u; + if n.x>n.y && n.x>n.z {uv=q.yz;camera_cell=phase_code/25u;} else if n.y>n.z {uv=q.xz;camera_cell=phase_code/25u;} + let band=i32(aging_scratch_band(uv.y,camera_cell)); + // The discarded whole u contributes an integer24 phase. Reducing + // before multiplication preserves the shallow line at distant origins. + let line=abs(fract(fract(uv.x)*24.0+aging_hash(vec3(band,0,0),seed)*0.7)-0.5); coverage*=1.0-smoothstep(0.025,0.09,line); coverage*=smoothstep(0.18,0.48,fine); } diff --git a/crates/gpu/src/path/denoise.rs b/crates/gpu/src/path/denoise.rs index 19c170ac5..b5ad0201b 100644 --- a/crates/gpu/src/path/denoise.rs +++ b/crates/gpu/src/path/denoise.rs @@ -82,6 +82,7 @@ impl Pipelines { } pub(super) struct Resources { + adaptive: Option, guide_pipeline: wgpu::ComputePipeline, guide_bind: wgpu::BindGroup, filter_pipeline: wgpu::ComputePipeline, @@ -99,6 +100,7 @@ impl Resources { scene: [&wgpu::Buffer; 5], accumulation: &wgpu::Buffer, size: u64, + adaptive_preview: bool, ) -> Result { let pipelines = Pipelines::shared(context)?; let device = &context.device; @@ -142,8 +144,10 @@ impl Resources { }) }) .collect(); + let adaptive = adaptive_preview.then(|| AdaptiveInput::new(context, pipelines, accumulation, &guides, &filter_uniform, &output, size)); checked(error_scopes)?; Ok(Self { + adaptive, guide_pipeline: pipelines.guide.clone(), guide_bind, filter_pipeline: pipelines.filter.clone(), @@ -159,13 +163,20 @@ impl Resources { } pub(super) fn run(&self, task: &Task) -> Result<()> { + self.run_with_input(task, false) + } + pub(super) fn run_adaptive_preview(&self, task: &Task) -> Result<()> { + self.adaptive.as_ref().ok_or_else(|| super::gpu("missing adaptive denoise preview input"))?.normalize(task)?; + self.run_with_input(task, true) + } + fn run_with_input(&self, task: &Task, preview: bool) -> Result<()> { let pixels = task.request.width * task.request.height; let mut budget = super::dispatch::Budget::default(); let mut offset = 0; while offset < pixels { task.cancel.check()?; let count = budget.count(pixels - offset); - let mut parameters = task.parameters(count); + let mut parameters = task.parameters(count)?; if let Some(bytes) = parameters.get_mut(12..16) { bytes.copy_from_slice(&offset.to_le_bytes()); } @@ -175,12 +186,17 @@ impl Resources { budget.observe(count, started.elapsed()); offset += count; } - self.run_filter(task) + self.run_filter(task, preview) } - fn run_filter(&self, task: &Task) -> Result<()> { + fn run_filter(&self, task: &Task, preview: bool) -> Result<()> { let pixels = task.request.width * task.request.height; for (pass, bind) in self.filter_binds.iter().enumerate() { + let bind = if preview && pass == 0 { + &self.adaptive.as_ref().ok_or_else(|| super::gpu("missing adaptive denoise preview input"))?.filter_bind + } else { + bind + }; let mut budget = super::dispatch::Budget::default(); let mut offset = 0; while offset < pixels { @@ -201,6 +217,112 @@ impl Resources { } } +/// A distinct normalized input for adaptive display only. The final filter stays bound +/// to the original production accumulation, and this pass never writes that film. +struct AdaptiveInput { + _pixels: wgpu::Buffer, + uniform: wgpu::Buffer, + pipeline: wgpu::ComputePipeline, + bind: wgpu::BindGroup, + filter_bind: wgpu::BindGroup, +} +impl AdaptiveInput { + fn new( + context: &Context, + pipelines: &Pipelines, + accumulation: &wgpu::Buffer, + guides: &wgpu::Buffer, + filter_uniform: &wgpu::Buffer, + output: &wgpu::Buffer, + size: u64, + ) -> Self { + let device = &context.device; + let pixels = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("adaptive preview denoise input"), + size, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("adaptive preview parameters"), + contents: &[0; 32], + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + let entries: Vec<_> = (0..3) + .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 == 1 } }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }) + .collect(); + let layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("adaptive preview normalization"), entries: &entries }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("adaptive preview normalization"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("adaptive preview normalization"), + source: wgpu::ShaderSource::Wgsl(include_str!("adaptive_preview.wgsl").into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("adaptive preview normalization"), + layout: Some(&pipeline_layout), + module: &module, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + let entries: Vec<_> = [&uniform, accumulation, &pixels] + .into_iter() + .enumerate() + .map(|(binding, buffer)| wgpu::BindGroupEntry { binding: binding as u32, resource: buffer.as_entire_binding() }) + .collect(); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("adaptive preview normalization"), + layout: &layout, + entries: &entries, + }); + let entries: Vec<_> = [filter_uniform, guides, &pixels, output] + .into_iter() + .enumerate() + .map(|(binding, buffer)| wgpu::BindGroupEntry { binding: binding as u32, resource: buffer.as_entire_binding() }) + .collect(); + let filter_bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("adaptive preview filter"), + layout: &pipelines.filter_layout, + entries: &entries, + }); + Self { _pixels: pixels, uniform, pipeline, bind, filter_bind } + } + fn normalize(&self, task: &Task) -> Result<()> { + let options = task.options.adaptive.ok_or_else(|| super::gpu("missing adaptive preview options"))?; + let pixels = task.request.width * task.request.height; + let mut budget = super::dispatch::Budget::default(); + let mut offset = 0; + while offset < pixels { + task.cancel.check()?; + let count = budget.count(pixels - offset); + let mut bytes = Vec::with_capacity(32); + for word in [task.request.width, task.request.height, task.sample, offset, count, options.pilot_samples, 0, 0] { + bytes.extend_from_slice(&word.to_le_bytes()); + } + task.context.queue.write_buffer(&self.uniform, 0, &bytes); + let started = std::time::Instant::now(); + dispatch(&task.context, &self.pipeline, &self.bind, count)?; + budget.observe(count, started.elapsed()); + offset += count; + } + task.cancel.check() + } +} + fn dispatch(context: &Context, pipeline: &wgpu::ComputePipeline, bind: &wgpu::BindGroup, count: u32) -> Result<()> { context.ensure_available()?; let error_scopes = scopes(&context.device); diff --git a/crates/gpu/src/path/denoise_tests.rs b/crates/gpu/src/path/denoise_tests.rs index 71c49ab34..7749b149a 100644 --- a/crates/gpu/src/path/denoise_tests.rs +++ b/crates/gpu/src/path/denoise_tests.rs @@ -264,11 +264,11 @@ fn gpu_atrous_matches_f64_guides_and_leaves_input_unchanged() { let dummy = make("denoise unused geometry", &[0; 64]); let mut task = Task::new(context.clone(), plane(), request(13), JobOptions::default(), CancelToken::default()).unwrap(); task.sample = 1; - let filter = Resources::new(&context, &task.uniform, [&dummy, &dummy, &dummy, &dummy, &dummy], &raw, bytes.len() as u64).unwrap(); + let filter = Resources::new(&context, &task.uniform, [&dummy, &dummy, &dummy, &dummy, &dummy], &raw, bytes.len() as u64, false).unwrap(); let guide_bytes: Vec = guides.iter().flatten().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); context.queue.write_buffer(&filter._guides, 0, &guide_bytes); let before = task.read_linear_buffer(&raw).unwrap(); - filter.run_filter(&task).unwrap(); + filter.run_filter(&task, false).unwrap(); assert_eq!(before, task.read_linear_buffer(&raw).unwrap()); let actual = task.read_linear_buffer(filter.output()).unwrap(); let mut expected = input; diff --git a/crates/gpu/src/path/effects_tests.rs b/crates/gpu/src/path/effects_tests.rs index faf175faa..53948d88d 100644 --- a/crates/gpu/src/path/effects_tests.rs +++ b/crates/gpu/src/path/effects_tests.rs @@ -154,7 +154,7 @@ fn weathering_reference(@builtin(global_invocation_id) gid:vec3){ let mut task = Task::new(context.clone(), sphere(white()), request(2), JobOptions { aging: stack, ..Default::default() }, CancelToken::default()) .unwrap(); - context.queue.write_buffer(&task.uniform, 0, &task.parameters(4)); + context.queue.write_buffer(&task.uniform, 0, &task.parameters(4).unwrap()); let mut encoder = context.device.create_command_encoder(&Default::default()); { let mut pass = encoder.begin_compute_pass(&Default::default()); @@ -313,3 +313,602 @@ fn saved_aging_identity_reaches_real_gpu_after_cold_reopen() { assert!(session.execute(command, &json!({"setup":"Aging"})).unwrap_err().to_string().contains("hidden")); } } + +#[test] +fn scratch_world_point_is_invariant_when_only_camera_target_crosses_a_noise_period() { + let Some(executor) = executor() else { return }; + let context = executor.context; + let mut stack = AgingStack::default(); + stack + .push(AgingLayer { + kind: AgingKind::Scratches, + scale_mm: 2.0, + strength: 1.0, + coverage: 1.0, + upward_bias: 0.0, + color_srgb: [255, 0, 0], + ..Default::default() + }) + .unwrap(); + let mut images = Vec::new(); + for target_y in [0.0, 8192.0] { + // Every point/translation is dyadic and exactly representable in f32. + // Only the camera's world origin changes; no geometry, RNG or tolerance + // changes can explain a different authored Scratch band at that point. + let reference = format!( + r#" +@compute @workgroup_size(64) +fn scratch_world_reference(@builtin(global_invocation_id) gid:vec3){{ + if gid.x>=16u{{return;}} + let world=vec3(2.0*f32(gid.x%4u)/128.0,2.0*(2.875+1.25*f32(gid.x/4u)),0.0); + let relative=world-vec3(0.0,{target_y:.1},0.0); + let result=aged_surface(triangle(0u),relative,vec3(0.0,0.0,1.0)); + accumulation[gid.x]=vec4(result.base.xyz,1.0); +}} +"# + ); + let shader = format!("{SHADER}\n{reference}"); + let module = + context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(shader.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &module, + entry_point: Some("scratch_world_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut req = request(4); + req.camera.target = solidcore_record::Vec3::new(0.0, target_y, 0.0); + let mut task = + Task::new(context.clone(), sphere(white()), req, JobOptions { aging: stack, ..Default::default() }, CancelToken::default()).unwrap(); + context.queue.write_buffer(&task.uniform, 0, &task.parameters(16).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; + images.push(task.read_linear().unwrap()); + } + assert!(images[0].iter().any(|pixel| pixel[1] < 0.99), "the fixed world-point oracle must include visible Scratch coverage"); + assert_eq!(images[0], images[1], "moving only the camera may not select different world-anchored Scratch bands"); +} + +#[test] +fn scratch_integer_band_matches_independent_f64_boundaries_and_signed_large_cells() { + let Some(executor) = executor() else { return }; + let context = executor.context; + let mut cases = Vec::new(); + for band in -256_i32..=256 { + let point = band as f32 * 1.25; + let bits = point.to_bits(); + let neighbours = if point == 0.0 { + [-1.0 / 1_048_576.0, 0.0, 1.0 / 1_048_576.0] + } else if point > 0.0 { + [f32::from_bits(bits - 1), point, f32::from_bits(bits + 1)] + } else { + [f32::from_bits(bits + 1), point, f32::from_bits(bits - 1)] + }; + for value in neighbours { + for carry in 0..5_u32 { + cases.push([value.to_bits(), carry]); + } + } + } + for point in [-200000000000.0_f32, -1000000000.0, -16777218.0, -5120.25, 4095.9998, 5120.25, 16777218.0, 1000000000.0, 200000000000.0] { + for carry in 0..5_u32 { + cases.push([point.to_bits(), carry]); + } + } + let mut random = 0xa903c717_u32; + while cases.len() < 8192 { + random = random.wrapping_mul(1664525).wrapping_add(1013904223); + let exponent = 110 + (random >> 8) % 54; + let bits = (random & 0x807fffff) | (exponent << 23); + cases.push([bits, random % 5]); + } + let mut bytes = Vec::with_capacity(4 + cases.len() * 8); + bytes.extend((cases.len() as u32).to_le_bytes()); + for case in &cases { + for word in case { + bytes.extend(word.to_le_bytes()); + } + } + let input = context.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("independent Scratch band inputs"), + contents: &bytes, + usage: wgpu::BufferUsages::STORAGE, + }); + let source = format!( + "{SHADER}\n{}", + r#" +@compute @workgroup_size(32) +fn scratch_band_reference(@builtin(global_invocation_id) gid:vec3){ + if gid.x>=geometry[0]{return;} + let point=bitcast(geometry[1u+2u*gid.x]); + let carry=geometry[2u+2u*gid.x]; + accumulation[gid.x]=vec4(f32(aging_scratch_band(point,carry)),f32(aging_floor_mod5120(point)),f32(aging_floor_mod4096(point)),1.0); +} +"# + ); + let module = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &module, + entry_point: Some("scratch_band_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), sphere(white()), request(128), JobOptions::default(), CancelToken::default()).unwrap(); + let bind = context.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: task.accumulation.as_entire_binding() }, + ], + }); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups((cases.len() as u32).div_ceil(32), 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let output = task.read_linear().unwrap(); + for (index, ([point, carry], actual)) in cases.iter().zip(output).enumerate() { + let point = f64::from(f32::from_bits(*point)); + // Independent real-coordinate arithmetic, not shader cell decomposition. + // All inputs are within2e11: f64 resolves the represented f32 fractions + // and the4/5 floor boundaries without the shader's integer algorithm. + let expected = ((point + 4096.0 * f64::from(*carry)) * 4.0 / 5.0).floor().rem_euclid(4096.0) as f32; + assert_eq!(actual[0], expected, "band case={index}, point={point}, carry={carry}"); + assert_eq!(actual[1], point.floor().rem_euclid(5120.0) as f32, "cell5120 case={index}, point={point}"); + assert_eq!(actual[2], point.floor().rem_euclid(4096.0) as f32, "cell4096 case={index}, point={point}"); + } +} + +#[test] +fn scratch_analytic_triangle_hits_keep_world_phase_for_signed_camera_and_world_origins() { + use solidcraft_geom::Mesh; + use solidcraft_render::ProductMesh; + let Some(executor) = executor() else { return }; + let context = executor.context; + let source = format!( + "{SHADER}\n{}", + r#" +@compute @workgroup_size(32) +fn scratch_geometry_reference(@builtin(global_invocation_id) gid:vec3){ + if gid.x>=16u{return;} + let t=triangle(0u); + let bary=vec3(1.0-f32(gid.x%4u+1u)/16.0-f32(gid.x/4u+1u)/16.0,f32(gid.x%4u+1u)/16.0,f32(gid.x/4u+1u)/16.0); + let point=surface_point(t,bary); + let normal=t.n0.xyz; + let hit=trace(point+normal*2.0,-normal,false); + if hit.triangle!=0u {accumulation[gid.x]=vec4(-1.0);return;} + let at=surface_point(t,hit.bary); + let result=aged_surface(t,at,normal); + accumulation[gid.x]=vec4(result.base.xyz,1.0); + accumulation[gid.x+16u]=vec4(hit.distance,hit.bary.yz,1.0); + let q=at*u.aging[0].mask.z+u.aging[0].origin.xyz; + let n=abs(normal);var uv=q.xy; + let phase_code=u32(u.aging[0].origin.w);var carry=(phase_code/5u)%5u; + if n.x>n.y && n.x>n.z {uv=q.yz;carry=phase_code/25u;} else if n.y>n.z {uv=q.xz;carry=phase_code/25u;} + accumulation[gid.x+32u]=vec4(f32(aging_scratch_band(uv.y,carry)),f32(aging_floor_mod4096(uv.x)),f32(aging_floor_mod4096(uv.y)),1.0); +} +"# + ); + let module = 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: &module, + entry_point: Some("scratch_geometry_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut visible = false; + for world in [0.0, 999000000.0, -999000000.0] { + for anchored_origin in [false, true] { + let origin = if anchored_origin { [world; 3] } else { [0.0; 3] }; + for axis in 0..3 { + let (u_axis, v_axis) = match axis { + 0 => (1, 2), + 1 => (0, 2), + _ => (0, 1), + }; + let mut local = [0.0; 3]; + local[v_axis] = 5.4375; + let p0 = Vec3::new(world + local[0], world + local[1], world + local[2]); + let mut along_u = [0.0; 3]; + along_u[u_axis] = 0.25; + let mut along_v = [0.0; 3]; + along_v[v_axis] = 5.0; + let u_edge = Vec3::new(along_u[0], along_u[1], along_u[2]); + let v_edge = Vec3::new(along_v[0], along_v[1], along_v[2]); + let normal = u_edge.cross(v_edge).normalized().unwrap(); + let mesh = Mesh { + positions: vec![p0, p0 + u_edge, p0 + v_edge], + normals: vec![normal; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![ProductMesh { + name: "Scratch analytic triangle".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(white()), + transmission: None, + faces: Vec::new(), + }], + bounds, + }; + let mut stack = AgingStack::default(); + stack + .push(AgingLayer { + kind: AgingKind::Scratches, + scale_mm: 2.0, + strength: 1.0, + coverage: 1.0, + upward_bias: 0.0, + color_srgb: [255, 0, 0], + origin_mm: origin, + ..Default::default() + }) + .unwrap(); + let mut baseline: Option> = None; + for cell in [0_i32, -4, -3, -2, -1, 1, 2, 3, 4] { + let target = + Vec3::new(world + 8192.0 * f64::from(cell), world + 8192.0 * f64::from(2 * cell), world + 8192.0 * f64::from(3 * cell)); + let mut req = request(8); + req.camera.target = target; + let mut task = + Task::new(context.clone(), scene.clone(), req, JobOptions { aging: stack, ..Default::default() }, CancelToken::default()) + .unwrap(); + let parameters = task.parameters(64).unwrap(); + assert_eq!(parameters.len(), PARAMETER_BYTES); + // Thirty-three aligned vec4s precede the aging array. This + // asserts actual host serialization, not just gpu_layers(). + let carry_offset = 33 * 16 + 11 * 4; + let carry = f32::from_le_bytes(parameters[carry_offset..carry_offset + 4].try_into().unwrap()); + let expected = stack.gpu_layers([target.x, target.y, target.z]).unwrap()[0][11]; + assert_eq!(carry.to_bits(), expected.to_bits()); + assert_eq!(¶meters[parameters.len() - 4..], &[0; 4], "the determinant materialization lane remains positive zero"); + context.queue.write_buffer(&task.uniform, 0, ¶meters); + 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(); + for index in 0..16 { + let u = (index % 4 + 1) as f64 / 16.0; + let v = (index / 4 + 1) as f64 / 16.0; + assert_eq!( + pixels[index + 16], + [2.0, u as f32, v as f32, 1.0], + "analytic hit world={world}, origin={origin:?}, axis={axis}, cell={cell}, index={index}" + ); + let point = p0 + u_edge * u + v_edge * v; + let coordinates = [(point.x - origin[0]) / 2.0, (point.y - origin[1]) / 2.0, (point.z - origin[2]) / 2.0]; + let band = (coordinates[v_axis] * 4.0 / 5.0).floor().rem_euclid(4096.0) as f32; + assert_eq!( + pixels[index + 32], + [band, coordinates[u_axis].floor().rem_euclid(4096.0) as f32, coordinates[v_axis].floor().rem_euclid(4096.0) as f32, 1.0], + "independent world phase world={world}, origin={origin:?}, axis={axis}, cell={cell}, index={index}" + ); + } + visible |= pixels[..16].iter().any(|pixel| pixel[1] < 0.99); + if let Some(reference) = &baseline { + assert_eq!(&pixels[..16], reference, "camera-only Scratch change world={world}, origin={origin:?}, axis={axis}, cell={cell}"); + } else { + baseline = Some(pixels[..16].to_vec()); + } + } + } + } + } + assert!(visible, "the analytic world-point fixture must contain visible Scratch coverage"); +} + +#[test] +fn inactive_scratch_layers_preserve_exact_default_pixels_raw_master_stream_and_admission() { + let Some(executor) = executor() else { return }; + let options = JobOptions { samples: 4, max_depth: 3, seed: 21026, linear_exr: true, ..Default::default() }; + let baseline = complete_linear_fixture(executor.context.clone(), options); + let original = admission(&sphere(white()), &request(16), options).unwrap(); + for layer in [ + AgingLayer { kind: AgingKind::Scratches, enabled: false, ..Default::default() }, + AgingLayer { kind: AgingKind::Scratches, strength: 0.0, ..Default::default() }, + AgingLayer { kind: AgingKind::Scratches, coverage: 0.0, ..Default::default() }, + ] { + let mut aging = AgingStack::default(); + aging.push(layer).unwrap(); + let current = JobOptions { aging, ..options }; + assert_eq!( + complete_linear_fixture(executor.context.clone(), current), + baseline, + "inactive Scratch cannot change PNG/raw bytes or the absolute sample stream" + ); + let admitted = admission(&sphere(white()), &request(16), current).unwrap(); + assert_eq!(admitted.estimated_total_bytes, original.estimated_total_bytes); + assert_eq!(admitted.preparation_bytes, original.preparation_bytes); + assert_eq!(admitted.pixel_scratch_bytes, original.pixel_scratch_bytes); + } +} + +#[test] +fn scratch_keeps_visible_analytic_emission_and_its_raw_master_exact() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let source = ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }; + let light = AreaLight { center: [0.0; 3], u: [10.0, 0.0, 0.0], v: [0.0, 10.0, 0.0], radiance: [1.5, 0.5, 0.25] }; + let complete = |aging| { + let options = JobOptions { + samples: 4, + max_depth: 2, + seed: 21026, + linear_exr: true, + aging, + lighting: Some(StudioLighting { + environment: [0.0; 3], + sun: None, + area_lights: AreaLights::new(&[light]).unwrap(), + ..Default::default() + }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), source.clone(), request(8), options, CancelToken::default()).unwrap(); + for _ in 0..5000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + for pixel in task.read_linear().unwrap() { + assert_eq!(pixel, [1.5, 0.5, 0.25, 1.0], "authored analytic-emitter radiance/coverage must remain exact"); + } + return (png, task.take_linear_exr().unwrap()); + } + } + panic!("bounded emission fixture did not complete") + }; + let baseline = complete(AgingStack::default()); + let mut aging = AgingStack::default(); + aging.push(AgingLayer { kind: AgingKind::Scratches, scale_mm: 2.0, strength: 1.0, coverage: 1.0, ..Default::default() }).unwrap(); + assert_eq!(complete(aging), baseline, "an optical surface layer cannot alter visible analytic emission, PNG/raw identity or its sample stream"); +} + +#[test] +fn saved_coat_gpu_capture_reopen_and_actual_render_match_independent_normal_incidence_layer() { + // Independent OpenEXR scanline/FLOAT reader for this fully covered1×1 oracle. + // No production encoder/decoder or optional image codec participates. + fn raw_pixel(bytes: &[u8]) -> [f32; 4] { + fn word(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) + } + fn string<'a>(bytes: &'a [u8], at: &mut usize) -> &'a [u8] { + let start = *at; + *at += bytes[start..].iter().position(|b| *b == 0).unwrap() + 1; + &bytes[start..*at - 1] + } + assert_eq!(word(bytes, 0), 20_000_630); + assert_eq!(word(bytes, 4), 2); + let mut at = 8; + let (mut channels, mut window, mut compression) = (false, false, false); + while bytes[at] != 0 { + let name = string(bytes, &mut at); + let kind = string(bytes, &mut at); + let length = word(bytes, at) as usize; + at += 4; + let data = &bytes[at..at + length]; + at += length; + match name { + b"channels" => { + assert_eq!(kind, b"chlist"); + let mut c = 0; + for expected in [b"A", b"B", b"G", b"R"] { + assert_eq!(string(data, &mut c), expected); + assert_eq!(word(data, c), 2); // FLOAT, never HALF + assert_eq!(&data[c + 4..c + 8], &[0; 4]); + assert_eq!((word(data, c + 8), word(data, c + 12)), (1, 1)); + c += 16; + } + assert_eq!(&data[c..], &[0]); + channels = true; + } + b"dataWindow" => { + assert_eq!(kind, b"box2i"); + assert_eq!(data, &[0; 16]); + window = true; + } + b"compression" => { + assert_eq!(kind, b"compression"); + assert_eq!(data, &[0]); + compression = true; + } + _ => {} + } + } + assert!(channels && window && compression); + at += 1; + let offset = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()) as usize; + assert_eq!((word(bytes, offset), word(bytes, offset + 4)), (0, 16)); + let channel = |i: usize| f32::from_bits(word(bytes, offset + 8 + i * 4)); + [channel(3), channel(2), channel(1), channel(0)] + } + use std::f64::consts::{FRAC_PI_2, PI, SQRT_2}; + let Some(executor) = executor() else { return }; + let mut session = solidcraft_engine::Session::default(); + session.execute("solid.box", &json!({"body_name":"Panel","corner":[-10,-10,-2],"length":20,"width":20,"height":2})).unwrap(); + session + .execute( + "appearance.assign", + &json!({"bodies":["Panel"],"name":"Analytic substrate","color":[128,64,32], + "pbr":{"metallic":0,"roughness":0.5,"dielectric_ior":1}}), + ) + .unwrap(); + let camera = Camera { target: Vec3::ZERO, distance: 1.0, yaw: 0.0, pitch: FRAC_PI_2, roll: 0.0, fov: 0.0, ..Default::default() }; + session + .execute( + "render.coat.bind", + &json!({"name":"Coat","body_index":0,"body_name":"Panel","expected_revision":session.revision, + "coat":{"weight":0.63,"roughness":0.61,"ior":1.7},"set":{"camera":camera,"width":1,"height":1,"job":{"method":"gpu_path","options":{ + "samples":4,"seed":81,"max_depth":1,"linear_exr":true,"lighting":{"environment":[0,0,0],"sun":null,"area_lights":[], + "directional_lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":PI}]}}}}}), + ) + .unwrap(); + let container = solidcraft_io::write_design_container(&session.doc).unwrap(); + session = solidcraft_engine::Session::new(solidcraft_io::read_design(&container).unwrap()); + session.execute("render.scene", &json!({})).unwrap(); + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + session.register_render_job_host(host.clone()).unwrap(); + let document = session.doc.clone(); + let model = session.model.state(); + let evaluation_cache = session.model.cache.clone(); + let world = session.world_state().unwrap(); + let session_camera = session.camera; + let history = (session.revision, session.model.recomputed, session.undo.len(), session.redo.len()); + let checked = session.execute("render.preflight", &json!({"setup":"Coat"})).unwrap(); + assert_eq!(checked["coats"], json!(session.doc.render.setups["Coat"].coats)); + assert_eq!(checked["resolved"]["executor"], "gpu-path"); + assert_eq!(host.admitted_bytes(), 0); + let complete = |session: &mut solidcraft_engine::Session, settings: serde_json::Value| { + let start = session.execute("render.start", &json!({"settings":settings})).unwrap(); + let id: JobId = serde_json::from_value(start["job"].clone()).unwrap(); + let handle = session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{status:?}"); + handle.frame().unwrap().unwrap() + }; + let saved = session.doc.render.setups["Coat"].clone(); + let coated = complete(&mut session, json!(saved)); + let raw = raw_pixel(coated.linear_exr().unwrap()); + assert_eq!(raw[3], 1.0); + // Independent normal-incidence dielectric GGX coat and its documented + // conservative entry/exit attenuation, over an IOR1 Lambert substrate. + let f0 = ((1.7_f64 - 1.0) / (1.7 + 1.0)).powi(2); + let bound = f0 + (1.0 - f0) * (1.0 - 1.0 / SQRT_2).powi(5); + let attenuation = (1.0 - 0.63 * bound).powi(2); + let highlight = 0.63 * f0 / (4.0 * 0.61_f64.powi(4)); + let expected = [128_u8, 64, 32].map(|code| { + let encoded = f64::from(code) / 255.0; + let linear = if encoded <= 0.04045 { encoded / 12.92 } else { ((encoded + 0.055) / 1.055).powf(2.4) }; + linear * attenuation + highlight + }); + for (actual, expected) in raw[..3].iter().zip(expected) { + assert!((f64::from(*actual) - expected).abs() < 2e-6, "GPU coat radiance {actual} vs independent {expected}"); + } + let mut plain = saved.clone(); + plain.coats = Default::default(); + let baseline_check = session.execute("render.preflight", &json!({"settings":plain})).unwrap(); + assert_eq!(checked["admission"], baseline_check["admission"]); + assert_eq!(checked["retained_options_bytes"], baseline_check["retained_options_bytes"]); + let mut zero = saved; + let row = zero.coats.iter().next().unwrap().clone(); + zero.coats + .set( + solidcraft_engine::doc::render_coat::SavedCoat { + coat: solidcraft_engine::doc::render_coat::CoatMaterial { weight: 0.0, ..row.coat }, + ..row + }, + true, + ) + .unwrap(); + let baseline = complete(&mut session, json!(plain)); + let identity = complete(&mut session, json!(zero)); + assert_eq!(baseline.png(), identity.png()); + assert_eq!(baseline.linear_exr().unwrap(), identity.linear_exr().unwrap()); + assert_ne!(coated.linear_exr().unwrap(), baseline.linear_exr().unwrap()); + assert!(Arc::ptr_eq(&document, &session.doc)); + assert!(Arc::ptr_eq(&model, &session.model.state())); + assert!(Arc::ptr_eq(&evaluation_cache, &session.model.cache)); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); + assert_eq!(session.camera, session_camera); + assert_eq!((session.revision, session.model.recomputed, session.undo.len(), session.redo.len()), history); +} + +#[test] +fn saved_gpu_coat_survives_builtin_maps_aging_and_guided_filter_without_changing_the_raw_master() { + let Some(executor) = executor() else { return }; + let mut session = solidcraft_engine::Session::default(); + session.execute("solid.box", &json!({"body_name":"Panel","corner":[-10,-10,-2],"length":20,"width":20,"height":2})).unwrap(); + session + .execute("appearance.assign", &json!({"bodies":["Panel"],"color":[128,64,32],"pbr":{"metallic":0,"roughness":0.5,"dielectric_ior":1}})) + .unwrap(); + let camera = Camera { distance: 10.0, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, fov: 0.0, ..Default::default() }; + session.execute("render.coat.bind",&json!({"name":"Coat","body_index":0,"body_name":"Panel","expected_revision":session.revision, + "coat":{"weight":0.63,"roughness":0.61,"ior":1.7},"set":{"camera":camera,"width":16,"height":16,"job":{"method":"gpu_path","options":{ + "samples":4,"seed":81,"max_depth":2,"linear_exr":true,"denoise":true,"lighting":{"environment":[0,0,0],"sun":null,"area_lights":[], + "directional_lights":[{"direction":[0,0,1],"color":[1,1,1],"intensity":3}]},"aging":[{"kind":"dust","strength":0.2,"coverage":1}]}}}})).unwrap(); + session + .execute("render.library.surface.bind", &json!({"name":"Coat","surface":{"id":"SURF-001","body_index":0,"body_name":"Panel","scale":10}})) + .unwrap(); + let bytes = solidcraft_io::write_design_container(&session.doc).unwrap(); + session = solidcraft_engine::Session::new(solidcraft_io::read_design(&bytes).unwrap()); + session.execute("render.scene", &json!({})).unwrap(); + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + session.register_render_job_host(host).unwrap(); + let document = session.doc.clone(); + let model = session.model.state(); + let evaluation_cache = session.model.cache.clone(); + let world = session.world_state().unwrap(); + let session_camera = session.camera; + let history = (session.revision, session.model.recomputed, session.undo.len(), session.redo.len()); + let complete = |session: &mut solidcraft_engine::Session, setup: solidcraft_engine::doc::render_settings::RenderSetup| { + let reply = session.execute("render.start", &json!({"settings":setup})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{status:?}"); + handle.frame().unwrap().unwrap() + }; + let saved = session.doc.render.setups["Coat"].clone(); + let actual = complete(&mut session, saved.clone()); + let mut uncoated = saved.clone(); + uncoated.coats = Default::default(); + let plain = complete(&mut session, uncoated); + assert_ne!(actual.linear_exr().unwrap(), plain.linear_exr().unwrap(), "maps and aging cannot erase the captured coat"); + let mut unmapped = saved.clone(); + unmapped.surfaces = Default::default(); + let no_map = complete(&mut session, unmapped); + assert_ne!(actual.linear_exr().unwrap(), no_map.linear_exr().unwrap(), "maps still modify the coated substrate"); + let mut unaged = saved.clone(); + let Some(solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options, .. }) = &mut unaged.job else { panic!("GPU") }; + options.aging = Default::default(); + let no_age = complete(&mut session, unaged); + assert_ne!(actual.linear_exr().unwrap(), no_age.linear_exr().unwrap(), "aging still modifies the mapped coat/substrate"); + let mut unfiltered = saved.clone(); + let Some(solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options, .. }) = &mut unfiltered.job else { panic!("GPU") }; + options.denoise = false; + let raw = complete(&mut session, unfiltered); + assert_eq!(actual.linear_exr().unwrap(), raw.linear_exr().unwrap(), "denoising cannot enter coated raw transport"); + assert_eq!(session.doc.render.setups["Coat"], saved); + assert!(Arc::ptr_eq(&document, &session.doc)); + assert!(Arc::ptr_eq(&model, &session.model.state())); + assert!(Arc::ptr_eq(&evaluation_cache, &session.model.cache)); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); + assert_eq!(session.camera, session_camera); + assert_eq!((session.revision, session.model.recomputed, session.undo.len(), session.redo.len()), history); +} diff --git a/crates/gpu/src/path/mod.rs b/crates/gpu/src/path/mod.rs index 2ca6e1a75..fbf741222 100644 --- a/crates/gpu/src/path/mod.rs +++ b/crates/gpu/src/path/mod.rs @@ -1,6 +1,7 @@ //! Native progressive product rendering. Software BVH traversal needs no ray-query //! features. Small measured quanta adapt to the device, then check cancellation. use solidcore_record::Vec3; +use solidcraft_geom::Vec3Geom; #[cfg(test)] use solidcraft_render::job::ToneMap; use solidcraft_render::{ @@ -45,7 +46,9 @@ macro_rules! path_shader { "\n", include_str!("volume.wgsl"), "\n", - include_str!("aging.wgsl") + include_str!("aging.wgsl"), + "\n", + include_str!("punctual.wgsl") ) }; } @@ -54,12 +57,19 @@ const SINGLE_MEDIUM_SHADER: &str = path_shader!(1); const MAX_TRIANGLES: u64 = MAX_GPU_PATH_TRIANGLES; const PATH_WORKGROUP_SIZE: u32 = 32; const SCENE_PIPELINE_CACHE_SLOTS: usize = 5; -const PARAMETER_BYTES: usize = 1184; +const PARAMETER_BYTES: usize = 2080; +// Five vec4s per source; exact device+upload growth is additional to v2's budget. +const PUNCTUAL_PARAMETER_BYTES: u64 = 8 * 80; +// Eight inline 32-byte hard directions: device uniform plus host upload bytes. +const DIRECTIONAL_PARAMETER_BYTES: u64 = 8 * 32; // Eight u32 words: count low, pixel, bounce, sample, code, count high, first-writer flag, spare. -const FAILURE_BYTES: u64 = 32; +const FAILURE_BYTES: u64 = 56; +// Original medium words0..7 remain unchanged; three low/high punctual counters +// occupy words8..13. Both device storage and complete-pass readback are prepaid. +const PUNCTUAL_COUNTER_BYTES: u64 = 24; // A path that cannot classify its glass medium ends there. Isolated paths at the // limits of f32 geometry are tolerated and logged; more than this fraction of all -// paths (any systematic error such as a camera inside glass) fails the job. +// paths (any systematic error such as an ambiguous boundary origin) fails the job. const FAILURE_FRACTION: f64 = 1e-6; const TIMEOUT: Duration = Duration::from_secs(30); // Software Vulkan drivers can compile a pipeline at its first dispatch, which on a cold @@ -449,6 +459,7 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) )); } let camera = request.camera; + validate_punctual_origin(options, camera.target)?; if options.lens.is_some_and(|lens| lens.aperture_radius_mm > 0.0) && (camera.distance < 1e-6 || !(1e-6..=1e6).contains(&(camera.half_height() / camera.distance)) || camera.fov == 0.0) { @@ -476,7 +487,7 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) // Peak preparation: f64 triangles + nodes + serialized upload. After preparation: // 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 } else { 0 }; + let denoise_bytes = pixels * if options.denoise { denoise::BYTES_PER_PIXEL + if options.adaptive.is_some() { 16 } else { 0 } } else { 0 }; admission.pixel_scratch_bytes = pixels * 64 + denoise_bytes; let vertex_bytes = scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::(); let triangle_preparation = @@ -484,7 +495,10 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) admission.preparation_bytes = (triangle_preparation + vertex_bytes * 2 + admission.face_appearances * 8) .max(admission.triangles * 264 + vertex_bytes * 2 + pixels * 32 + denoise_bytes) .max(admission.triangles * 132 + vertex_bytes + admission.pixel_scratch_bytes) - + 1_048_576; + + 1_048_576 + + 2 * DIRECTIONAL_PARAMETER_BYTES + + 2 * PUNCTUAL_PARAMETER_BYTES + + 2 * PUNCTUAL_COUNTER_BYTES; admission.preparation_bytes += request.environment.as_ref().map_or(0, |source| source.admitted_bytes()); if let Some(textures) = &request.textures { textures.validate_scene(scene)?; @@ -508,7 +522,9 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) let photo_bytes = options.finishing.photographic.scratch_bytes(request.width, request.height)?; admission.pixel_scratch_bytes += photo_bytes; admission.preparation_bytes += photo_bytes; - let adaptive_bytes = pixels * if options.adaptive.is_some() { 32 } else { 0 }; + // 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.estimated_total_bytes = admission.geometry_bytes + admission.preparation_bytes; @@ -519,6 +535,9 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) } impl ImageExecutor for Executor { + fn preview_samples(&self, options: JobOptions) -> Option { + options.preview_target().ok() + } fn supports_aging(&self) -> bool { true } @@ -562,7 +581,14 @@ impl ImageExecutor for Executor { fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { self.context.ensure_available()?; let a = admission(scene, request, options)?; - let limit = self.context.device.limits().max_storage_buffer_binding_size; + let device_limits = self.context.device.limits(); + 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 + { + 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::(); let texture_bytes = request.textures.as_ref().map_or(16, |t| textures::packed_bytes(t, scene.meshes.len())); let environment_bytes = @@ -581,7 +607,9 @@ impl ImageExecutor for Executor { } fn begin(&self, scene: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result> { self.admit(&scene, &request, options)?; - Ok(Box::new(Task::new(self.context.clone(), scene, request, options, cancel)?)) + let mut task = Task::new(self.context.clone(), scene, request, options, cancel)?; + task.preview_enabled = true; + Ok(Box::new(task)) } } @@ -612,6 +640,39 @@ fn prepare_environment(request: &ImageRequest, cancel: &CancelToken) -> Result [[f32; 4]; 5] { + let p = Vec3::new(light.position_mm[0], light.position_mm[1], light.position_mm[2]) - origin; + let hi = [p.x as f32, p.y as f32, p.z as f32]; + let lo = [(p.x - f64::from(hi[0])) as f32, (p.y - f64::from(hi[1])) as f32, (p.z - f64::from(hi[2])) as f32]; + let (axis, inner, outer, enabled) = if let Some(cone) = light.cone { + let [x, y, z] = cone.emitted_axis; + let scale = x.abs().max(y.abs()).max(z.abs()); + let v = Vec3::new(x / scale, y / scale, z / scale); + let v = v / v.len(); + ([v.x as f32, v.y as f32, v.z as f32], cone.inner_half_angle_radians.cos() as f32, cone.outer_half_angle_radians.cos() as f32, 1.0) + } else { + ([0.0; 3], 0.0, 0.0, 0.0) + }; + [ + [hi[0], hi[1], hi[2], light.reference_distance_mm as f32], + [lo[0], lo[1], lo[2], light.minimum_distance_mm as f32], + [light.color[0] as f32, light.color[1] as f32, light.color[2] as f32, light.intensity as f32], + [axis[0], axis[1], axis[2], inner], + [outer, enabled, 0.0, 0.0], + ] +} +fn validate_punctual_origin(options: JobOptions, origin: Vec3) -> Result<()> { + if let Some(lighting) = options.lighting { + for light in lighting.punctual_lights.iter() { + light.validate_gpu()?; + if punctual_parameters(light, origin).iter().flatten().any(|v| !v.is_finite()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "point or spot position is outside the GPU camera-relative range")); + } + } + } + Ok(()) +} + struct Task { dispatch_budget: dispatch::Budget, context: Arc, @@ -629,12 +690,16 @@ struct Task { sample: u32, lane: u32, sampling_report: Option, + punctual_diagnostics: std::cell::Cell, volume: [[f32; 4]; 3], aging: [[f32; 20]; 8], photographic: Option, offset: u32, epsilon: f32, png: Option, + encoding_preview: bool, + preview_enabled: bool, + preview: Option, exr_work: Option, bloom_work: Option, exr: Option>, @@ -649,6 +714,8 @@ struct Task { impl Task { fn new(context: Arc, scene: ProductScene, mut request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result { cancel.check()?; + options.validate()?; + 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)?; @@ -704,7 +771,7 @@ impl Task { ); let readback = device.create_buffer(&wgpu::BufferDescriptor { label: Some("path readback"), - size: size + FAILURE_BYTES, + size: size * if options.adaptive.is_some() { 2 } else { 1 } + FAILURE_BYTES, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -723,6 +790,7 @@ impl Task { [&triangles, &nodes, &environment, &texture_buffer, &failures], &accumulation, size, + options.adaptive.is_some(), )?) } else { None @@ -751,12 +819,16 @@ impl Task { sample: 0, lane: 0, sampling_report: None, + punctual_diagnostics: Default::default(), volume, aging, photographic: None, offset: 0, epsilon: upload.epsilon, png: None, + encoding_preview: false, + preview_enabled: false, + preview: None, exr_work: None, bloom_work: None, exr: None, @@ -768,8 +840,11 @@ impl Task { metrics: (bvh_ms, upload_bytes, upload_ms), }) } - fn parameters(&self, count: u32) -> Vec { - let mut bytes = Vec::with_capacity(PARAMETER_BYTES); + fn parameters(&self, count: u32) -> Result> { + let mut bytes = scene::reserved(PARAMETER_BYTES)?; + if bytes.capacity() != PARAMETER_BYTES { + return Err(JobError::new(ErrorCode::LimitExceeded, "GPU parameter upload exceeds its prepaid capacity")); + } for x in [ self.request.width, self.request.height, @@ -805,7 +880,11 @@ impl Task { Vec3::new(lighting.environment[0], lighting.environment[1], lighting.environment[2]), if self.options.lighting.is_some() || self.request.environment.is_some() { 1.0 } else { 0.0 }, ); - scene::vector(&mut bytes, Vec3::ZERO, lighting.area_lights.iter().count() as f32); + scene::vector( + &mut bytes, + Vec3::new(lighting.directional_lights.iter().count() as f64, lighting.punctual_lights.iter().count() as f64, 0.0), + lighting.area_lights.iter().count() as f32, + ); for light in lighting.area_lights.iter() { let vector = |[x, y, z]: [f64; 3]| Vec3::new(x, y, z); scene::vector(&mut bytes, vector(light.center) - camera.target, light.area() as f32); @@ -852,11 +931,30 @@ impl Task { bytes.extend_from_slice(&value.to_le_bytes()); } } + for light in lighting.directional_lights.iter() { + // Validation rejects zero/nonfinite input; scaled normalization preserves + // every bounded CPU directional intent, including tiny finite vectors. + let [x, y, z] = light.direction; + let scale = x.abs().max(y.abs()).max(z.abs()); + let direction = Vec3::new(x / scale, y / scale, z / scale); + scene::vector(&mut bytes, direction / direction.len(), light.intensity as f32); + let [r, g, b] = light.color; + scene::vector(&mut bytes, Vec3::new(r, g, b), 0.0); + } + bytes.resize(PARAMETER_BYTES - PUNCTUAL_PARAMETER_BYTES as usize - 16, 0); + for light in lighting.punctual_lights.iter() { + for vector in punctual_parameters(light, camera.target) { + for value in vector { + bytes.extend_from_slice(&value.to_le_bytes()); + } + } + } + bytes.resize(PARAMETER_BYTES - 16, 0); let weights = self.request.studio_weights.unwrap_or([1.0; 3]); for value in [weights[0] as f32, weights[1] as f32, weights[2] as f32, 0.0] { bytes.extend_from_slice(&value.to_le_bytes()); } - bytes + Ok(bytes) } fn normalization_samples(&self) -> u32 { if self.options.adaptive.is_some() { 1 } else { self.sample } @@ -872,7 +970,7 @@ impl Task { let count = self.dispatch_budget.count(pixels - self.offset); let context = &self.context; let scopes = scopes(&context.device); - context.queue.write_buffer(&self.uniform, 0, &self.parameters(count)); + context.queue.write_buffer(&self.uniform, 0, &self.parameters(count)?); 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 }); @@ -917,13 +1015,24 @@ impl Task { self.read_linear_buffer(&self.accumulation) } fn read_linear_buffer(&self, source: &wgpu::Buffer) -> Result> { + self.read_pixels(source, false) + } + fn read_checkpoint(&self) -> Result> { + self.read_pixels(&self.accumulation, self.options.adaptive.is_some()) + } + fn read_pixels(&self, source: &wgpu::Buffer, adaptive_preview: bool) -> Result> { self.cancel.check()?; let context = &self.context; let scopes = scopes(&context.device); let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("path readback") }); let pixel_bytes = u64::from(self.request.width) * u64::from(self.request.height) * 16; - encoder.copy_buffer_to_buffer(source, 0, &self.readback, 0, pixel_bytes); - encoder.copy_buffer_to_buffer(&self.failures, 0, &self.readback, pixel_bytes, FAILURE_BYTES); + let pilot = adaptive_preview && self.options.adaptive.is_some_and(|options| self.sample <= options.pilot_samples); + encoder.copy_buffer_to_buffer(source, if pilot { pixel_bytes } else { 0 }, &self.readback, 0, pixel_bytes); + if adaptive_preview && !pilot { + encoder.copy_buffer_to_buffer(&self.accumulation, pixel_bytes * 2, &self.readback, pixel_bytes, pixel_bytes); + } + let failure_offset = pixel_bytes * if self.options.adaptive.is_some() { 2 } else { 1 }; + encoder.copy_buffer_to_buffer(&self.failures, 0, &self.readback, failure_offset, FAILURE_BYTES); let submission = context.queue.submit([encoder.finish()]); checked(scopes)?; let slice = self.readback.slice(..); @@ -935,37 +1044,60 @@ impl Task { rx.try_recv().map_err(gpu)?.map_err(gpu)?; let data = slice.get_mapped_range().map_err(gpu)?; let result = (|| { - let (pixels, failures) = data.split_at(data.len().saturating_sub(FAILURE_BYTES as usize)); + let pixels = data.get(..pixel_bytes as usize).ok_or_else(|| gpu("missing image readback"))?; + let failures = data.get(failure_offset as usize..).ok_or_else(|| gpu("missing failure readback"))?; + let budgets = if adaptive_preview && !pilot { + Some(data.get(pixel_bytes as usize..(pixel_bytes * 2) as usize).ok_or_else(|| gpu("missing adaptive preview budgets"))?) + } else { + None + }; let word = |i: usize| failures.as_chunks::<4>().0.get(i).map_or(0, |w| u32::from_le_bytes(*w)); if word(7) != 0 { return Err(JobError::new(ErrorCode::Internal, "nonfinite or negative pilot/production path radiance")); } + self.punctual_diagnostics.set(solidcraft_render::job::PunctualDiagnostics { + near_source: u64::from(word(8)) | (u64::from(word(9)) << 32), + radiance_limit: u64::from(word(10)) | (u64::from(word(11)) << 32), + shadow_offset_crossed: u64::from(word(12)) | (u64::from(word(13)) << 32), + }); let failed = u64::from(word(0)) | (u64::from(word(5)) << 32); if failed > 0 { let pixels = u64::from(self.request.width) * u64::from(self.request.height); - let paths = self - .sampling_report - .as_ref() - .map_or(pixels * u64::from(self.sample.max(1)) * u64::from(self.options.transmission_samples), |report| { - report.production_samples * u64::from(report.transmission_strata) + pixels * u64::from(report.pilot_samples_per_pixel) - }); + let paths = if adaptive_preview { + adaptive::preview_paths(self, budgets)? + } else { + self.sampling_report.as_ref().map_or( + pixels * u64::from(self.sample.max(1)) * u64::from(self.options.transmission_samples), + |report| { + report.production_samples * u64::from(report.transmission_strata) + pixels * u64::from(report.pilot_samples_per_pixel) + }, + ) + }; let detail = format!("{failed} of {paths} paths, first at pixel {}, bounce {}, sample {}, code {}", word(1), word(2), word(3), word(4)); if !medium_failures_tolerated(failed, paths) { return Err(JobError::new( ErrorCode::InvalidScene, format!( - "inconsistent glass medium paths ({detail}): camera must start outside volumes; overlapping solids or more than 16 nested media are unsupported" + "inconsistent glass medium paths ({detail}): ambiguous boundary origin or invalid containment; overlapping solids or more than 16 nested media are unsupported" ), )); } log::warn!("gpu-path ended {detail} at an unclassifiable glass medium"); } let mut values = scene::reserved((self.request.width * self.request.height) as usize)?; - for pixel in pixels.as_chunks::<16>().0 { + for (index, pixel) in pixels.as_chunks::<16>().0.iter().enumerate() { + if index % 4096 == 0 { + self.cancel.check()?; + } + let divisor = if adaptive_preview { + adaptive::preview_divisor(&self.options, self.sample, budgets.and_then(|values| values.get(index * 16..index * 16 + 4)))? + } else { + self.normalization_samples() as f32 + }; let mut value = [0.0; 4]; for (v, bytes) in value.iter_mut().zip(pixel.as_chunks::<4>().0) { - *v = f32::from_le_bytes(*bytes) / self.normalization_samples() as f32; + *v = f32::from_le_bytes(*bytes) / divisor; if !v.is_finite() || *v < 0.0 { return Err(JobError::new(ErrorCode::Internal, "nonfinite or negative path radiance")); } @@ -983,6 +1115,13 @@ impl Task { use solidcraft_render::job::presentation::Display; impl ImageWork for Task { + fn punctual_diagnostics(&self) -> Option { + self.options.lighting.filter(|l| !l.punctual_lights.is_empty()).map(|_| self.punctual_diagnostics.get()) + } + + fn take_preview(&mut self) -> Option { + self.preview.take() + } fn sampling_report(&self) -> Option { self.sampling_report.clone() } @@ -992,8 +1131,25 @@ impl ImageWork for Task { fn step(&mut self, units: usize) -> Result { self.cancel.check()?; self.context.ensure_available()?; + // Direct executor consumers may ignore previews; dropping their old slot + // here never changes accumulated samples or final output. The image host + // takes every publication immediately after this quantum. + self.preview = None; if let Some(png) = &mut self.png { - return png.step(units); + let poll = png.step(units)?; + if self.encoding_preview + && let TaskPoll::Complete(png) = poll + { + self.png = None; + self.encoding_preview = false; + self.preview = Some(solidcraft_render::job::ImageWorkPreview { png, samples_per_pixel: self.sample }); + return Ok(TaskPoll::Pending(Progress { + phase: Phase::Running, + done: u64::from(self.sample), + total: u64::from(self.target_samples()), + })); + } + return Ok(poll); } if let Some(mut task) = self.photographic.take() { if !task.step(units)? { @@ -1004,13 +1160,6 @@ impl ImageWork for Task { self.png = Some(PngTask::new(&self.request, task.finish()?, self.cancel.clone())?); return Ok(TaskPoll::Pending(Progress { phase: Phase::Encoding, done: 0, total: u64::from(self.request.height) })); } - if self.sample < self.target_samples() { - self.dispatch()?; - return Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: u64::from(self.sample), total: u64::from(self.target_samples()) })); - } - if self.sampling_report.is_none() && (self.options.adaptive.is_some() || self.options.transmission_samples != 1) { - self.sampling_report = Some(adaptive::report(self)?); - } if let Some(mut bloom) = self.bloom_work.take() { if !bloom.step(8)? { let done = bloom.completed_lines(); @@ -1021,10 +1170,25 @@ impl ImageWork for Task { let (pixels, glow) = bloom.finish()?; return self.encode_output(pixels, Some(glow)); } + if self.sample < self.target_samples() { + let before = self.sample; + self.dispatch()?; + 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. + self.encoding_preview = true; + let linear = self.read_checkpoint()?; + return self.finish_output(linear); + } + return Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: u64::from(self.sample), total: u64::from(self.target_samples()) })); + } + if self.sampling_report.is_none() && (self.options.adaptive.is_some() || self.options.transmission_samples != 1) { + self.sampling_report = Some(adaptive::report(self)?); + } if self.exr_work.is_none() { log::info!("gpu-path {} spp, {:.3} ms/spp", self.sample, self.started.elapsed().as_secs_f64() * 1000.0 / f64::from(self.sample)); } - let mut linear = if let Some(mut work) = self.exr_work.take() { + let linear = if let Some(mut work) = self.exr_work.take() { if !work.step(4)? { let done = work.completed_rows(); self.exr_work = Some(work); @@ -1042,11 +1206,20 @@ impl ImageWork for Task { } pixels }; + self.finish_output(linear) + } +} +impl Task { + fn finish_output(&mut self, mut linear: Vec<[f32; 4]>) -> Result { if let Some(denoiser) = &self.denoiser { // Diagnose the raw path buffer before filtering: never hide invalid media // or nonfinite radiance by replacing a pixel with neighbouring values. drop(linear); - denoiser.run(self)?; + if self.encoding_preview && self.options.adaptive.is_some() { + denoiser.run_adaptive_preview(self)?; + } else { + denoiser.run(self)?; + } linear = self.read_linear_buffer(denoiser.output())?; } if let Some(options) = self.options.finishing.bloom.filter(|options| options.active()) { @@ -1060,8 +1233,6 @@ impl ImageWork for Task { } self.encode_output(linear, None) } -} -impl Task { fn encode_output(&mut self, linear: Vec<[f32; 4]>, bloom: Option>) -> Result { let encoded_len = linear.len().checked_mul(4).ok_or_else(|| gpu("display byte length overflow"))?; if bloom.as_ref().is_some_and(|pixels| pixels.len() != linear.len()) { diff --git a/crates/gpu/src/path/optical_media_tests.rs b/crates/gpu/src/path/optical_media_tests.rs index 2dd852a67..b4b816724 100644 --- a/crates/gpu/src/path/optical_media_tests.rs +++ b/crates/gpu/src/path/optical_media_tests.rs @@ -137,3 +137,451 @@ fn subsurface_random_walk_preserves_zero_rate_and_matches_energy_and_absorption_ eprintln!("absorbing homogeneous interior RGB={mean:?}"); assert!(mean[0] < average && mean[0] > mean[1] && mean[1] > mean[2] && mean[2] > 0.0); } + +#[test] +fn nested_media_camera_inside_before_opaque_geometry_attenuates_the_visible_emitter_from_the_actual_origin() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let radiance = [2.0, 3.0, 5.0]; + let render = |inside: bool, absorbing: bool, reverse: bool| { + let outer_sigma = if absorbing { Vec3::new(2.0_f64.ln(), 2.0_f64.ln(), 0.0) } else { Vec3::ZERO }; + let inner_sigma = if absorbing { Vec3::new(2.0_f64.ln(), 4.0_f64.ln(), 0.0) } else { Vec3::ZERO }; + // Both index-matched media have no Fresnel/refraction uncertainty. The inner + // medium replaces, rather than adds to, the outer absorption along its part. + let outer = slab_body("Outer origin medium", Vec3::new(1.0, 1.0, 8.0), Vec3::ZERO, 1.0, outer_sigma); + let inner = slab_body("Inner origin medium", Vec3::new(0.5, 0.5, 4.0), Vec3::ZERO, 1.0, inner_sigma); + let opaque_mesh = Mesh { + positions: vec![Vec3::new(-3.5, -3.5, -1.5), Vec3::new(3.5, -3.5, -1.5), Vec3::new(3.5, 3.5, -1.5), Vec3::new(-3.5, 3.5, -1.5)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + let opaque = ProductMesh { + name: "First inside geometry is opaque".into(), + mesh: Arc::new(opaque_mesh), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, 1.0).unwrap()), + transmission: None, + faces: Vec::new(), + }; + let mut image = request(4); + image.camera.fov = 0.0; // Orthographic rays all have the same exact axial lengths. + image.camera.distance = if inside { 0.5 } else { 5.0 }; + image.camera.target = if inside { Vec3::new(0.0, 0.0, -2.0) } else { Vec3::ZERO }; + assert_eq!((outer.mesh.bounds().min.z, outer.mesh.bounds().max.z), (-4.0, 4.0)); + assert_eq!((inner.mesh.bounds().min.z, inner.mesh.bounds().max.z), (-2.0, 2.0)); + assert_eq!((opaque.mesh.bounds().min.z, opaque.mesh.bounds().max.z), (-1.5, -1.5)); + // In the inside case the geometry ray first meets the opaque plane at1.5mm, + // before the inner exit at2mm. The front-facing analytic light at1mm must + // still acquire Beer attenuation from the camera's actual inner medium. + let light = AreaLight { center: [0.0, 0.0, -1.0], u: [3.0, 0.0, 0.0], v: [0.0, 3.0, 0.0], radiance }; + let bounds = outer.mesh.bounds(); + let mut source = ProductScene { bounds, meshes: vec![outer, inner, opaque] }; + if reverse { + source.meshes.reverse(); + } + assert!( + scene::flatten_with_media(&source, Vec3::ZERO, &CancelToken::default(), true).is_ok(), + "opaque backing inside two separated certified closed media is valid input" + ); + let options = JobOptions { + nested_media: true, + samples: 4, + max_depth: 4, + seed: 71, + lighting: Some(StudioLighting { + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + ..Default::default() + }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), source, image, options, CancelToken::default()).unwrap(); + // Orthographic GPU launches use target + back*(4*distance), not Camera::eye. + // Inspect the actual packed primary origin before measuring physical Beer. + let packed = task.parameters(0).unwrap(); + let coordinate = |axis: usize| f64::from(f32::from_le_bytes(packed[32 + axis * 4..36 + axis * 4].try_into().unwrap())); + let actual_origin = Vec3::new(coordinate(0), coordinate(1), coordinate(2)) + task.request.camera.target; + assert_eq!(f32::from_le_bytes(packed[44..48].try_into().unwrap()), 0.0, "this fixture uses the actual orthographic GPU branch"); + assert!((actual_origin.z - if inside { 0.0 } else { 20.0 }).abs() < 1e-14, "actual packed GPU world origin: {actual_origin:?}"); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + task.read_linear().unwrap() + }; + // Controls run before the expected-red inside/absorbing cases. Outside rays + // traverse outer4→2 (2mm), then inner2→-1 (3mm); inside rays see inner0→-1 (1mm). + // Thus absorbing outside RGB is exactly[1/16,3/256,5], inside is[1,3/4,5]. + for (inside, absorbing, reverse) in + [(false, false, false), (true, false, false), (false, true, false), (false, true, true), (true, true, false), (true, true, true)] + { + let expected: [f64; 3] = if !absorbing { + radiance + } else if inside { + [1.0, 0.75, 5.0] + } else { + [1.0 / 16.0, 3.0 / 256.0, 5.0] + }; + for (pixel, value) in render(inside, absorbing, reverse).into_iter().enumerate() { + assert_eq!(value[3], 1.0, "visible analytic emitter has full coverage"); + if !absorbing { + assert_eq!(value, [2.0, 3.0, 5.0, 1.0], "lossless same-IOR control must retain exact source radiance"); + } + for channel in 0..3 { + assert!( + (f64::from(value[channel]) - expected[channel]).abs() < 2e-5, + "inside={inside} absorbing={absorbing} reverse={reverse} pixel={pixel}: {value:?} vs independent Beer {expected:?}" + ); + } + } + } +} + +#[test] +fn gpu_origin_query_uses_only_closed_boundaries_and_refuses_surface_and_silhouette_ambiguity() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let source = [ + SHADER, + r#" +@compute @workgroup_size(1) fn origin_reference() { + let boundary=origin_boundary(u.eye.xyz,u.right.xyz); + var media:array;var count=0u;var valid=boundary.valid; + if valid && boundary.hit.triangle!=0xffffffffu { valid=initialize_media(boundary.hit.triangle,u.right.xyz,&media,&count); } + var sigma=vec3(0.0);var scatter=vec2(0.0);var outer=0.0;var top=0.0; + 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(sigma,select(0.0,1.0,valid)); + accumulation[1]=vec4(outer,top,f32(count),select(0.0,1.0,boundary.hit.triangle!=0xffffffffu)); + accumulation[2]=vec4(scatter,0.0,1.0); +} +"#, + ] + .concat(); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("actual origin classification"), + 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("origin_reference"), + compilation_options: Default::default(), + cache: None, + }); + for reverse in [false, true] { + let mut source = nested(); + source.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.125).unwrap()); + source.meshes[1].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.25).unwrap()); + source.meshes[0].transmission = + Some(source.meshes[0].transmission.unwrap().with_subsurface(Subsurface { scattering_per_mm: 0.1, anisotropy: 0.2 }).unwrap()); + source.meshes[1].transmission = + Some(source.meshes[1].transmission.unwrap().with_subsurface(Subsurface { scattering_per_mm: 0.3, anisotropy: 0.35 }).unwrap()); + let mut opaque = directional_receiver().meshes.remove(0); + for p in &mut Arc::make_mut(&mut opaque.mesh).positions { + p.z = -0.25; + } + opaque.name = "Opaque first hit".into(); + source.meshes.push(opaque); + let mut thin = glass_slab(true).meshes.remove(0); + thin.name = "Outside thin sheet".into(); + for p in &mut Arc::make_mut(&mut thin.mesh).positions { + p.z = 3.0; + } + source.meshes.push(thin); + if reverse { + source.meshes.reverse(); + } + // GPU12's original 1x1/seed71/sample4 ray rounds both projected outer + // top-face triangles onto their shared diagonal. Prove the uploaded + // topology and exact arithmetic independently before querying it. + let upload = scene::flatten_with_media(&source, Vec3::ZERO, &CancelToken::default(), true).unwrap(); + let word = |at: usize| u32::from_le_bytes(upload.geometry[at * 4..at * 4 + 4].try_into().unwrap()); + let vertex = |index: u32| { + let start = word(1) as usize + index as usize * 8; + std::array::from_fn::<_, 3, _>(|axis| f32::from_bits(word(start + axis))) + }; + let tops: Vec<_> = (0..word(0) as usize) + .filter_map(|index| { + let positions = [vertex(word(4 + index * 4)), vertex(word(5 + index * 4)), vertex(word(6 + index * 4))]; + positions.iter().all(|p| p[2] == 2.0).then_some((index, positions)) + }) + .collect(); + assert_eq!(tops.len(), 2); + assert_eq!(word(word(3) as usize + tops[0].0), word(word(3) as usize + tops[1].0), "the actual uploaded face has one certified patch"); + let coefficients = |index: usize| { + let material = word(2) as usize + word(7 + index * 4) as usize * 20; + [6, 8, 9, 10, 11, 16, 17, 18, 19].map(|offset| word(material + offset)) + }; + assert_eq!(coefficients(tops[0].0), coefficients(tops[1].0), "actual IOR/absorption/medium/SSS/parent coefficients agree"); + let origin = [0.0_f32, f32::from_bits(0xb686_37bd), 4.0]; + let direction = [f32::from_bits(0xb69a_9748), f32::from_bits(0xb643_2e36), -1.0]; + // Products of two binary32 values fit exactly in binary64 here. This + // independent determinant rounds their exact difference once to f32. + let determinant = |a: f32, b: f32, c: f32, d: f32| (f64::from(a) * f64::from(b) - f64::from(c) * f64::from(d)) as f32; + let edges: Vec<_> = tops + .iter() + .map(|(_, p)| { + let q = p.map(|v| { + let relative = std::array::from_fn::<_, 3, _>(|axis| v[axis] - origin[axis]); + [ + determinant(relative[0], direction[2], direction[0], relative[2]), + determinant(relative[1], direction[2], direction[1], relative[2]), + ] + }); + let [a, b, c] = q; + let weights = [determinant(b[0], c[1], b[1], c[0]), determinant(c[0], a[1], c[1], a[0]), determinant(a[0], b[1], a[1], b[0])]; + assert_eq!(weights.iter().filter(|&&weight| weight == 0.0).count(), 1, "only the internal edge is zero, not a vertex"); + let zero = weights.iter().position(|&weight| weight == 0.0).unwrap(); + [p[(zero + 1) % 3], p[(zero + 2) % 3]] + }) + .collect(); + assert_eq!(edges[0], [edges[1][1], edges[1][0]], "the shared edge is exact and oppositely directed, not merely two same-patch hits"); + let mut task = Task::new( + context.clone(), + source, + request(2), + JobOptions { nested_media: true, samples: 1, ..Default::default() }, + CancelToken::default(), + ) + .unwrap(); + let epsilon = f64::from(task.epsilon); + let cases = [ + (Vec3::new(0.25, 0.125, 0.0), -Vec3::Z, Some((2, Vec3::new(0.3, 0.4, 0.0), 1.125, 1.25))), + (Vec3::new(0.25, 0.125, 1.5), -Vec3::Z, Some((1, Vec3::new(0.1, 0.2, 0.0), 1.125, 1.125))), + (Vec3::new(0.25, 0.125, 3.5), -Vec3::Z, Some((0, Vec3::ZERO, 0.0, 0.0))), + (Vec3::ZERO, -Vec3::Z, Some((2, Vec3::new(0.3, 0.4, 0.0), 1.125, 1.25))), + (Vec3::new(0.0, 0.0, 1.5), -Vec3::Z, Some((1, Vec3::new(0.1, 0.2, 0.0), 1.125, 1.125))), + (Vec3::new(0.0, 0.0, 3.5), -Vec3::Z, Some((0, Vec3::ZERO, 0.0, 0.0))), + ( + Vec3::new(f64::from(origin[0]), f64::from(origin[1]), f64::from(origin[2])), + Vec3::new(f64::from(direction[0]), f64::from(direction[1]), f64::from(direction[2])), + Some((0, Vec3::ZERO, 0.0, 0.0)), + ), + (Vec3::new(30.0, 0.125, 0.0), Vec3::X, Some((0, Vec3::ZERO, 0.0, 0.0))), + (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(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(-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), + ]; + for (origin, direction, expected) in cases { + 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, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let value = task.read_linear().unwrap(); + if let Some((count, sigma, outer, top)) = expected { + assert_eq!( + value[0], + [sigma.x as f32, sigma.y as f32, sigma.z as f32, 1.0], + "reverse={reverse} origin={origin:?} direction={direction:?}" + ); + assert_eq!(value[1][..3], [outer as f32, top as f32, count as f32]); + let scatter = match count { + 2 => [0.3_f32, 0.35], + 1 => [0.1, 0.2], + _ => [0.0, 0.0], + }; + assert_eq!(value[2][..2], scatter, "initial-medium classification preserves the actual homogeneous random-walk parameters"); + } else { + assert_eq!( + value[0][3], 0.0, + "an actual boundary/silhouette cannot certify an arbitrary incident normal: reverse={reverse} origin={origin:?} direction={direction:?}" + ); + } + } + } +} + +fn origin_emitter_fixture() -> ProductScene { + let mut glass = slab_body("Pupil medium", Vec3::new(0.5, 1.0, 4.0), Vec3::new(-5.0, 0.0, 0.0), 1.0, Vec3::new(2.0_f64.ln(), 4.0_f64.ln(), 0.0)); + // The exact uploaded box is x[-10,0], y[-10,10], z[-2,2]. + assert_eq!((glass.mesh.bounds().min.x, glass.mesh.bounds().max.x), (-10.0, 0.0)); + let mut opaque = directional_receiver().meshes.remove(0); + opaque.name = "Opaque behind emitter".into(); + for p in &mut Arc::make_mut(&mut opaque.mesh).positions { + p.z = -1.5; + } + opaque.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, 1.0).unwrap()); + glass.transmission = Some(Transmission::new(Vec3::new(2.0_f64.ln(), 4.0_f64.ln(), 0.0), None).unwrap()); + ProductScene { bounds: glass.mesh.bounds(), meshes: vec![glass, opaque] } +} +#[test] +fn gpu_actual_sampled_pupils_normalize_initial_beer_before_visible_emission_without_new_variates() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let mut image = request(1); + image.camera.target = Vec3::new(0.25, 0.0, -0.5); + image.camera.distance = 0.5; + image.camera.fov = 0.2; + let samples = 16; + let seed = 71; + let lens = solidcraft_render::job::ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 2.0 }; + let radiance = [2.0, 3.0, 5.0]; + let light = AreaLight { center: [0.0, 0.0, -1.0], u: [3.0, 0.0, 0.0], v: [0.0, 3.0, 0.0], radiance }; + let options = JobOptions { + nested_media: true, + samples, + seed, + max_depth: 8, + lens: Some(lens), + lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap(), ..Default::default() }), + ..Default::default() + }; + let mut expected = [0.0; 3]; + let mut inside = 0; + let mut outside = 0; + let (right, up, back) = image.camera.basis(); + for ordinal in 0..samples { + let mut rng = ordinal.wrapping_mul(0x9e3779b9) ^ seed; + let mut random = || { + rng = rng.wrapping_mul(747796405).wrapping_add(2891336453); + let word = ((rng >> ((rng >> 28) + 4)) ^ rng).wrapping_mul(277803737); + f64::from(((word >> 22) ^ word) >> 8) / 16777216.0 + }; + let x = random(); + let y = random(); + let u = random(); + let v = random(); + let displacement = + (right * (std::f64::consts::TAU * v).cos() + up * (std::f64::consts::TAU * v).sin()) * (lens.aperture_radius_mm * u.sqrt()); + let origin = image.camera.eye() + displacement; + let pinhole = image.camera.ray(x, y, 1.0, 1.0).1; + let aimed = pinhole * (lens.focus_distance_mm / pinhole.dot(-back)) - displacement; + let direction = aimed / aimed.len(); + if origin.x < 0.0 { + inside += 1; + } else { + outside += 1; + } + let end = (-1.0 - origin.z) / direction.z; + assert!(end > 0.0); + let mut enter = f64::NEG_INFINITY; + let mut exit = f64::INFINITY; + for (p, d, lo, hi) in [(origin.x, direction.x, -10.0, 0.0), (origin.y, direction.y, -10.0, 10.0), (origin.z, direction.z, -2.0, 2.0)] { + if d == 0.0 { + if p < lo || p > hi { + exit = f64::NEG_INFINITY; + break; + } + } else { + let a = (lo - p) / d; + let b = (hi - p) / d; + enter = enter.max(a.min(b)); + exit = exit.min(a.max(b)); + } + } + let length = (exit.min(end) - enter.max(0.0)).max(0.0); + for (channel, sigma) in [2.0_f64.ln(), 4.0_f64.ln(), 0.0].into_iter().enumerate() { + expected[channel] += radiance[channel] * (-sigma * length).exp() / f64::from(samples); + } + } + assert!(inside > 0 && outside > 0, "one actual pupil disk must exercise both initial media"); + let render = |absorbing: bool| { + let mut source = origin_emitter_fixture(); + if !absorbing { + source.meshes[0].transmission = Some(clear_glass()); + } + let mut task = Task::new(executor.context.clone(), source, image.clone(), options, CancelToken::default()).unwrap(); + let packed = task.parameters(0).unwrap(); + let coordinate = |axis: usize| f64::from(f32::from_le_bytes(packed[32 + axis * 4..36 + axis * 4].try_into().unwrap())); + let actual_eye = Vec3::new(coordinate(0), coordinate(1), coordinate(2)) + image.camera.target; + assert_eq!(f32::from_le_bytes(packed[44..48].try_into().unwrap()), 1.0, "pupil fixture uses the actual perspective GPU branch"); + assert!(actual_eye.dist(image.camera.eye()) < 1e-12, "the independent per-pupil oracle starts at the actual packed perspective eye"); + while task.sample < samples { + task.complete_sample().unwrap(); + } + task.read_linear().unwrap()[0] + }; + assert_eq!(render(false), [2.0, 3.0, 5.0, 1.0], "same-IOR lossless pupil paths preserve exact source radiance"); + let actual = render(true); + assert_eq!(actual[3], 1.0); + for (a, e) in actual[..3].iter().zip(expected) { + assert!((f64::from(*a) - e).abs() < 2e-5, "actual per-pupil origin and unchanged RNG: {actual:?} vs{expected:?}"); + } +} +#[test] +fn gpu_boundary_origins_refuse_through_existing_diagnostics_and_non_nested_outside_pixels_stay_exact() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + for z in [-2.0, 2.0] { + let mut image = request(4); + image.camera.fov = 0.0; + image.camera.distance = 0.5; + image.camera.target = Vec3::new(-5.0, 0.0, z - 2.0); + let mut task = Task::new( + executor.context.clone(), + origin_emitter_fixture(), + image, + JobOptions { nested_media: true, samples: 1, ..Default::default() }, + CancelToken::default(), + ) + .unwrap(); + let packed = task.parameters(0).unwrap(); + let actual_z = f64::from(f32::from_le_bytes(packed[40..44].try_into().unwrap())) + task.request.camera.target.z; + assert_eq!(actual_z, z, "actual packed orthographic origin lies on the selected boundary"); + task.complete_sample().unwrap(); + let error = task.read_linear().unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("code 4")); + } + let light = AreaLight { center: [-5.0, 0.0, -1.0], u: [3.0, 0.0, 0.0], v: [0.0, 3.0, 0.0], radiance: [2.0, 3.0, 5.0] }; + let mut image = request(4); + image.camera.fov = 0.0; + image.camera.target = Vec3::new(-5.0, 0.0, 0.0); + image.camera.distance = 5.0; + let render = |nested_media| { + let options = JobOptions { + nested_media, + samples: 4, + max_depth: 4, + seed: 71, + lighting: Some(StudioLighting { + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + ..Default::default() + }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), origin_emitter_fixture(), image.clone(), options, CancelToken::default()).unwrap(); + let packed = task.parameters(0).unwrap(); + assert_eq!( + f64::from(f32::from_le_bytes(packed[40..44].try_into().unwrap())) + image.camera.target.z, + 20.0, + "the established outside ortho origin is not generic Camera::eye" + ); + while task.sample < options.samples { + task.complete_sample().unwrap(); + } + task.read_linear().unwrap() + }; + let legacy = render(false); + assert!(legacy.iter().all(|p| p[0] > 0.0 && p[3] == 1.0)); + assert_eq!(legacy, render(true), "the extra opt-in query consumes no RNG and leaves an already supported outside path byte-identical"); +} diff --git a/crates/gpu/src/path/path.wgsl b/crates/gpu/src/path/path.wgsl index feae01193..6439dc8fd 100644 --- a/crates/gpu/src/path/path.wgsl +++ b/crates/gpu/src/path/path.wgsl @@ -11,6 +11,8 @@ struct Triangle { }; struct Node { lo: vec3, first: u32, hi: vec3, count: u32 }; struct AreaLight { center: vec4, u: vec4, v: vec4, radiance: vec4 }; +struct DirectionalLight { direction: vec4, color: vec4 }; +struct PunctualLight { position: vec4, position_low: vec4, color: vec4, axis: vec4, cone: vec4 }; struct Params { // width, height, sample index, pixel offset image: vec4, @@ -20,7 +22,7 @@ struct Params { // ray epsilon, test environment radiance, studio scale, reserved lighting: vec4, environment: vec4, // RGB radiance, enabled flag - light_count: vec4, // w: rectangle count + light_count: vec4, // x: hard directional count, y: point/spot count, w: rectangle count area_lights: array, environment_map: vec4, // cosine rotation, sine rotation, intensity, enabled sun_direction: vec4, // normalized toward sun, cosine angular radius @@ -31,6 +33,8 @@ struct Params { volume_max: vec4, // camera-relative bounds maximum, HG mean cosine volume_albedo: vec4, // RGB single-scattering albedo, reserved aging: array, + directional_lights: array, + punctual_lights: array, studio_weights: vec4, }; @@ -45,7 +49,7 @@ struct EnvironmentData { header: vec4, texels: array }; // Two atomic words count jobs with more than 2^32 paths without wrapping to zero. @group(0) @binding(6) var failures: array>; // Codes: 1 escaped inside a medium, 2 exit with no medium, 3 exit from another -// medium, 4 entry while inside a medium or beyond 16 nested media. +// medium, 4 ambiguous origin/certificate, invalid entry or beyond16 nested media. fn medium_failure(radiance: vec3, coverage: f32, pixel: u32, bounce: u32, code: u32) -> vec4 { if atomicAdd(&failures[0],1u)==0xffffffffu { atomicAdd(&failures[5],1u); } if atomicExchange(&failures[6],1u)==0u { @@ -333,10 +337,70 @@ fn triangle_ahead_precise(t: Triangle, o: vec3, o_low: vec3, d: vec3(0.0))&((lo>vec3(0.0))|(hi(0.0)))) { return false; } return true; } +// The host keeps studio_weights.w at positive zero. The integer dependency +// materializes scalar intermediates and prevents floating reassociation. +fn split_materialize(value: f32) -> f32 { + return bitcast(bitcast(value)^bitcast(u.studio_weights.w)); +} +struct SplitScaled { value: f32, exponent: i32 }; +fn split_scaled(value: f32) -> SplitScaled { + let bits=bitcast(value);let exponent=(bits>>23u)&255u;let fraction=bits&0x7fffffu; + if (bits&0x7fffffffu)==0u || exponent==255u { return SplitScaled(value,0); } + let sig=fraction|select(0u,0x800000u,exponent!=0u); + let shift=countLeadingZeros(sig)-8u; + let normalized=(bits&0x80000000u)|0x3f800000u|((sig<(normalized),select(-126,i32(exponent)-127,exponent!=0u)-i32(shift)); +} +fn split_add(a: f32, b: f32) -> f32 { + return bitcast(fp_add_bits(bitcast(a),bitcast(b))); +} +// With normalized operands, all four12-by12-bit partial products and these +// subtractions are exactly representable, even if p chose either faithful neighbor. +fn split_product(a: f32, b: f32) -> vec2 { + let ah=bitcast(bitcast(a)&0xfffff000u);let al=split_materialize(a-ah); + let bh=bitcast(bitcast(b)&0xfffff000u);let bl=split_materialize(b-bh); + let p=split_materialize(a*b); + let e1=split_materialize(p-ah*bh); + let e2=split_materialize(e1-al*bh); + let e3=split_materialize(e2-ah*bl); + return vec2(p,split_materialize(al*bl-e3)); +} +fn split_two_sum(a: f32, b: f32) -> vec2 { + let swap=abs(a)(sum,split_materialize(small-delta)); +} +fn split_rescale(value: f32, exponent: i32) -> f32 { + if value==0.0 { return value; } + let scaled=split_scaled(value);let combined=scaled.exponent+exponent+1; + if combined>128 { return bitcast((bitcast(value)&0x80000000u)|0x7f800000u); } + return ldexp(scaled.value*0.5,combined); +} +fn split_difference_products(a: f32, b: f32, c: f32, d: f32) -> f32 { + let aa=split_scaled(a);let bb=split_scaled(b);let cc=split_scaled(c);let dd=split_scaled(d); + let p=split_product(aa.value,bb.value);let q=split_product(cc.value,dd.value); + let ep=aa.exponent+bb.exponent;let eq=cc.exponent+dd.exponent; + if p.x==0.0 { return split_rescale(-split_add(q.x,q.y),eq); } + if q.x==0.0 { return split_rescale(split_add(p.x,p.y),ep); } + let exponent=max(ep,eq); + let pp=ldexp(p,vec2(ep-exponent));let qq=ldexp(q,vec2(eq-exponent)); + let high=split_materialize(pp.x-qq.x); + let tail=split_two_sum(pp.y,-qq.y); + if high==0.0 { return split_rescale(tail.x,exponent); } + if tail.x==0.0 { return split_rescale(high,exponent); } + let total=split_two_sum(high,tail.x); + return split_rescale(split_add(total.x,split_add(total.y,tail.y)),exponent); +} fn difference_products(a: f32, b: f32, c: f32, d: f32) -> f32 { - let cd = c*d; - let error = fma(-c,d,cd); - return fma(a,b,-cd)+error; + let ab=a*b;let cd=c*d; + // Four cancelled leading bits select the compensated method; this is an + // arithmetic strategy, not a change to any intersection tolerance. + if abs(ab-cd)>max(abs(ab),abs(cd))*(1.0/16.0) { + let error=fma(-c,d,cd); + return fma(a,b,-cd)+error; + } + return split_difference_products(a,b,c,d); } struct Hit { distance: f32, triangle: u32, bary: vec3 }; // A closed continuation that leaves its producing triangle at a shared edge or @@ -362,15 +426,17 @@ fn tie_preferred(t: Triangle, d: vec3, inside: bool) -> bool { return front!=inside; } fn trace_precise(o: vec3, o_low: vec3, d: vec3, any_hit: bool, excluded: u32, minimum: f32, inside: bool) -> Hit { + if all(o_low==vec3(0.0)) { return trace_ordered_within(o,d,any_hit,excluded,minimum,inside,FAR,-1.0); } return trace_precise_within(o,o_low,d,any_hit,excluded,minimum,inside,FAR,-1.0); } // Only hits closer than `limit` are reported, and nodes beyond it are culled. // An opaque or shadow-blocking hit closer than `blocker` ends traversal at once: // a shadow connection is blocked whichever such hit is closest. fn trace_precise_within(o: vec3, o_low: vec3, d: vec3, any_hit: bool, excluded: u32, minimum: f32, inside: bool, limit: f32, blocker: f32) -> Hit { - // Dispatch once before traversal. Ordinary rays keep the original lean BVH - // loop, without precision-helper branches inside every candidate/node test. - if all(o_low==vec3(0.0)) { return trace_ordered_within(o,d,any_hit,excluded,minimum,inside,limit,blocker); } + // One shared walk bounds native inlining for primary, surface and volume + // connections. The ordinary branch retains its original candidate arithmetic; + // only a retained low origin selects the compensated candidate policy. + let has_origin_residual=any(o_low!=vec3(0.0)); var hit = Hit(limit, 0xffffffffu, vec3(0.0)); // Project every candidate into the same ray-aligned 2D coordinate system. // Shared edges then use identical products with opposite signs, avoiding the @@ -390,10 +456,12 @@ fn trace_precise_within(o: vec3, o_low: vec3, d: vec3, any_hit: b // than the near radius uses ordinary arithmetic from it: that error cannot // reorder such a hit, but it can move the ray across an edge, so decisions // within the error bound of an edge or bound fall back to the exact path. - let rounded=o+o_low; + var rounded=o; + if has_origin_residual { rounded=o+o_low; } let scale=max(max(abs(rounded.x),max(abs(rounded.y),abs(rounded.z))),1.0); let origin_error=scale*(1.0/1048576.0); - let pad=u.lighting.x+origin_error; + var pad=u.lighting.x; + if has_origin_residual { pad=u.lighting.x+origin_error; } var source: Triangle; if excluded!=0xffffffffu { source=triangle(excluded); } let near_radius=scale*(1.0/256.0); @@ -431,6 +499,32 @@ fn trace_precise_within(o: vec3, o_low: vec3, d: vec3, any_hit: b // IDs join only connected, exactly coplanar uploaded f32 triangles // of one body; curved facets and other bodies remain candidates. if excluded!=0xffffffffu && geometry[geometry[3]+i]==geometry[geometry[3]+excluded] { continue; } + // The ordinary source uses exactly the former ordered candidate + // branch. Sharing only the node walk avoids another inlined BVH. + if !has_origin_residual { + let t = triangle(i); + if !triangle_ahead(t,o,d) { continue; } + let pa=t.p0.xyz-o; let pb=t.p1.xyz-o; let pc=t.p2.xyz-o; + let a=vec2(pa[kx]-shear.x*pa[kz],pa[ky]-shear.y*pa[kz]); + let b=vec2(pb[kx]-shear.x*pb[kz],pb[ky]-shear.y*pb[kz]); + let c=vec2(pc[kx]-shear.x*pc[kz],pc[ky]-shear.y*pc[kz]); + let weights=vec3(difference_products(b.x,c.y,b.y,c.x),difference_products(c.x,a.y,c.y,a.x),difference_products(a.x,b.y,a.y,b.x)); + if any(weights(0.0)) && any(weights>vec3(0.0)) { continue; } + let det=weights.x+weights.y+weights.z; + if det==0.0 { continue; } + // Retain all three directly evaluated weights: 1-u-v can erase a + // small corner clearance when the other two weights sum to one. + let bary=weights/det; + let depth=surface_ray_depth(t,bary,o,kz); + let distance=depth*shear.z; + let key=depth*order; + if excluded!=0xffffffffu && repeated_crossing(t,source,d,inside,distance,origin_error) { continue; } + if distance > minimum && distance < limit && (key < best || (key == best && tie_preferred(t,d,inside))) { + hit = Hit(distance,i,bary); best=key; + if any_hit || (distance < blocker && (t.base.w<=0.0 || t.coat.w<=0.0)) { return hit; } + } + continue; + } let t = triangle(i); let lo=min(t.p0.xyz,min(t.p1.xyz,t.p2.xyz)); let hi=max(t.p0.xyz,max(t.p1.xyz,t.p2.xyz)); @@ -570,6 +664,144 @@ fn trace_ordered_within(o: vec3, d: vec3, any_hit: bool, excluded: u32 fn trace(o: vec3, d: vec3, any_hit: bool) -> Hit { return trace_bounded(o,d,any_hit,0xffffffffu,u.lighting.x); } +// Origin classification is separate from visible/shadow traversal. A nearer +// opaque triangle, thin sheet or analytic emitter cannot hide a closed boundary. +// This uses the existing uploaded-f32 intersection domain and no launch epsilon: +// exact numeric contacts, silhouette edges/vertices and tied nearest boundaries +// are ambiguous certificates, not an invitation to guess a containing medium. +struct OriginBoundary { hit: Hit, valid: bool }; +struct OriginEdge { start: vec3, end: vec3 }; +fn origin_edge(t: Triangle, zero: u32) -> OriginEdge { + if zero==0u { return OriginEdge(t.p1.xyz,t.p2.xyz); } + if zero==1u { return OriginEdge(t.p2.xyz,t.p0.xyz); } + return OriginEdge(t.p0.xyz,t.p1.xyz); +} +fn origin_internal_edge(a: Triangle, ai: u32, az: u32, b: Triangle, bi: u32, bz: u32, d: vec3) -> bool { + if geometry[geometry[3]+ai]!=geometry[geometry[3]+bi] { return false; } + // The host patch proves connected exact uploaded-f32 coplanarity in one + // body. Still require the same actual region/parent/medium coefficients. + if a.parameters.z!=b.parameters.z || any(a.optics!=b.optics) || any(a.interior!=b.interior) { return false; } + let ae=origin_edge(a,az);let be=origin_edge(b,bz); + if any(ae.start!=be.end) || any(ae.end!=be.start) { return false; } + let at=dot(cross(a.p1.xyz-a.p0.xyz,a.p2.xyz-a.p0.xyz),d); + let bt=dot(cross(b.p1.xyz-b.p0.xyz,b.p2.xyz-b.p0.xyz),d); + return at!=0.0 && bt!=0.0 && (at<0.0)==(bt<0.0); +} +fn origin_on_boundary(t: Triangle, o: vec3) -> bool { + let lo=min(t.p0.xyz,min(t.p1.xyz,t.p2.xyz)); + let hi=max(t.p0.xyz,max(t.p1.xyz,t.p2.xyz)); + if any(ohi) { return false; } + let normal=cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz); + if all(normal==vec3(0.0)) { return true; } + if dot(normal,o-t.p0.xyz)!=0.0 { return false; } + var axis=0u; + if abs(normal.y)>abs(normal.x) { axis=1u; } + if abs(normal.z)>abs(normal[axis]) { axis=2u; } + let x=(axis+1u)%3u;let y=(x+1u)%3u; + let pa=t.p0.xyz-o;let pb=t.p1.xyz-o;let pc=t.p2.xyz-o; + let a=vec2(pa[x],pa[y]);let b=vec2(pb[x],pb[y]);let c=vec2(pc[x],pc[y]); + let weights=vec3(difference_products(b.x,c.y,b.y,c.x),difference_products(c.x,a.y,c.y,a.x),difference_products(a.x,b.y,a.y,b.x)); + return !(any(weights(0.0)) && any(weights>vec3(0.0))); +} +fn origin_boundary(o: vec3, d: vec3) -> OriginBoundary { + var hit=Hit(FAR,0xffffffffu,vec3(0.0)); + var best=FAR; + var ambiguous=FAR; + var edge_index=3u; + var edge_count=0u; + var kz=0u; + if abs(d.y)>abs(d.x) { kz=1u; } + if abs(d.z)>abs(d[kz]) { kz=2u; } + let kx=(kz+1u)%3u;let ky=(kx+1u)%3u; + let inverse_depth=1.0/d[kz]; + let order=select(-1.0,1.0,d[kz]>0.0); + // The same host-built depth<=30 BVH bounds both visible and origin queries. + // These fixed arrays replace no image/buffer and require no storage upload. + var stack: array; + var entry: array; + 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); } + stack[0]=0u;var size=1u; + loop { + if size==0u { break; } + size-=1u; + if entry[size]>hit.distance { continue; } + let node=nodes[stack[size]]; + if node.count==0u { + if size+2u>32u { return OriginBoundary(hit,false); } + let left=box_entry_padded(nodes[node.first],o,d,hit.distance,u.lighting.x); + let right=box_entry_padded(nodes[node.first+1u],o,d,hit.distance,u.lighting.x); + var near_child=node.first;var near_entry=left; + var far_child=node.first+1u;var far_entry=right; + if right>=0.0 && (left<0.0 || right=0.0 { stack[size]=far_child;entry[size]=far_entry;size+=1u; } + if near_entry>=0.0 { stack[size]=near_child;entry[size]=near_entry;size+=1u; } + continue; + } + for(var i=node.first;i=0.0 { continue; } + // Check the actual point before the forward-ray fast rejection. A + // boundary origin moving away must not be assigned vacuum by it. + if origin_on_boundary(t,o) { return OriginBoundary(hit,false); } + if !triangle_ahead(t,o,d) { continue; } + let pa=t.p0.xyz-o;let pb=t.p1.xyz-o;let pc=t.p2.xyz-o; + // Keep the ray projection homogeneous: a rounded d[kx]/d[kz] + // must not turn an exact uploaded-f32 edge tangent into a crossing. + // All projected coordinates share d[kz], so barycentrics are invariant. + let a=vec2(difference_products(pa[kx],d[kz],d[kx],pa[kz]),difference_products(pa[ky],d[kz],d[ky],pa[kz])); + let b=vec2(difference_products(pb[kx],d[kz],d[kx],pb[kz]),difference_products(pb[ky],d[kz],d[ky],pb[kz])); + let c=vec2(difference_products(pc[kx],d[kz],d[kx],pc[kz]),difference_products(pc[ky],d[kz],d[ky],pc[kz])); + let weights=vec3(difference_products(b.x,c.y,b.y,c.x),difference_products(c.x,a.y,c.y,a.x),difference_products(a.x,b.y,a.y,b.x)); + if any(weights(0.0)) && any(weights>vec3(0.0)) { continue; } + let det=weights.x+weights.y+weights.z; + if det==0.0 { continue; } + let bary=weights/det; + let depth=surface_ray_depth(t,bary,o,kz); + let distance=depth*inverse_depth; + let key=depth*order; + if distance==0.0 { return OriginBoundary(hit,false); } + if distance<0.0 || distance>=FAR { continue; } + let transverse=dot(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz),d); + let zeros=select(0u,1u,weights.x==0.0)+select(0u,1u,weights.y==0.0)+select(0u,1u,weights.z==0.0); + // A vertex needs a complete planar fan proof, which this query does + // not infer. Tangencies and actual boundary origins stay refusals. + if zeros>1u || transverse==0.0 { + ambiguous=min(ambiguous,key); + continue; + } + var zero=3u; + if zeros==1u { + if weights.x==0.0 { zero=0u; } + else if weights.y==0.0 { zero=1u; } + else { zero=2u; } + } + if key==best { + // Only the exact opposite directed edge of two certified + // coplanar triangles proves an internal triangulation edge. + // Two arbitrary same-patch hits, perimeter edges and key-near + // interfaces are insufficient; there is no distance tolerance. + if edge_count==1u && zero<3u && origin_internal_edge(triangle(hit.triangle),hit.triangle,edge_index,t,i,zero,d) { + edge_count=2u; + } else { ambiguous=min(ambiguous,key); } + } + if key) -> u32 { var anchor=0u; if bary.y>bary.x { anchor=1u; } @@ -725,19 +957,24 @@ const FIXED_LIGHTS = array,3>(vec4(0.6,0.0,0.8,3.0),vec4(-0. // Next-event estimation for every light source family through ONE shadow-ray call site, like // volume_direct. Native compilers inline each call of the BVH walk; one walk per source family // made `main` too large for NVIDIA's Vulkan compiler (#6705). Studio lighting visits every area -// light, then the environment, then the sun, drawing random numbers in that order; without it +// light, then the environment, then the sun, drawing random numbers in that order; hard +// directions follow without consuming random numbers. Without explicit lighting // the three fixed lights are used. -fn direct_light(t: Triangle, position: vec3, o: vec3, n: vec3, geometric: vec3, v: vec3, remaining: u32, rng: ptr) -> vec3 { +fn direct_light(t: Triangle, position: vec3, physical: PrecisePoint, o: vec3, n: vec3, geometric: vec3, v: vec3, remaining: u32, rng: ptr) -> vec3 { var result = vec3(0.0); let opaque = 1.0-t.base.w; let studio = u.environment.w > 0.0; if studio && opaque<=0.0 { return result; } let area_count = u32(u.light_count.w); - let count = select(3u, area_count+2u, studio); + let count = select(3u, area_count+2u+u32(u.light_count.x)+u32(u.light_count.y), studio); for (var source=0u; source(0.0,0.0,1.0),vec3(0.0),0.0); var shadow_direction = vec3(0.0,0.0,1.0); var shadow_distance = FAR; + var shadow_origin = o; + var shadow_origin_low = vec3(0.0); + var punctual = false; + var physical_distance = FAR; if !studio { let light = FIXED_LIGHTS[source]; if u.lighting.z <= 0.0 || dot(geometric,light.xyz)<=0.0 || dot(n,light.xyz)<=0.0 { continue; } @@ -756,25 +993,59 @@ fn direct_light(t: Triangle, position: vec3, o: vec3, n: vec3, ge if u.environment_map.w<=0.0 && !any(u.environment.xyz>vec3(0.0)) { continue; } sample = env_sample(rng); shadow_direction = sample.direction; - } else { + } else if source==area_count+1u { if u.sun_radiance.w<=0.0 { continue; } sample = sun_sample(rng); shadow_direction = sample.direction; + } else if sourcevec3(0.0)) { continue; } + sample = EnvironmentSample(light.direction.xyz,light.color.xyz*light.direction.w,1.0); + shadow_direction = sample.direction; + } else { + punctual = true; + let light = u.punctual_lights[source-area_count-2u-u32(u.light_count.x)]; + let value = punctual_sample(light,physical); + if value.omitted!=0u { continue; } + sample = EnvironmentSample(value.direction,value.radiance,1.0); + physical_distance = value.distance; + var contribution=vec3(0.0); + if dot(n,sample.direction)>0.0 && dot(geometric,sample.direction)>0.0 { + contribution=brdf(t,n,v,sample.direction)*(opaque*dot(n,sample.direction)*sample.radiance); + } + 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)); + 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); + shadow_distance=length(connection); + if !(shadow_distance>0.0) || dot(connection,sample.direction)<=0.0 { + punctual_count(2u); continue; + } + shadow_direction=connection/shadow_distance; + shadow_distance=punctual_endpoint(shadow_distance); } if sample.pdf<=0.0 || dot(n,sample.direction)<=0.0 || dot(geometric,sample.direction)<=0.0 { continue; } } // Studio emitters block a connection that passes them; studio volumes attenuate it. var visibility = blocked_shadow(); - if !studio || emitter_hit(o,shadow_direction).distance>=shadow_distance-u.lighting.x*2.0 { - visibility = shadow_transmittance(o,shadow_direction,shadow_distance); + let shadow_minimum=select(u.lighting.x,0.0,punctual); + 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); if studio && u.volume_min.w>0.0 { - let attenuation=volume_transmittance(o,shadow_direction,shadow_distance); + var attenuation=volume_transmittance_precise(shadow_origin,shadow_origin_low,shadow_direction,shadow_distance); + if punctual { attenuation=volume_transmittance_precise(physical.hi,physical.lo,sample.direction,physical_distance); } visibility.transmittance*=attenuation; visibility.branch_pdf*=attenuation; } } let nl = dot(n,sample.direction); - if !studio { + // A hard source is a delta distribution. A continuous BSDF continuation + // has no competing probability mass at that direction, so its MIS weight is one. + if !studio || source>=area_count+2u { result += visibility.transmittance * brdf(t,n,v,sample.direction) * (opaque*nl*sample.radiance); continue; } @@ -839,11 +1110,30 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4 { var medium_count = 0u; var texture_path_length = 0.0; for (var bounce = 0u; bounce < u.sampling.y; bounce += 1u) { + // Classify the actual sampled primary/pupil origin once, before an opaque + // hit, emitter endpoint, subsurface flight or escape can consume its segment. + // No random draw or extra traversal is added to nested_media=false paths. + if !OPAQUE_SCENE && bounce==0u && u.lighting.w>0.0 { + let boundary=origin_boundary(o,d); + if !boundary.valid { return medium_failure(radiance,coverage,pixel,0u,4u); } + if boundary.hit.triangle!=0xffffffffu { + let first=triangle(boundary.hit.triangle); + // Match initialize_media's exact uploaded-f32 entry predicate. A + // certified first entry with no parent already proves vacuum; its + // 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); } + } + } + } // Closed-glass continuations set an excluded producing triangle; every // other launch (camera, opaque or thin-sheet surface) does not. let continued = ray_excluded != 0xffffffffu; let hit = trace_precise(o,o_low,d,false,ray_excluded,ray_minimum,medium_count>0u); - if !OPAQUE_SCENE && u.lighting.w>0.0 && medium_count==0u && hit.triangle!=0xffffffffu { + // 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 medium_count>0u && media[medium_count-1u].scatter.x>0.0 { @@ -870,7 +1160,15 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4 { } if u.volume_min.w>0.0 { let emitter_distance=emitter_hit_precise(o,o_low,d,ray_minimum).distance; - let segment=volume_segment(o+o_low,d,min(hit.distance,emitter_distance)); + var segment=vec2(0.0); + if bounce==0u && u.eye.w<=0.5 { + // The orthographic camera has no physical eye plane. Its fog + // line starts at the finite box entry, even before the artificial + // geometry origin; the existing forward endpoint stays fixed. + segment=volume_orthographic_segment(o+o_low,d,min(hit.distance,emitter_distance)); + } else { + segment=volume_segment(o+o_low,d,min(hit.distance,emitter_distance)); + } let length=segment.y-segment.x; if length>0.0 { let travel=-log(1.0-random(&rng))/u.volume_min.w; @@ -881,7 +1179,9 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4 { throughput*=u.volume_albedo.xyz; if !any(throughput>vec3(0.0)) { break; } let remaining=u.sampling.y-bounce-1u; - radiance+=throughput*volume_direct(position,d,remaining,&rng); + var physical=PrecisePoint(o,o_low+d*(segment.x+travel)); + if u.light_count.y>0.0 {physical=punctual_offset(physical,vec3(0.0));} + radiance+=throughput*volume_direct(position,physical,d,remaining,&rng); if remaining==0u { break; } let next=volume_sample(d,&rng); previous_pdf=volume_phase(dot(d,next)); @@ -1075,7 +1375,9 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4 { 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); - radiance += throughput*direct_light(t,position,o,n,geometric,v,u.sampling.y-bounce-1u,&rng); + var physical=PrecisePoint(position,position_low); + if u.light_count.y>0.0 { physical=punctual_offset(surface_point_precise(captured,hit.bary),vec3(0.0)); } + radiance += throughput*direct_light(t,position,physical,o,n,geometric,v,u.sampling.y-bounce-1u,&rng); d = sample_surface(t,n,v,&rng); let nl = dot(n,d); if nl<=0.0 || dot(geometric,d)<=0.0 { break; } @@ -1398,3 +1700,16 @@ fn integer_relative_reference(@builtin(global_invocation_id) invocation: vec3(f32(reference&65535u),f32(reference>>16u),f32(candidate&65535u),f32(candidate>>16u)); } + +@compute @workgroup_size(32) +fn split_predicate_reference(@builtin(global_invocation_id) gid: vec3) { + if gid.x>=geometry[0] { return; } + let word=1u+gid.x*4u; + let a=bitcast(geometry[word]);let b=bitcast(geometry[word+1u]); + let c=bitcast(geometry[word+2u]);let d=bitcast(geometry[word+3u]); + let product=split_product(split_scaled(a).value,split_scaled(b).value); + let p=bitcast(product.x);let e=bitcast(product.y); + let direct=bitcast(split_difference_products(a,b,c,d));let wrapped=bitcast(difference_products(a,b,c,d)); + accumulation[2u*gid.x]=vec4(f32(p&65535u),f32(p>>16u),f32(e&65535u),f32(e>>16u)); + accumulation[2u*gid.x+1u]=vec4(f32(direct&65535u),f32(direct>>16u),f32(wrapped&65535u),f32(wrapped>>16u)); +} diff --git a/crates/gpu/src/path/punctual.wgsl b/crates/gpu/src/path/punctual.wgsl new file mode 100644 index 000000000..cc5c46aca --- /dev/null +++ b/crates/gpu/src/path/punctual.wgsl @@ -0,0 +1,50 @@ +// Original relative point/spot transport. No sampling RNG, photometry or clamp. +// Diagnostics count actual sampled surface/volume paths (adaptive pilots included). +fn punctual_count(kind:u32) { + let word=8u+kind*2u; + if atomicAdd(&failures[word],1u)==0xffffffffu { atomicAdd(&failures[word+1u],1u); } +} +fn punctual_radiance_valid(value:vec3)->bool { + return all(value>=vec3(0.0)) && all(value<=vec3(1e12)); +} +struct PunctualSample { direction:vec3, radiance:vec3, distance:f32, omitted:u32 }; +fn punctual_sample(light:PunctualLight,position:PrecisePoint)->PunctualSample { + // A barycentric anchor may have a large local displacement. Canonicalize + // both parts before subtracting a nearby canonically packed source. + let physical=punctual_offset(position,vec3(0.0)); + let delta=precise_point_delta(light.position.xyz,light.position_low.xyz,physical.hi,physical.lo); + let distance=length(delta); + // Count near-source before testing intensity/colour/cone, like the CPU. + if !(distance>=light.position_low.w) { + punctual_count(0u); + return PunctualSample(vec3(0.0,0.0,1.0),vec3(0.0),distance,1u); + } + let direction=delta/distance; + var cone=1.0; + if light.cone.y>0.0 { + let cosine=dot(light.axis.xyz,-direction); + let t=clamp((cosine-light.cone.x)/(light.axis.w-light.cone.x),0.0,1.0); + cone=t*t*(3.0-2.0*t); + } + let ratio=light.position.w/distance; + let incident=light.color.xyz*(light.color.w*ratio*ratio*cone); + if !punctual_radiance_valid(incident) { + punctual_count(1u); + return PunctualSample(direction,vec3(0.0),distance,2u); + } + return PunctualSample(direction,incident,distance,0u); +} + +// Finite delta sources exclude their endpoint, as the CPU next_down interval does. +fn punctual_endpoint(distance:f32)->f32 { return bitcast(bitcast(distance)-1u); } + +// Canonicalize an anchored point before adding a tiny geometric offset. Adding +// directly to an arbitrarily large local barycentric displacement can erase it. +fn punctual_offset(point:PrecisePoint,offset:vec3)->PrecisePoint { + var hi=vec3(0.0);var lo=vec3(0.0); + for(var axis=0u;axis<3u;axis+=1u) { + hi[axis]=bitcast(fp_add_bits(bitcast(point.hi[axis]),bitcast(point.lo[axis]))); + lo[axis]=anchored_delta_component(point.hi[axis],point.lo[axis],hi[axis],0.0)+offset[axis]; + } + return PrecisePoint(hi,lo); +} diff --git a/crates/gpu/src/path/shadows.wgsl b/crates/gpu/src/path/shadows.wgsl index 21824e036..6f28d1040 100644 --- a/crates/gpu/src/path/shadows.wgsl +++ b/crates/gpu/src/path/shadows.wgsl @@ -4,20 +4,20 @@ struct ShadowResult { transmittance: vec3, branch_pdf: f32, crossings: u32, fn blocked_shadow() -> ShadowResult { return ShadowResult(vec3(0.0),0.0,0u,false); } -fn shadow_transmittance(origin: vec3, direction: vec3, limit: f32) -> ShadowResult { +fn shadow_transmittance(origin: vec3, origin_low: vec3, direction: vec3, limit: f32, minimum: f32) -> ShadowResult { var result = ShadowResult(vec3(1.0),1.0,0u,false); var o = origin; - var o_low = vec3(0.0); + var o_low = origin_low; var ray_excluded = 0xffffffffu; - var ray_minimum = u.lighting.x; + var ray_minimum = minimum; var medium_id = 0.0; var medium_ior = 1.0; var sigma = vec3(0.0); var entry = origin; - var entry_low = vec3(0.0); + var entry_low = 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,vec3(0.0)),direction); + let traversed = dot(precise_point_delta(o,o_low,origin,origin_low),direction); let remaining = limit-traversed; // Outside media nothing beyond the endpoint matters. Inside, the // endpoint branch below must still see the farther boundary. @@ -76,7 +76,7 @@ fn shadow_transmittance(origin: vec3, direction: vec3, limit: f32) -> // 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=vec3(0.0); + medium_id=t.optics.w; medium_ior=t.parameters.z; sigma=t.optics.xyz; entry=origin; entry_low=origin_low; } 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))); @@ -100,7 +100,7 @@ fn shadow_transmittance(origin: vec3, direction: vec3, limit: f32) -> @compute @workgroup_size(1) fn shadow_reference() { - let shadow=shadow_transmittance(u.eye.xyz,u.back.xyz,u.back.w); + let shadow=shadow_transmittance(u.eye.xyz,vec3(0.0),u.back.xyz,u.back.w,u.lighting.x); accumulation[0]=vec4(shadow.transmittance,1.0); accumulation[1]=vec4(shadow.branch_pdf,f32(shadow.crossings),select(0.0,1.0,shadow.solid),1.0); } diff --git a/crates/gpu/src/path/tests.rs b/crates/gpu/src/path/tests.rs index c028f55af..195b67c10 100644 --- a/crates/gpu/src/path/tests.rs +++ b/crates/gpu/src/path/tests.rs @@ -1,5 +1,4 @@ use super::*; -use solidcraft_geom::prelude::*; use solidcraft_geom::{Aabb3, Mesh}; use solidcraft_render::{Camera, ProductMesh, StandardView, surface::OpaqueSurface}; @@ -321,7 +320,7 @@ fn gpu_thin_lens_focus_and_defocus_match_geometric_oracle() { let focal = eye + (right * ux + up * uy) * (camera.half_height() * lens.focus_distance_mm / camera.distance) - back * lens.focus_distance_mm; for (radial, azimuth) in [(0.0_f64, 0.0_f64), (0.25, 0.125), (0.75, 0.625), (0.999, 0.999)] { - let mut params = task.parameters(1); + let mut params = task.parameters(1).unwrap(); params.truncate(96); scene::vector(&mut params, Vec3::new(ux, uy, radial), azimuth as f32); context.queue.write_buffer(&task.uniform, 0, ¶ms); @@ -580,7 +579,7 @@ fn main_inlines_few_bvh_walks() { .into_iter() .map(|handle| { let callee = &module.functions[handle]; - let walk = matches!(callee.name.as_deref(), Some("trace_precise_within" | "trace_ordered_within")); + let walk = matches!(callee.name.as_deref(), Some("trace_precise_within" | "trace_ordered_within" | "origin_boundary")); usize::from(walk) + walks(module, callee) }) .sum() @@ -591,6 +590,34 @@ fn main_inlines_few_bvh_walks() { assert!(inlined <= 5, "`main` inlines {inlined} BVH walks"); } +#[test] +fn geometry_materialization_lane_keeps_positive_zero_at_the_shader_offset() { + let Some(executor) = executor() else { return }; + let module = naga::front::wgsl::parse_str(SHADER).unwrap(); + let params = module.types.iter().find(|(_, ty)| ty.name.as_deref() == Some("Params")).unwrap().1; + let naga::TypeInner::Struct { members, .. } = ¶ms.inner else { panic!("Params must be a struct") }; + let offset = members.iter().find(|member| member.name.as_deref() == Some("studio_weights")).unwrap().offset as usize + 12; + let mut task = Task::new( + executor.context, + ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }, + request(1), + JobOptions::default(), + CancelToken::default(), + ) + .unwrap(); + for weights in [None, Some([0.0; 3]), Some([1.0, 0.5, 0.25])] { + task.request.studio_weights = weights; + for sample in [0, 1, 4095] { + task.sample = sample; + let bytes = task.parameters(1).unwrap(); + assert_eq!(&bytes[offset..offset + 4], &0u32.to_le_bytes(), "reserved arithmetic lane must remain positive zero"); + } + } + task.request.studio_weights = None; + task.options.lighting = Some(solidcraft_render::job::StudioLighting { environment: [0.75; 3], ..Default::default() }); + assert_eq!(&task.parameters(1).unwrap()[offset..offset + 4], &0u32.to_le_bytes()); +} + #[test] fn render_lights_path_visibility_uniform_keeps_the_shader_contract() { shader_validates_without_a_device(); @@ -1370,11 +1397,17 @@ fn gpu_studio_area_mis_matches_independent_quadrature_and_distance_visibility() samples: 4096, max_depth: depth, seed: 37, - lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + }), ..Default::default() }; let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); - assert_eq!(task.parameters(1).len(), PARAMETER_BYTES); + assert_eq!(task.parameters(1).unwrap().len(), PARAMETER_BYTES); for _ in 0..options.samples { task.complete_sample().unwrap(); } @@ -1421,7 +1454,13 @@ fn gpu_emitter_inside_glass_applies_final_segment_absorption() { let options = JobOptions { samples: 16, max_depth: 2, - lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + }), ..Default::default() }; let mut image = request(2); @@ -1555,7 +1594,7 @@ fn gpu_environment_orientation_rotation_intensity_and_pdf_match_cpu() { let local = Vec3::new(theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos()); let direction = Vec3::new(rotation.cos() * local.x - rotation.sin() * local.y, rotation.sin() * local.x + rotation.cos() * local.y, local.z); - let mut params = task.parameters(1); + let mut params = task.parameters(1).unwrap(); for (out, value) in params[48..60].as_chunks_mut::<4>().0.iter_mut().zip([direction.x, direction.y, direction.z]) { out.copy_from_slice(&(value as f32).to_le_bytes()); } @@ -1729,7 +1768,13 @@ fn gpu_shadow_mis_does_not_double_direct_energy_through_index_matched_glass() { samples: 4096, max_depth: depth, seed: 37, - lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + }), ..Default::default() }; let mut image = request(1); @@ -1792,7 +1837,13 @@ fn gpu_absorbing_two_sheet_mis_matches_f64_quadrature() { samples: 4096, max_depth: depth, seed: 37, - lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + }), ..Default::default() }; let mut image = request(1); @@ -2092,7 +2143,13 @@ fn gpu_finite_emitter_inside_solid_retains_entry_radiance_eta() { samples: 4096, max_depth: depth, seed: 37, - lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + sun: None, + environment: [0.0; 3], + area_lights: AreaLights::new(&[light]).unwrap(), + }), ..Default::default() }; let mut image = request(1); @@ -2777,6 +2834,95 @@ fn gpu_rib_total_internal_reflection_retains_origin_residual() { } } } +#[test] +fn gpu_split_products_reconstruct_exact_products_and_near_determinants() { + use wgpu::util::DeviceExt; + let Some(executor) = executor() else { return }; + let context = &executor.context; + let unit = 0x3f800000u32; + let c = unit | (13_264_529 - (1 << 23)); + let d = unit | (2351 * 4513 - (1 << 23)); + let mut cases = + vec![[0x40000000, unit, c, d], [c, d, 0x40000000, unit], [unit, 0x40000000, 0x40000000, unit], [unit + 1, unit + 1, unit, unit + 2]]; + let mut state = 0x11c731u32; + let mut next = || { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + state + }; + while cases.len() < 4096 { + let a = f32::from_bits(((110 + next() % 41) << 23) | (next() & 0x7fffff)); + let b = f32::from_bits(((110 + next() % 41) << 23) | (next() & 0x7fffff)); + let c = f32::from_bits(((110 + next() % 41) << 23) | (next() & 0x7fffff)); + let d = (f64::from(a) * f64::from(b) / f64::from(c)) as f32; + cases.push([a.to_bits(), b.to_bits(), c.to_bits(), d.to_bits()]); + } + for [a, b, c, d] in cases.clone() { + cases.push([a ^ 0x80000000, b, c ^ 0x80000000, d]); + } + assert_eq!(cases.len(), 8192); + let mut bytes = Vec::with_capacity(4 + cases.len() * 16); + bytes.extend((cases.len() as u32).to_le_bytes()); + for case in &cases { + for word in case { + bytes.extend(word.to_le_bytes()); + } + } + let input = context.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("split determinant inputs"), + contents: &bytes, + usage: wgpu::BufferUsages::STORAGE, + }); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("split determinant oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &shader, + entry_point: Some("split_predicate_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), glass_slab(false), request(128), JobOptions::default(), CancelToken::default()).unwrap(); + context.queue.write_buffer(&task.uniform, 0, &task.parameters(0).unwrap()); + let bind = context.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("split determinant oracle"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: task.uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: task.accumulation.as_entire_binding() }, + ], + }); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups((cases.len() as u32).div_ceil(32), 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + let word = |low: f32, high: f32| low as u32 | ((high as u32) << 16); + let value = |bits| f64::from(f32::from_bits(bits)); + let normalized = |bits| value((bits & 0x807fffff) | 0x3f800000); + for (index, ([a, b, c, d], output)) in cases.iter().zip(values.as_chunks::<2>().0).enumerate() { + let product = value(word(output[0][0], output[0][1])); + let error = value(word(output[0][2], output[0][3])); + assert_eq!(product + error, normalized(*a) * normalized(*b), "exact split product index={index}"); + let expected = (value(*a) * value(*b) - value(*c) * value(*d)) as f32; + for got in [word(output[1][0], output[1][1]), word(output[1][2], output[1][3])] { + if expected == 0.0 { + assert_eq!(f32::from_bits(got), 0.0, "zero determinant index={index}"); + } else { + assert_eq!(got, expected.to_bits(), "split determinant index={index}, operands={a:08x}/{b:08x}/{c:08x}/{d:08x}"); + } + } + } +} + #[test] fn gpu_integer_binary32_add_sub_matches_hardware_bits() { use wgpu::util::DeviceExt; @@ -3705,7 +3851,13 @@ fn complete_linear_fixture(context: Arc, options: JobOptions) -> (Vec>(), [1, 2, 3]); + for preview in previews { + let mut prefix = Task::new( + executor.context.clone(), + scene.clone(), + request.clone(), + JobOptions { samples: preview.samples_per_pixel, ..options }, + CancelToken::default(), + ) + .unwrap(); + let mut expected = None; + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = prefix.step(4096).unwrap() { + expected = Some(png); + break; + } + } + assert_eq!(Some(preview.png), expected, "provisional effects must match the same complete sample prefix"); + } + assert!(final_png.is_some()); + let master = task.take_linear_exr().unwrap(); + let mut reference = Task::new(executor.context.clone(), scene, request, options, CancelToken::default()).unwrap(); + let mut reference_png = None; + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = reference.step(4096).unwrap() { + reference_png = Some(png); + break; + } + } + assert_eq!(final_png, reference_png, "publishing previews cannot change final presentation"); + assert_eq!(Some(master), reference.take_linear_exr(), "provisional effects cannot alter the raw master"); +} + +#[test] +fn adaptive_gpu_checkpoint_target_includes_pilots_without_disabling_final_rendering() { + let Some(executor) = executor() else { return }; + let options = JobOptions { + samples: 16, + adaptive: Some(solidcraft_render::job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }), + ..Default::default() + }; + assert_eq!(executor.preview_samples(options), Some(32)); + assert!(executor.preview_unavailable_reason(options).is_none()); + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + let job = host + .submit_with_options( + solidcraft_render::job::JobId { session: 9023, serial: 1, generation: 1 }, + 57, + ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }, + request(2), + options, + ) + .unwrap(); + assert!(job.status().unwrap().preview_unavailable_reason.is_none()); + let status = job.wait_timeout(Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert!(job.preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_some()); +} + +#[test] +fn gpu_ui_box_coat_and_color_map_keep_every_raw_sample_finite() { + use image::ImageEncoder; + use serde_json::json; + use solidcraft_render::{ + clear_coat::ClearCoat, + job::textures::{PlanarFrame, RuntimeTextures, TextureBinding, TextureMap}, + surface::srgb8_to_linear, + texture_input::MapRole, + }; + let Some(executor) = executor() else { return }; + let mut session = solidcraft_engine::Session::default(); + session.execute("solid.box", &json!({"length":10,"width":20,"height":5})).unwrap(); + let captured = solidcraft_engine::product_scene::extract(&session).unwrap(); + assert_eq!(captured.meshes.len(), 1); + let mut encoded_map = Vec::new(); + image::codecs::png::PngEncoder::new(&mut encoded_map).write_image(&[80, 160, 220, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap(); + let color_map = TextureMap::new(encoded_map, MapRole::BaseColor).unwrap(); + // Retain the exact camera and request from the UI failure. This exercises + // the production `main` entry point, not only the BRDF reference kernels. + let camera = Camera { + target: Vec3::new(10.525041892255036, 11.6661345783332, -1.3589073139218368), + yaw: -std::f64::consts::FRAC_PI_4, + pitch: 0.6154797086703874, + roll: 0.0, + distance: 61.06594959585294, + fov: 0.0, + up: solidcraft_render::UpAxis::Z, + }; + let options: JobOptions = serde_json::from_value(json!({ + "samples":4,"max_depth":3,"seed":7,"exposure_ev":0.5,"tone_map":"aces_fitted", + "lens":{"aperture_radius_mm":0.0,"focus_distance_mm":100.0}, + "lighting":{"environment":[0.75,0.75,0.75],"sun":null,"area_lights":[]} + })) + .unwrap(); + for (coated, mapped) in [(false, false), (true, false), (false, true), (true, true)] { + let mut source = captured.clone(); + if coated { + let coat = ClearCoat::new(1.0, 0.12, 1.5).unwrap(); + let body = &mut source.meshes[0]; + let coat_surface = |color: [u8; 3], surface: Option| { + let [r, g, b] = color.map(srgb8_to_linear); + surface.unwrap_or_else(|| OpaqueSurface::new(Vec3::new(r, g, b), 0.0, 0.5, 1.5).unwrap()).with_clear_coat(coat) + }; + body.surface = Some(coat_surface(body.color, body.surface)); + for face in &mut body.faces { + face.surface = Some(coat_surface(face.color, face.surface)); + } + } + let textures = mapped.then(|| { + Arc::new( + RuntimeTextures::new(vec![TextureBinding { + body_index: 0, + body_name: source.meshes[0].name.clone(), + frame: PlanarFrame { origin: [0.0; 3], u: [10.0, 0.0, 0.0], v: [0.0, 10.0, 0.0] }, + normal_strength: 1.0, + base_color: Some(color_map.clone()), + normal: None, + roughness: None, + metallic: None, + base_color_mode: Default::default(), + flip_v: false, + }]) + .unwrap(), + ) + }); + let input = ImageRequest { camera, background: [236, 240, 245], textures, ..request(16) }; + let mut task = Task::new(executor.context.clone(), source, input, options, CancelToken::default()).unwrap(); + for sample in 1..=options.samples { + task.complete_sample().unwrap(); + let pixels = task.read_linear().unwrap_or_else(|error| panic!("coat={coated}, map={mapped}, sample={sample}: {error}")); + assert_eq!(pixels.len(), 256); + assert!(pixels.iter().flatten().all(|value| value.is_finite() && *value >= 0.0)); + assert!(pixels.iter().all(|pixel| pixel[3] <= 1.0)); + assert!(pixels.iter().any(|pixel| pixel[3] > 0.0 && pixel[..3].iter().any(|value| *value > 0.0)), "the fixture must shade the box"); + // A diagnostic fingerprint for comparing the same test with and + // without shader instrumentation; not a cross-device golden. + let fingerprint = pixels + .iter() + .flatten() + .flat_map(|value| value.to_bits().to_le_bytes()) + .fold(0xcbf29ce484222325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3)); + eprintln!("UI box raw float fingerprint coat={coated} map={mapped} sample={sample}: {fingerprint:016x}"); + } + let mut completed = None; + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = task.step(4096).unwrap() { + completed = Some(png); + break; + } + } + let image = image::load_from_memory(&completed.expect("bounded GPU box render must produce its final PNG")).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (16, 16)); + assert!(image.pixels().any(|pixel| pixel.0 != image.get_pixel(0, 0).0)); + } +} + +fn directional_receiver() -> ProductScene { + let mesh = Mesh { + positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + ProductScene { + meshes: vec![ProductMesh { + name: "directional receiver".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(white()), + transmission: None, + faces: Vec::new(), + }], + bounds: Aabb3::EMPTY, + } +} + +#[test] +fn gpu_hard_directional_rgb_sum_matches_f64_brdf_without_emitter_mis_or_sample_count_bias() { + use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let sources = [ + DirectionalLightOptions { direction: [0.0, 0.0, 2.0], color: [1.0, 0.0, 0.0], intensity: 2.0 }, + DirectionalLightOptions { direction: [3.0, 0.0, 4.0], color: [0.0, 1.0, 0.0], intensity: 3.0 }, + DirectionalLightOptions { direction: [0.0, -4.0, 3.0], color: [0.0, 0.0, 1.0], intensity: 4.0 }, + ]; + let mut expected = Vec3::ZERO; + for light in sources { + let [x, y, z] = light.direction; + let l = Vec3::new(x, y, z).normalized().unwrap(); + let [r, g, b] = light.color; + let response = white().brdf(Vec3::Z, Vec3::Z, l).unwrap(); + expected += Vec3::new(response.x * r, response.y * g, response.z * b) * (light.intensity * l.z); + } + for depth in [1, 2] { + for samples in [1, 4] { + let options = JobOptions { + samples, + max_depth: depth, + seed: 43, + lighting: Some(StudioLighting { directional_lights: DirectionalLights::new(&sources).unwrap(), ..Default::default() }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), directional_receiver(), request(1), options, CancelToken::default()).unwrap(); + while task.sample < samples { + task.complete_sample().unwrap(); + } + let actual = task.read_linear().unwrap()[0]; + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-6, "depth{depth} samples{samples}: {actual:?} vs {expected:?}"); + } + assert_eq!(actual[3], 1.0); + } + } +} + +#[test] +fn gpu_hard_directionals_preserve_zero_source_and_default_streams_and_cancel_without_publication() { + use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights, LightingPreset, StudioLighting}; + let Some(executor) = executor() else { return }; + let render = |lighting| { + let options = JobOptions { samples: 4, max_depth: 3, seed: 71, lighting, ..Default::default() }; + let mut task = Task::new(executor.context.clone(), directional_receiver(), request(4), options, CancelToken::default()).unwrap(); + while task.sample < 4 { + task.complete_sample().unwrap(); + } + task.read_linear().unwrap() + }; + let black = render(Some(StudioLighting::default())); + let zero = DirectionalLightOptions { direction: [1.0, 0.0, 1.0], color: [1.0; 3], intensity: 0.0 }; + assert_eq!(black, render(Some(StudioLighting { directional_lights: DirectionalLights::new(&[zero; 8]).unwrap(), ..Default::default() }))); + let defaults = LightingPreset::Neutral.directional_lights(); + assert_eq!( + render(None), + render(Some(StudioLighting { directional_lights: DirectionalLights::new(&defaults).unwrap(), ..Default::default() })), + "materializing the implicit three hard sources preserves their stream and values" + ); + let token = CancelToken::default(); + let options = JobOptions { + lighting: Some(StudioLighting { directional_lights: DirectionalLights::new(&[zero; 8]).unwrap(), ..Default::default() }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), directional_receiver(), request(4), options, token.clone()).unwrap(); + token.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert!(std::mem::size_of::() <= 65_536, "inline sources must fit the unchanged fixed task reserve"); +} + +#[test] +fn gpu_hard_directional_uniform_layout_and_admission_keep_the_positive_zero_abi() { + use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights, StudioLighting}; + let Some(executor) = executor() else { return }; + shader_validates_without_a_device(); + main_inlines_few_bvh_walks(); + let module = naga::front::wgsl::parse_str(SHADER).unwrap(); + let params = module.types.iter().find(|(_, t)| t.name.as_deref() == Some("Params")).unwrap().1; + let naga::TypeInner::Struct { members, .. } = ¶ms.inner else { panic!("Params") }; + let offset = members.iter().find(|m| m.name.as_deref() == Some("directional_lights")).unwrap().offset as usize; + let barrier = members.iter().find(|m| m.name.as_deref() == Some("studio_weights")).unwrap().offset as usize + 12; + assert_eq!(barrier, PARAMETER_BYTES - 4); + let mut lights = [DirectionalLightOptions { direction: [0.0, 0.0, 2.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }; 8]; + lights[7].direction = [f64::MIN_POSITIVE, 0.0, 0.0]; + let options = JobOptions { + lighting: Some(StudioLighting { directional_lights: DirectionalLights::new(&lights).unwrap(), ..Default::default() }), + ..Default::default() + }; + let task = Task::new(executor.context.clone(), directional_receiver(), request(1), options, CancelToken::default()).unwrap(); + let bytes = task.parameters(1).unwrap(); + let f = |i| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap()); + assert_eq!([f(offset), f(offset + 4), f(offset + 8), f(offset + 12)], [0.0, 0.0, 1.0, 2.0]); + assert_eq!([f(offset + 16), f(offset + 20), f(offset + 24), f(offset + 28)], [0.25, 0.5, 1.0, 0.0]); + assert_eq!([f(offset + 7 * 32), f(offset + 7 * 32 + 4), f(offset + 7 * 32 + 8)], [1.0, 0.0, 0.0]); + assert_eq!(&bytes[barrier..], &0u32.to_le_bytes()); + assert_eq!(DIRECTIONAL_PARAMETER_BYTES, 256); + let admitted = admission(&directional_receiver(), &request(1), options).unwrap(); + assert!(admitted.preparation_bytes >= 1_048_576 + 2 * DIRECTIONAL_PARAMETER_BYTES); + assert_eq!( + serde_json::to_value(admitted).unwrap(), + serde_json::to_value(admission(&directional_receiver(), &request(1), JobOptions::default()).unwrap()).unwrap(), + "fixed uniform billing is independent of list contents" + ); +} + +#[test] +fn gpu_hard_directional_visibility_obeys_opaque_blockers_and_external_beer_attenuation() { + use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights, StudioLighting, volume::HomogeneousVolume}; + let Some(executor) = executor() else { return }; + let light = DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }; + for (blocker, medium) in [(false, false), (true, false), (false, true)] { + let mut scene = directional_receiver(); + if blocker { + let mut plane = scene.meshes[0].clone(); + plane.name = "shadow blocker".into(); + for p in &mut Arc::make_mut(&mut plane.mesh).positions { + p.z = 1.0; + } + scene.meshes.push(plane); + } + let options = JobOptions { + samples: 4, + max_depth: 1, + lighting: Some(StudioLighting { directional_lights: DirectionalLights::new(&[light]).unwrap(), ..Default::default() }), + volume: medium.then_some(HomogeneousVolume { + min_mm: [-100.0, -100.0, 0.2], + max_mm: [100.0, 100.0, 0.8], + extinction_per_mm: 0.5, + scattering_albedo: [0.0; 3], + anisotropy: 0.0, + }), + ..Default::default() + }; + let mut image = request(1); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); + while task.sample < options.samples { + task.complete_sample().unwrap(); + } + let actual = task.read_linear().unwrap()[0]; + let visibility = if blocker { + 0.0 + } else if medium { + (-0.3_f64).exp() + } else { + 1.0 + }; + for (a, scale) in actual.iter().zip([1.0, 0.5, 0.25]) { + let expected = 2.0 * scale * visibility / std::f64::consts::PI; + assert!((f64::from(*a) - expected).abs() < 2e-6, "blocker{blocker} volume{medium}: {actual:?} vs{expected}"); + } + } +} + +fn punctual_options(sources: &[solidcraft_render::job::PunctualLightOptions], samples: u32, depth: u32) -> JobOptions { + use solidcraft_render::job::{PunctualLights, StudioLighting}; + JobOptions { + samples, + max_depth: depth, + seed: 43, + lighting: Some(StudioLighting { punctual_lights: PunctualLights::new(sources).unwrap(), ..Default::default() }), + ..Default::default() + } +} +fn punctual_point() -> solidcraft_render::job::PunctualLightOptions { + solidcraft_render::job::PunctualLightOptions { + position_mm: [0.0, 0.0, 4.0], + color: [0.25, 0.5, 1.0], + intensity: 2.0, + reference_distance_mm: 4.0, + minimum_distance_mm: 0.001, + cone: None, + } +} +// Independent scalar law; does not call the CPU/GPU punctual sampling helpers. +fn punctual_oracle(source: solidcraft_render::job::PunctualLightOptions, position: Vec3) -> (Vec3, Vec3) { + let [x, y, z] = source.position_mm; + let delta = Vec3::new(x, y, z) - position; + let distance = delta.len(); + let direction = delta / distance; + let weight = source.cone.map_or(1.0, |cone| { + let [x, y, z] = cone.emitted_axis; + let axis = Vec3::new(x, y, z).normalized().unwrap(); + let t = ((axis.dot(-direction) - cone.outer_half_angle_radians.cos()) + / (cone.inner_half_angle_radians.cos() - cone.outer_half_angle_radians.cos())) + .clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }); + let [r, g, b] = source.color; + (direction, Vec3::new(r, g, b) * (source.intensity * (source.reference_distance_mm / distance).powi(2) * weight)) +} +fn punctual_primary_point(camera: Camera, ordinal: u32, seed: u32) -> Vec3 { + let mut state = ordinal.wrapping_mul(0x9e3779b9) ^ 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 x = random() * 2.0 - 1.0; + let y = 1.0 - random() * 2.0; + let (right, up, back) = camera.basis(); + let origin = camera.target + back * (camera.distance * 4.0) + (right * x + up * y) * camera.half_height(); + origin - back * (origin.z / back.z) +} +#[test] +fn gpu_point_and_spot_real_primary_rays_match_inverse_square_rgb_cone_and_endpoint_depth() { + use solidcraft_render::job::SpotConeOptions; + let Some(executor) = executor() else { return }; + for cone in [None, Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.9 })] { + let source = solidcraft_render::job::PunctualLightOptions { cone, ..punctual_point() }; + for depth in [1, 2] { + let options = punctual_options(&[source], 16, depth); + let image = request(1); + let mut task = Task::new(executor.context.clone(), directional_receiver(), image.clone(), options, CancelToken::default()).unwrap(); + let mut expected = Vec3::ZERO; + for ordinal in 0..16 { + let position = punctual_primary_point(image.camera, ordinal, options.seed); + let (direction, incident) = punctual_oracle(source, position); + let brdf = white().brdf(Vec3::Z, image.camera.back(), direction).unwrap(); + expected += Vec3::new(brdf.x * incident.x, brdf.y * incident.y, brdf.z * incident.z) * direction.z; + task.complete_sample().unwrap(); + let actual = task.read_linear().unwrap()[0]; + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z].map(|v| v / f64::from(ordinal + 1))) { + assert!((f64::from(*a) - b).abs() < 3e-6, "ordinal{ordinal} depth{depth} cone{cone:?}: {actual:?} vs {expected:?}"); + } + assert_eq!(actual[3], 1.0); + } + assert_eq!(task.punctual_diagnostics(), Some(Default::default())); + } + } +} +#[test] +fn gpu_punctual_uniform_high_low_precision_and_admission_are_exact_and_keep_barrier_last() { + use solidcraft_render::job::PunctualLightOptions; + shader_validates_without_a_device(); + main_inlines_few_bvh_walks(); + let light = PunctualLightOptions { position_mm: [1e9 - 0.01, -1e9 + 0.02, 0.003], ..punctual_point() }; + let packed = punctual_parameters(&light, Vec3::ZERO); + for (axis, expected) in light.position_mm.into_iter().enumerate() { + let actual = f64::from(packed[0][axis]) + f64::from(packed[1][axis]); + assert!((actual - expected).abs() < 1e-6, "axis{axis}: {actual} vs {expected}"); + } + assert_eq!(packed[0][0], 1e9_f32); + assert!(packed[1][0] < -0.009 && packed[1][0] > -0.011); + let module = naga::front::wgsl::parse_str(SHADER).unwrap(); + let params = module.types.iter().find(|(_, t)| t.name.as_deref() == Some("Params")).unwrap().1; + let naga::TypeInner::Struct { members, span } = ¶ms.inner else { panic!("Params") }; + assert_eq!(*span as usize, PARAMETER_BYTES); + let offset = members.iter().find(|m| m.name.as_deref() == Some("punctual_lights")).unwrap().offset; + let barrier = members.iter().find(|m| m.name.as_deref() == Some("studio_weights")).unwrap().offset + 12; + assert_eq!(offset as usize, PARAMETER_BYTES - PUNCTUAL_PARAMETER_BYTES as usize - 16); + assert_eq!(barrier as usize, PARAMETER_BYTES - 4); + assert_eq!(FAILURE_BYTES, 32 + PUNCTUAL_COUNTER_BYTES); + let a = admission(&directional_receiver(), &request(1), JobOptions::default()).unwrap(); + let b = admission(&directional_receiver(), &request(1), punctual_options(&[light; 8], 1, 1)).unwrap(); + assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap()); + assert!(a.preparation_bytes >= 1_048_576 + 2 * (DIRECTIONAL_PARAMETER_BYTES + PUNCTUAL_PARAMETER_BYTES + PUNCTUAL_COUNTER_BYTES)); + assert_eq!(punctual_options(&[light; 8], 1, 1).retained_bytes().unwrap(), std::mem::size_of::() as u64); + assert!(std::mem::size_of::() <= 65_536); +} +#[test] +fn gpu_punctual_delta_sources_preserve_zero_default_stream_and_cancel_without_publication() { + use solidcraft_render::job::{DirectionalLights, LightingPreset, StudioLighting}; + let Some(executor) = executor() else { return }; + let render = |options| { + let mut task = Task::new(executor.context.clone(), directional_receiver(), request(4), options, CancelToken::default()).unwrap(); + for _ in 0..4 { + task.complete_sample().unwrap(); + } + task.read_linear().unwrap() + }; + let zero = solidcraft_render::job::PunctualLightOptions { intensity: 0.0, ..punctual_point() }; + let old = JobOptions { samples: 4, max_depth: 3, seed: 71, ..Default::default() }; + let mut explicit = punctual_options(&[zero; 8], 4, 3); + explicit.seed = old.seed; + let lighting = explicit.lighting.as_mut().unwrap(); + lighting.directional_lights = DirectionalLights::new(&LightingPreset::Neutral.directional_lights()).unwrap(); + assert_eq!(render(old), render(explicit), "zero point/spot sources consume no random values and preserve implicit-three lighting"); + assert_eq!( + render(JobOptions { lighting: Some(StudioLighting::default()), ..old }), + render(JobOptions { lighting: punctual_options(&[zero; 8], 4, 3).lighting, ..old }) + ); + // Existing stochastic families draw exactly the same continuation stream + // when a zero-strength delta family is appended after them. + let mut mixed = old; + mixed.lighting = Some(StudioLighting { + sun: Some(solidcraft_render::job::Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.2, radiance: [2.0; 3] }), + directional_lights: DirectionalLights::new(&LightingPreset::Neutral.directional_lights()).unwrap(), + environment: [0.2; 3], + area_lights: solidcraft_render::job::AreaLights::new(&[solidcraft_render::job::AreaLight { + center: [1.0, 0.0, 4.0], + u: [1.0, 0.0, 0.0], + v: [0.0, -1.0, 0.0], + radiance: [1.0, 2.0, 3.0], + }]) + .unwrap(), + ..Default::default() + }); + let mut with_zero = mixed; + with_zero.lighting.as_mut().unwrap().punctual_lights = solidcraft_render::job::PunctualLights::new(&[zero; 8]).unwrap(); + assert_eq!(render(mixed), render(with_zero)); + let cancel = CancelToken::default(); + let mut task = Task::new(executor.context.clone(), directional_receiver(), request(4), explicit, cancel.clone()).unwrap(); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert!(task.take_preview().is_none() && task.take_linear_exr().is_none()); +} +#[test] +fn gpu_punctual_finite_shadow_blocks_only_before_the_source_and_preserves_physical_falloff() { + let Some(executor) = executor() else { return }; + let light = solidcraft_render::job::PunctualLightOptions { position_mm: [4.0, 0.0, 4.0], ..punctual_point() }; + for blocker_z in [None, Some(2.0), Some(4.0), Some(6.0)] { + let mut scene = directional_receiver(); + if let Some(z) = blocker_z { + let mut blocker = scene.meshes[0].clone(); + blocker.name = "finite shadow panel".into(); + let mesh = Arc::make_mut(&mut blocker.mesh); + mesh.positions = vec![Vec3::new(z - 0.5, -1.0, z), Vec3::new(z + 0.5, -1.0, z), Vec3::new(z + 0.5, 1.0, z), Vec3::new(z - 0.5, 1.0, z)]; + scene.meshes.push(blocker); + } + let options = punctual_options(&[light], 4, 1); + let mut image = request(1); + image.camera.distance = 0.1; + let mut task = Task::new(executor.context.clone(), scene, image.clone(), options, CancelToken::default()).unwrap(); + let mut expected = Vec3::ZERO; + for ordinal in 0..4 { + let p = punctual_primary_point(image.camera, ordinal, options.seed); + let (l, incident) = punctual_oracle(light, p); + let brdf = white().brdf(Vec3::Z, image.camera.back(), l).unwrap(); + if blocker_z != Some(2.0) { + expected += Vec3::new(brdf.x * incident.x, brdf.y * incident.y, brdf.z * incident.z) * l.z; + } + task.complete_sample().unwrap(); + } + let actual = task.read_linear().unwrap()[0]; + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z].map(|v| v / 4.0)) { + assert!((f64::from(*a) - b).abs() < 3e-6, "blocker {blocker_z:?}: {actual:?} vs {expected:?}"); + } + } +} + +#[test] +fn gpu_punctual_samples_match_independent_cone_boundaries_midpoint_high_low_and_counter_carry() { + use solidcraft_render::job::SpotConeOptions; + let Some(executor) = executor() else { return }; + let context = &executor.context; + // A test-only entry calls the production sampler at an independently given + // physical point; it does not launch a camera ray or copy the sampler math. + let source = format!( + "{SHADER}\n@compute @workgroup_size(1) fn punctual_reference() {{ let value=punctual_sample(u.punctual_lights[0],PrecisePoint(u.eye.xyz,u.right.xyz)); accumulation[0]=vec4(value.radiance,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("punctual_reference"), + compilation_options: Default::default(), + cache: None, + }); + let run = |light, point: Vec3, carry| { + let mut task = + Task::new(context.clone(), directional_receiver(), request(1), punctual_options(&[light], 1, 1), CancelToken::default()).unwrap(); + let mut params = task.parameters(1).unwrap(); + let hi = Vec3::new(f64::from(point.x as f32), f64::from(point.y as f32), f64::from(point.z as f32)); + let mut positions = Vec::new(); + scene::vector(&mut positions, hi, 0.0); + scene::vector(&mut positions, point - hi, 0.0); + params[32..64].copy_from_slice(&positions); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + if carry { + let mut bytes = [0; FAILURE_BYTES as usize]; + bytes[8 * 4..9 * 4].copy_from_slice(&u32::MAX.to_le_bytes()); + context.queue.write_buffer(&task.failures, 0, &bytes); + } + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + (task.read_linear().unwrap()[0], task.punctual_diagnostics().unwrap()) + }; + let cone = SpotConeOptions { emitted_axis: [0.0, 0.0, -3.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.8 }; + let light = solidcraft_render::job::PunctualLightOptions { cone: Some(cone), ..punctual_point() }; + let midpoint = ((cone.inner_half_angle_radians.cos() + cone.outer_half_angle_radians.cos()) * 0.5).acos(); + for angle in [0.0, cone.inner_half_angle_radians, midpoint, cone.outer_half_angle_radians, 1.0] { + let point = Vec3::new(4.0 * angle.sin(), 0.0, 4.0 - 4.0 * angle.cos()); + let actual = run(light, point, false); + let expected = punctual_oracle(light, point).1; + for (a, b) in actual.0.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-6, "angle{angle}: {:?} vs {expected:?}", actual.0); + } + assert!(actual.1.is_empty()); + } + let far = solidcraft_render::job::PunctualLightOptions { position_mm: [1e9 - 0.01, 0.0, 0.0], reference_distance_mm: 0.01, ..punctual_point() }; + let point = Vec3::new(1e9 - 0.02, 0.0, 0.0); + let actual = run(far, point, false); + let expected = punctual_oracle(far, point).1; + for (a, b) in actual.0.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-6, "nearby large-world points {:?} vs {expected:?}", actual.0); + } + assert!(actual.1.is_empty()); + let near = solidcraft_render::job::PunctualLightOptions { position_mm: [0.0; 3], intensity: 0.0, ..punctual_point() }; + let actual = run(near, Vec3::ZERO, true); + assert_eq!(actual.0, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(actual.1.near_source, 1_u64 << 32, "near-source counting precedes zero-intensity omission and carries into the high word"); + let excessive = solidcraft_render::job::PunctualLightOptions { + position_mm: [0.0, 0.0, 0.002], + reference_distance_mm: 1e6, + intensity: 64.0, + ..punctual_point() + }; + let actual = run(excessive, Vec3::ZERO, false); + assert_eq!(actual.0, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(actual.1.radiance_limit, 1); + assert_eq!(actual.1.near_source, 0); +} +#[test] +fn gpu_punctual_shadow_offset_crossing_is_reported_without_reversing_or_infinite_connection() { + let Some(executor) = executor() else { return }; + let light = solidcraft_render::job::PunctualLightOptions { position_mm: [0.0, 0.0, 0.01], ..punctual_point() }; + let mut image = request(1); + image.camera.distance = 0.001; + // Keep the original tiny orthographic pixel footprint. Move only its axial + // framing target so the actual GPU primary origin is before the receiver: + // target.z + 4*distance = 1.004, beyond the explicit0.1 primary minimum. + // The former origin0.004 was clipped before any shadow connection existed. + image.camera.target.z = 1.0; + assert_eq!(image.camera.fov, 0.0); + assert_eq!(image.camera.target.z + 4.0 * image.camera.distance, 1.004); + let mut control = + Task::new(executor.context.clone(), directional_receiver(), image.clone(), punctual_options(&[], 1, 1), CancelToken::default()).unwrap(); + control.epsilon = 0.1; + assert!(image.camera.target.z + 4.0 * image.camera.distance > f64::from(control.epsilon)); + control.complete_sample().unwrap(); + assert_eq!(control.read_linear().unwrap()[0], [0.0, 0.0, 0.0, 1.0], "the actual primary sees opaque geometry without any light source"); + assert!(control.punctual_diagnostics().is_none(), "an authored empty punctual-light family has no diagnostic counters"); + drop(control); + let mut task = + Task::new(executor.context.clone(), directional_receiver(), image, punctual_options(&[light], 4, 1), CancelToken::default()).unwrap(); + task.epsilon = 0.1; + for _ in 0..4 { + task.complete_sample().unwrap(); + } + assert_eq!(task.read_linear().unwrap()[0], [0.0, 0.0, 0.0, 1.0]); + let counts = task.punctual_diagnostics().unwrap(); + assert_eq!(counts.shadow_offset_crossed, 4); + assert_eq!(counts.near_source, 0); + assert_eq!(counts.radiance_limit, 0); +} +#[test] +fn gpu_point_delta_visibility_keeps_glass_and_external_beer_without_competing_mis_bias() { + let Some(executor) = executor() else { return }; + let light = solidcraft_render::job::PunctualLightOptions { position_mm: [4.0, 0.0, 4.0], ..punctual_point() }; + for glass in [false, true] { + let mut scene = directional_receiver(); + let optics = solidcraft_render::transmission::Transmission::new(Vec3::new(0.1, 0.2, 0.3), Some(0.7)).unwrap().with_shadow_transmission(true); + if glass { + let mut panel = scene.meshes[0].clone(); + panel.name = "point connection glass".into(); + Arc::make_mut(&mut panel.mesh).positions = + vec![Vec3::new(1.0, -2.0, 2.0), Vec3::new(3.0, -2.0, 2.0), Vec3::new(3.0, 2.0, 2.0), Vec3::new(1.0, 2.0, 2.0)]; + panel.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + panel.transmission = Some(optics); + scene.meshes.push(panel); + } + let mut options = punctual_options(&[light], 4, 1); + if !glass { + options.volume = Some(solidcraft_render::job::volume::HomogeneousVolume { + min_mm: [-10.0, -10.0, 1.0], + max_mm: [10.0, 10.0, 3.0], + extinction_per_mm: 0.1, + scattering_albedo: [0.0; 3], + anisotropy: 0.0, + }); + } + let mut image = request(1); + image.camera.distance = 0.1; + let mut task = Task::new(executor.context.clone(), scene, image.clone(), options, CancelToken::default()).unwrap(); + assert_eq!(options.seed, 43); + assert_eq!(image.camera.fov, 0.0); + let primary_fog_length = if let Some(volume) = options.volume { + // Top retains a slight f64 tilt. The GPU uses the independently + // packed f32 basis, and orthographic primary_ray does not normalize + // its -back direction again. Verify those actual upload words. + let (right, up, back) = image.camera.basis(); + let expected_vectors = [ + back * (4.0 * image.camera.distance), + right * image.camera.half_height() * (f64::from(image.width) / f64::from(image.height)), + up * image.camera.half_height(), + back, + ]; + let params = task.parameters(1).unwrap(); + let vectors: [[f64; 3]; 4] = std::array::from_fn(|vector| { + std::array::from_fn(|axis| { + let at = 32 + vector * 16 + axis * 4; + let packed = f32::from_le_bytes(params[at..at + 4].try_into().unwrap()); + let expected = expected_vectors[vector]; + assert_eq!(packed.to_bits(), ([expected.x, expected.y, expected.z][axis] as f32).to_bits()); + f64::from(packed) + }) + }); + assert_eq!(¶ms[44..48], &0.0_f32.to_le_bytes(), "the actual GPU projection is orthographic"); + let [eye, right, up, back] = vectors; + assert_eq!(back[2], f64::from(1.0_f32)); + assert_eq!(image.camera.target, Vec3::ZERO, "the box and plane use these same camera-relative coordinates"); + // For |uv|<=1, two products and two additions form each origin + // component. 4*EPSILON bounds their gamma4 absolute rounding error + // (also conservatively covers fused evaluation); no image tolerance + // changes. This includes every jittered pixel, not just its centre. + let origin_error: [f64; 3] = + std::array::from_fn(|axis| 4.0 * f64::from(f32::EPSILON) * (eye[axis].abs() + right[axis].abs() + up[axis].abs())); + let origin_min_z = eye[2] - right[2].abs() - up[2].abs() - origin_error[2]; + let origin_max_z = eye[2] + right[2].abs() + up[2].abs() + origin_error[2]; + assert!( + origin_min_z > 0.0 && origin_max_z < volume.min_mm[2], + "every geometry origin is above the receiver and below the complete fog slab" + ); + assert!(origin_min_z / back[2] > f64::from(task.epsilon), "the original forward interval still reaches the receiver"); + let farthest_signed_entry = (volume.max_mm[2] - origin_min_z) / back[2]; + for axis in [0, 1] { + let absolute_bound = + eye[axis].abs() + right[axis].abs() + up[axis].abs() + origin_error[axis] + back[axis].abs() * farthest_signed_entry; + assert!( + -absolute_bound > volume.min_mm[axis] && absolute_bound < volume.max_mm[axis], + "the full signed chord remains inside the finite box laterally" + ); + } + // Origin displacement cancels between the two z-plane endpoints. + let chord = (volume.max_mm[2] - volume.min_mm[2]) / back[2]; + assert_eq!(chord, 2.0); + chord + } else { + 0.0 + }; + let mut expected = Vec3::ZERO; + let mut survivors = [true; 4]; + for ordinal in 0..4 { + let p = punctual_primary_point(image.camera, ordinal, options.seed); + let (direction, incident) = punctual_oracle(light, p); + let brdf = white().brdf(Vec3::Z, image.camera.back(), direction).unwrap(); + let visibility = if glass { + solidcraft_render::transmission::slab(optics, 0.7, direction.z, 1.0, 1.5).unwrap().1 + } else { + Vec3::new(1.0, 1.0, 1.0) * (-0.1 * 2.0 / direction.z).exp() + }; + if !glass { + // Independent scalar PCG law: the first two draws belong to XY; + // the third is the primary analog free flight. No renderer RNG + // or volume helper defines this survival oracle. + let mut state = ordinal.wrapping_mul(0x9e3779b9) ^ options.seed; + let mut draws = [0.0_f64; 3]; + for draw in &mut draws { + state = state.wrapping_mul(747796405).wrapping_add(2891336453); + let word = ((state >> ((state >> 28) + 4)) ^ state).wrapping_mul(277803737); + *draw = f64::from((((word >> 22) ^ word) >> 8) as f32 * (1.0 / 16777216.0)); + } + let travel = -(-draws[2]).ln_1p() / 0.1; + let survives = travel >= primary_fog_length; + assert_eq!(survives, ordinal < 3, "seed43 supplies three survived flights followed by one absorption"); + assert!((travel - primary_fog_length).abs() > 1.8, "the independent decision is separated from f32 rounding: {travel}"); + survivors[ordinal as usize] = survives; + } + // Finite source visibility keeps its own Beer/slab factor above. + // Camera Beer is supplied by analog survival, not another exp factor. + if survivors[ordinal as usize] { + expected += Vec3::new(brdf.x * incident.x * visibility.x, brdf.y * incident.y * visibility.y, brdf.z * incident.z * visibility.z) + * direction.z; + } + task.complete_sample().unwrap(); + let actual = task.read_linear().unwrap()[0]; + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z].map(|v| v / f64::from(ordinal + 1))) { + assert!((f64::from(*a) - b).abs() < 5e-6, "glass{glass} ordinal{ordinal}: {actual:?} vs prefix sum{expected:?}"); + } + assert_eq!(actual[3], 1.0, "opaque receiver or absorbed foreground fog covers every prefix"); + } + if !glass { + assert_eq!(survivors, [true, true, true, false]); + } + } +} +#[test] +fn gpu_point_spot_complete_previews_match_prefixes_and_preserve_exact_final_png_raw_exr() { + use solidcraft_render::job::SpotConeOptions; + let Some(executor) = executor() else { return }; + let sources = [ + punctual_point(), + solidcraft_render::job::PunctualLightOptions { + position_mm: [2.0, 0.0, 4.0], + cone: Some(SpotConeOptions { emitted_axis: [-2.0, 0.0, -4.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.8 }), + ..punctual_point() + }, + ]; + let options = JobOptions { linear_exr: true, ..punctual_options(&sources, 4, 2) }; + let render = |samples, previews, units| { + let mut task = + Task::new(executor.context.clone(), directional_receiver(), request(4), JobOptions { samples, ..options }, CancelToken::default()) + .unwrap(); + task.preview_enabled = previews; + let mut held = Vec::new(); + for _ in 0..20_000 { + let poll = task.step(units).unwrap(); + if let Some(preview) = task.take_preview() { + assert!(task.exr.is_none()); + held.push(preview); + } + if let TaskPoll::Complete(png) = poll { + return (held, png, task.take_linear_exr().unwrap(), task.punctual_diagnostics().unwrap()); + } + } + panic!("bounded point/spot output did not finish") + }; + let (previews, png, exr, counts) = render(4, true, 1); + assert_eq!(previews.iter().map(|p| p.samples_per_pixel).collect::>(), [1, 2, 3]); + assert!(counts.is_empty()); + for preview in previews { + assert_eq!(preview.png, render(preview.samples_per_pixel, false, 4096).1); + } + let reference = render(4, false, 4096); + assert_eq!(png, reference.1); + assert_eq!(exr, reference.2); + assert_eq!(counts, reference.3); +} + +#[test] +fn gpu_punctual_volume_connection_matches_independent_hg_and_finite_beer_without_rng_consumption() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let source = format!( + "{SHADER}\n@compute @workgroup_size(1) fn punctual_volume_reference() {{ var rng=123u; let value=volume_direct(u.eye.xyz,PrecisePoint(u.eye.xyz,vec3(0.0)),vec3(0.0,0.0,1.0),0u,&rng); accumulation[0]=vec4(value,f32(rng)); }}" + ); + 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("punctual_volume_reference"), + compilation_options: Default::default(), + cache: None, + }); + for cone in [ + None, + Some(solidcraft_render::job::SpotConeOptions { + emitted_axis: [-1.0, 0.0, -2.0], + inner_half_angle_radians: 0.2, + outer_half_angle_radians: 0.8, + }), + ] { + let light = solidcraft_render::job::PunctualLightOptions { position_mm: [1.0, 0.0, 4.0], cone, ..punctual_point() }; + let options = JobOptions { + volume: Some(solidcraft_render::job::volume::HomogeneousVolume { + min_mm: [-10.0, -10.0, 1.0], + max_mm: [10.0, 10.0, 3.0], + extinction_per_mm: 0.1, + scattering_albedo: [0.8; 3], + anisotropy: 0.3, + }), + ..punctual_options(&[light], 1, 1) + }; + let mut task = Task::new(context.clone(), directional_receiver(), request(1), options, CancelToken::default()).unwrap(); + let point = Vec3::new(0.0, 0.0, 2.0); + let mut params = task.parameters(1).unwrap(); + let mut position = Vec::new(); + scene::vector(&mut position, point, 0.0); + params[32..48].copy_from_slice(&position); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let (l, incident) = punctual_oracle(light, point); + let g = 0.3_f64; + let denominator = 1.0 + g * g - 2.0 * g * l.z; + let phase = (1.0 - g * g) / (4.0 * std::f64::consts::PI * denominator.powf(1.5)); + let expected = incident * ((-0.1 / l.z).exp() * phase); + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-6, "{actual:?} vs {expected:?}"); + } + assert_eq!(actual[3], 123.0, "point and spot delta connections consume no random values"); + assert!(task.punctual_diagnostics().unwrap().is_empty()); + } +} +#[test] +fn gpu_adaptive_denoised_point_spot_updates_preserve_every_pilot_production_pass_and_final_bytes() { + use solidcraft_render::job::{SpotConeOptions, adaptive::AdaptiveSampling}; + let Some(executor) = executor() else { return }; + let light = solidcraft_render::job::PunctualLightOptions { + cone: Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.8 }), + ..punctual_point() + }; + for denoise in [false, true] { + let options = JobOptions { + denoise, + linear_exr: true, + adaptive: Some(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }), + ..punctual_options(&[light], 16, 2) + }; + let render = |preview_enabled| { + let mut task = Task::new(executor.context.clone(), directional_receiver(), request(1), options, CancelToken::default()).unwrap(); + task.preview_enabled = preview_enabled; + let mut sequences = Vec::new(); + for _ in 0..30_000 { + let poll = task.step(4096).unwrap(); + if let Some(preview) = task.take_preview() { + sequences.push(preview.samples_per_pixel); + assert!(task.exr.is_none()); + } + if let TaskPoll::Complete(png) = poll { + return (sequences, png, task.take_linear_exr().unwrap(), task.sampling_report().unwrap(), task.punctual_diagnostics().unwrap()); + } + } + panic!("bounded adaptive punctual fixture did not finish") + }; + let previewed = render(true); + let final_only = render(false); + assert_eq!(previewed.0, (1..32).collect::>()); + assert!(final_only.0.is_empty()); + assert_eq!(previewed.1, final_only.1); + assert_eq!(previewed.2, final_only.2); + assert_eq!(previewed.3, final_only.3); + assert_eq!(previewed.4, final_only.4); + assert!(previewed.4.is_empty()); + assert_eq!(previewed.3.primary_path_evaluations, 32); + } +} + +#[test] +fn gpu_punctual_offset_preserves_small_shift_after_large_local_barycentric_displacement() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let source = format!( + "{SHADER}\n@compute @workgroup_size(1) fn punctual_offset_reference() {{ let original=PrecisePoint(vec3(1000000.0,0.0,0.0),vec3(-999999.0,0.0,0.0)); let shifted=punctual_offset(original,vec3(0.00001,0.0,0.0)); let canonical=punctual_offset(original,vec3(0.0)); let delta=precise_point_delta(shifted.hi,shifted.lo,canonical.hi,canonical.lo); accumulation[0]=vec4(delta,1.0); let light=punctual_sample(u.punctual_lights[0],original); accumulation[1]=vec4(light.radiance,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("punctual_offset_reference"), + compilation_options: Default::default(), + cache: None, + }); + let light = solidcraft_render::job::PunctualLightOptions { position_mm: [1.01, 0.0, 0.0], reference_distance_mm: 0.01, ..punctual_point() }; + let mut task = Task::new(context.clone(), directional_receiver(), request(2), punctual_options(&[light], 1, 1), CancelToken::default()).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 pixels = task.read_linear().unwrap(); + assert_eq!(pixels[0], [0.00001, 0.0, 0.0, 1.0]); + let expected = punctual_oracle(light, Vec3::new(1.0, 0.0, 0.0)).1; + for (actual, expected) in pixels[1].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*actual) - expected).abs() < 2e-6, "the sampler must canonicalize large local displacement before source subtraction"); + } + assert_eq!(-999999.0_f32 + 0.00001, -999999.0_f32, "the raw local addition would lose the real geometric shift"); +} + +#[test] +fn shared_bvh_node_walk_preserves_original_ordinary_and_compensated_hit_bits() { + // Frozen f53 policy, not re-derived from the new implementation. Only its + // test-local function name changes; it still calls the byte-identical old + // ordered walker for zero low parts. This reference entry inlines three + // real walks, rather than compiling the historical seven-walk main. + let legacy = r#"fn legacy_precise_policy(o: vec3, o_low: vec3, d: vec3, any_hit: bool, excluded: u32, minimum: f32, inside: bool, limit: f32, blocker: f32) -> Hit { + // Dispatch once before traversal. Ordinary rays keep the original lean BVH + // loop, without precision-helper branches inside every candidate/node test. + if all(o_low==vec3(0.0)) { return trace_ordered_within(o,d,any_hit,excluded,minimum,inside,limit,blocker); } + var hit = Hit(limit, 0xffffffffu, vec3(0.0)); + // Project every candidate into the same ray-aligned 2D coordinate system. + // Shared edges then use identical products with opposite signs, avoiding the + // independently rounded barycentric comparisons of Moller-Trumbore. + var kz = 0u; + if abs(d.y)>abs(d.x) { kz=1u; } + if abs(d.z)>abs(d[kz]) { kz=2u; } + let kx=(kz+1u)%3u; let ky=(kx+1u)%3u; + let shear=vec3(d[kx]/d[kz],d[ky]/d[kz],1.0/d[kz]); + let order=select(-1.0,1.0,d[kz]>0.0); + var best=FAR; + // Only candidates near the origin need the integer-defined deltas. The + // rounded origin is within a few ULPs of the true anchor plus offset, so + // boxes grown by that bound reject conservatively: every point the true + // ray reaches at depth t lies in the grown box along the rounded ray at + // the same t. A triangle whose bounds are farther from the rounded origin + // than the near radius uses ordinary arithmetic from it: that error cannot + // reorder such a hit, but it can move the ray across an edge, so decisions + // within the error bound of an edge or bound fall back to the exact path. + let rounded=o+o_low; + let scale=max(max(abs(rounded.x),max(abs(rounded.y),abs(rounded.z))),1.0); + let origin_error=scale*(1.0/1048576.0); + let pad=u.lighting.x+origin_error; + var source: Triangle; + if excluded!=0xffffffffu { source=triangle(excluded); } + let near_radius=scale*(1.0/256.0); + // Children are tested at their parent and visited near-first. The build + // bounds tree depth to 30, so at most 31 nodes are pending. + var stack: array; + var entry: array; + if nodes[0].first == 0xffffffffu { return hit; } + entry[0] = box_entry_padded(nodes[0], rounded, d, hit.distance, pad); + if entry[0] < 0.0 { return hit; } + stack[0] = 0u; + var size = 1u; + loop { + if size == 0u { break; } + size -= 1u; + if entry[size] > hit.distance { continue; } + let node = nodes[stack[size]]; + if node.count == 0u { + if size + 2u > 32u { break; } + let left = box_entry_padded(nodes[node.first], rounded, d, hit.distance, pad); + let right = box_entry_padded(nodes[node.first+1u], rounded, d, hit.distance, pad); + var near_child = node.first; var near_entry = left; + var far_child = node.first+1u; var far_entry = right; + if right >= 0.0 && (left < 0.0 || right < left) { + near_child = node.first+1u; near_entry = right; + far_child = node.first; far_entry = left; + } + if far_entry >= 0.0 { stack[size] = far_child; entry[size] = far_entry; size += 1u; } + if near_entry >= 0.0 { stack[size] = near_child; entry[size] = near_entry; size += 1u; } + continue; + } + for (var i = node.first; i < node.first + node.count; i += 1u) { + if i == excluded { continue; } + // A straight continuation cannot revisit its producing exact plane. + // IDs join only connected, exactly coplanar uploaded f32 triangles + // of one body; curved facets and other bodies remain candidates. + if excluded!=0xffffffffu && geometry[geometry[3]+i]==geometry[geometry[3]+excluded] { continue; } + let t = triangle(i); + let lo=min(t.p0.xyz,min(t.p1.xyz,t.p2.xyz)); + let hi=max(t.p0.xyz,max(t.p1.xyz,t.p2.xyz)); + let gap=max(lo-rounded,rounded-hi); + if any(gap>vec3(near_radius)) { + // The rounded origin is within origin_error of the true one on each + // axis. Bound and edge decisions that close to their threshold could + // flip, while a nearby neighbour across the edge is tested exactly: + // a crossing would fall between them. Such candidates take the exact + // path below. + if any((rounded<=lo-vec3(origin_error))&(d(0.0))) || any((rounded>=hi+vec3(origin_error))&(d>vec3(0.0))) { continue; } + if any((d==vec3(0.0))&((rounded(origin_error))|(rounded>hi+vec3(origin_error)))) { continue; } + let qa=t.p0.xyz-rounded; let qb=t.p1.xyz-rounded; let qc=t.p2.xyz-rounded; + let fa=vec2(qa[kx]-shear.x*qa[kz],qa[ky]-shear.y*qa[kz]); + let fb=vec2(qb[kx]-shear.x*qb[kz],qb[ky]-shear.y*qb[kz]); + let fc=vec2(qc[kx]-shear.x*qc[kz],qc[ky]-shear.y*qc[kz]); + let far_weights=vec3(difference_products(fb.x,fc.y,fb.y,fc.x),difference_products(fc.x,fa.y,fc.y,fa.x),difference_products(fa.x,fb.y,fa.y,fb.x)); + let edge_error=origin_error*vec3(length(fb-fc),length(fc-fa),length(fa-fb)); + if all(abs(far_weights)>edge_error) { + if any(far_weights(0.0)) && any(far_weights>vec3(0.0)) { continue; } + let far_det=far_weights.x+far_weights.y+far_weights.z; + let far_bary=far_weights/far_det; + let far_depth=surface_ray_depth(t,far_bary,rounded,kz); + let far_distance=far_depth*shear.z; + let far_key=far_depth*order; + if far_distance > minimum && far_distance < limit && (far_key < best || (far_key == best && tie_preferred(t,d,inside))) { + hit = Hit(far_distance,i,far_bary); best=far_key; + if any_hit || (far_distance < blocker && (t.base.w<=0.0 || t.coat.w<=0.0)) { return hit; } + } + continue; + } + } + if !triangle_ahead_precise(t,o,o_low,d) { continue; } + let pa=precise_point_delta(t.p0.xyz,vec3(0.0),o,o_low); + let pb=precise_point_delta(t.p1.xyz,vec3(0.0),o,o_low); + let pc=precise_point_delta(t.p2.xyz,vec3(0.0),o,o_low); + let a=vec2(pa[kx]-shear.x*pa[kz],pa[ky]-shear.y*pa[kz]); + let b=vec2(pb[kx]-shear.x*pb[kz],pb[ky]-shear.y*pb[kz]); + let c=vec2(pc[kx]-shear.x*pc[kz],pc[ky]-shear.y*pc[kz]); + let weights=vec3(difference_products(b.x,c.y,b.y,c.x),difference_products(c.x,a.y,c.y,a.x),difference_products(a.x,b.y,a.y,b.x)); + if any(weights(0.0)) && any(weights>vec3(0.0)) { continue; } + let det=weights.x+weights.y+weights.z; + if det==0.0 { continue; } + // Retain all three directly evaluated weights: 1-u-v can erase a + // small corner clearance when the other two weights sum to one. + let bary=weights/det; + let depth=surface_ray_depth_precise(t,bary,o,o_low,kz); + let distance=depth*shear.z; + let key=depth*order; + if excluded!=0xffffffffu && repeated_crossing(t,source,d,inside,distance,origin_error) { continue; } + if distance > minimum && distance < limit && (key < best || (key == best && tie_preferred(t,d,inside))) { + hit = Hit(distance,i,bary); best=key; + if any_hit || (distance < blocker && (t.base.w<=0.0 || t.coat.w<=0.0)) { return hit; } + } + } + } + return hit; +} +"#; + let source = [ + SHADER, + "\n", + legacy, + "\n", + r#" +@compute @workgroup_size(1) fn shared_bvh_policy_reference() { + let excluded=select(0xffffffffu,u32(max(u.back.w,0.0)),u.back.w>=0.0); + let old=legacy_precise_policy(u.eye.xyz,u.right.xyz,u.up.xyz,u.back.z>0.5,excluded,u.back.x,u.back.y>0.5,u.environment.x,u.environment.y); + let combined_hit=trace_precise_within(u.eye.xyz,u.right.xyz,u.up.xyz,u.back.z>0.5,excluded,u.back.x,u.back.y>0.5,u.environment.x,u.environment.y); + accumulation[0]=vec4(select(0.0,1.0,old.triangle==combined_hit.triangle), + select(0.0,1.0,bitcast(old.distance)==bitcast(combined_hit.distance)), + select(0.0,1.0,all(bitcast>(old.bary)==bitcast>(combined_hit.bary))),1.0); + accumulation[1]=vec4(old.distance,f32(old.triangle),old.bary.xy); + accumulation[2]=vec4(combined_hit.distance,f32(combined_hit.triangle),combined_hit.bary.xy); + accumulation[3]=vec4(old.bary.z,combined_hit.bary.z,0.0,1.0); +} +"#, + ] + .concat(); + // Check the generated reference before opening a device: a reserved test + // identifier must report a parse error rather than silently retire its host. + let module = naga::front::wgsl::parse_str(&source).unwrap_or_else(|error| panic!("{}", error.emit_to_string(&source))); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|error| panic!("{}", error.emit_to_string(&source))); + let Some(executor) = executor() else { return }; + let context = &executor.context; + let pipeline = checked_creation(&context.device, || { + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("shared BVH exact legacy policies"), + 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, + }); + Ok(context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("shared_bvh_policy_reference"), + compilation_options: Default::default(), + cache: None, + })) + }) + .unwrap(); + for scene in [directional_receiver(), glass_slab(false)] { + let mut task = + Task::new(context.clone(), scene, request(2), JobOptions { samples: 1, max_depth: 1, ..Default::default() }, CancelToken::default()) + .unwrap(); + let cases = [ + (Vec3::new(0.125, 0.25, 4.0), Vec3::ZERO, -Vec3::Z, 0.0, false, false, None, 1e30, -1.0), + (Vec3::new(0.0, 0.0, 4.0), Vec3::ZERO, -Vec3::Z, 0.0, false, true, None, 1e30, -1.0), + ( + Vec3::new(0.125, 0.25, 4.0), + Vec3::new(1e-10, -2e-10, 0.0), + Vec3::new(0.01, 0.02, -1.0).normalized().unwrap(), + 0.0, + false, + false, + None, + 1e30, + 1.5, + ), + (Vec3::new(0.0, 0.125, 0.5), Vec3::new(0.0, 0.0, -1e-8), -Vec3::Z, 0.0, true, false, None, 1e30, -1.0), + (Vec3::new(0.0, 0.125, 0.5), Vec3::new(0.0, 0.0, 1e-8), Vec3::Z, 0.0, false, false, None, 1e30, -1.0), + (Vec3::new(30.0, 0.125, 4.0), Vec3::new(1e-5, 0.0, 0.0), -Vec3::Z, 0.0, false, true, None, 2.0, 1.0), + (Vec3::new(0.25, 0.25, -0.5), Vec3::new(0.0, 0.0, 1e-8), Vec3::Z, 0.0, true, false, Some(0), 1e30, -1.0), + (Vec3::new(-11.0, 0.125, 0.0), Vec3::new(1e-8, 0.0, 0.0), Vec3::X, 0.0, false, true, None, 1e30, -1.0), + ]; + for (origin, low, direction, minimum, inside, any_hit, excluded, limit, blocker) in cases { + let mut params = task.parameters(1).unwrap(); + let mut vectors = Vec::new(); + scene::vector(&mut vectors, origin, 0.0); + scene::vector(&mut vectors, low, 0.0); + scene::vector(&mut vectors, direction, 0.0); + scene::vector( + &mut vectors, + Vec3::new(minimum, if inside { 1.0 } else { 0.0 }, if any_hit { 1.0 } else { 0.0 }), + excluded.map_or(-1.0, |id| id as f32), + ); + params[32..96].copy_from_slice(&vectors); + vectors.clear(); + scene::vector(&mut vectors, Vec3::new(limit, blocker, 0.0), 0.0); + params[112..128].copy_from_slice(&vectors); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let pixels = task.read_linear().unwrap(); + eprintln!( + "shared-BVH policy origin={origin:?} low={low:?} direction={direction:?} minimum={minimum} inside={inside} any={any_hit} excluded={excluded:?} limit={limit} blocker={blocker}: old(distance,index,baryXY)={:?} combined={:?} baryZ={:?} exactFlags={:?} hitBits={:?}", + pixels[1], + pixels[2], + pixels[3], + pixels[0], + [pixels[1].map(f32::to_bits), pixels[2].map(f32::to_bits), pixels[3].map(f32::to_bits)] + ); + assert_eq!( + pixels[0], [1.0; 4], + "exact triangle/distance/barycentric bits: origin={origin:?} low={low:?} direction={direction:?} inside={inside} any={any_hit} limit={limit} blocker={blocker}" + ); + } + } +} diff --git a/crates/gpu/src/path/volume.wgsl b/crates/gpu/src/path/volume.wgsl index 221b3f367..908eb0e81 100644 --- a/crates/gpu/src/path/volume.wgsl +++ b/crates/gpu/src/path/volume.wgsl @@ -17,6 +17,19 @@ fn volume_segment(o: vec3, d: vec3, limit: f32) -> vec2 { } return vec2(enter,leave); } +fn volume_transmittance_precise(o: vec3, o_low: vec3, d: vec3, distance: f32) -> f32 { + if all(o_low==vec3(0.0)) { return volume_transmittance(o,d,distance); } + if u.volume_min.w<=0.0 { return 1.0; } + let lo=precise_point_delta(u.volume_min.xyz,vec3(0.0),o,o_low); + let hi=precise_point_delta(u.volume_max.xyz,vec3(0.0),o,o_low); + var enter=0.0; var leave=distance; + for(var axis=0u;axis<3u;axis+=1u) { + if d[axis]==0.0 { if lo[axis]>0.0 || hi[axis]<0.0 { return 1.0; } } + else { let a=lo[axis]/d[axis]; let b=hi[axis]/d[axis]; enter=max(enter,min(a,b));leave=min(leave,max(a,b)); } + if enter>=leave { return 1.0; } + } + return exp(-u.volume_min.w*(leave-enter)); +} fn volume_transmittance(o: vec3, d: vec3, distance: f32) -> f32 { let segment = volume_segment(o,d,distance); return exp(-u.volume_min.w*(segment.y-segment.x)); @@ -48,23 +61,26 @@ fn sample_hg(direction: vec3,g:f32,rng: ptr) -> vec3 { fn volume_sample(direction: vec3,rng:ptr) -> vec3 { return sample_hg(direction,u.volume_max.w,rng); } -fn volume_visible(o: vec3, d: vec3, distance: f32) -> ShadowResult { +fn volume_visible(o: vec3, o_low: vec3, d: vec3, distance: f32, punctual: bool) -> ShadowResult { // Volume launches are interior points, not offsets from a surface. Glass is // refused by admission, so the ordinary opaque traversal needs no interface walk. - if emitter_hit_bounded(o,d,0.0).distance(attenuation),attenuation,0u,false); } -fn volume_direct(position: vec3, incoming: vec3, remaining: u32, rng: ptr) -> vec3 { +fn volume_direct(position: vec3, physical: PrecisePoint, incoming: vec3, remaining: u32, rng: ptr) -> vec3 { var radiance=vec3(0.0); let count=u32(u.light_count.w); // One shared visibility evaluation avoids cloning the complete BVH walk // separately for area, environment and sun source families in this branch. - for (var source=0u; source(0.0,0.0,1.0),vec3(0.0),0.0); var distance=FAR; + var origin=position; + var origin_low=vec3(0.0); + var punctual=false; if source, incoming: vec3, remaining: u32, rng: } else if source==count { if u.environment_map.w<=0.0 && !any(u.environment.xyz>vec3(0.0)) { continue; } sample=env_sample(rng); - } else { + } else if source==count+1u { if u.sun_radiance.w<=0.0 { continue; } sample=sun_sample(rng); + } else if sourcevec3(0.0)) { continue; } + sample=EnvironmentSample(light.direction.xyz,light.color.xyz*light.direction.w,1.0); + } else { + punctual=true; + let light=u.punctual_lights[source-count-2u-u32(u.light_count.x)]; + let value=punctual_sample(light,physical); + if value.omitted!=0u { continue; } + sample=EnvironmentSample(value.direction,value.radiance,1.0); + origin=physical.hi; origin_low=physical.lo; + distance=punctual_endpoint(value.distance); } if sample.pdf<=0.0 { continue; } - let visibility=volume_visible(position,sample.direction,distance); let phase=volume_phase(dot(incoming,sample.direction)); - let weight=select(power_weight(sample.pdf,phase*visibility.branch_pdf),1.0,remaining==0u); + if punctual && !punctual_radiance_valid(sample.radiance*phase) { punctual_count(1u); continue; } + let visibility=volume_visible(origin,origin_low,sample.direction,distance,punctual); + let weight=select(power_weight(sample.pdf,phase*visibility.branch_pdf),1.0,remaining==0u || source>=count+2u); radiance+=visibility.transmittance*sample.radiance*(phase*weight/sample.pdf); } return radiance; } + +// Only the primary orthographic optical line uses signed entry. Secondary, +// shadow and perspective rays retain volume_segment's physical forward origin. +// The caller supplies the original forward geometry/emitter endpoint unchanged. +fn volume_orthographic_segment(o: vec3, d: vec3, limit: f32) -> vec2 { + var enter = -FAR; + var leave = limit; + for (var axis = 0u; axis < 3u; axis += 1u) { + if d[axis] == 0.0 { + if o[axis] < u.volume_min[axis] || o[axis] > u.volume_max[axis] { return vec2(0.0); } + } else { + let a = (u.volume_min[axis]-o[axis])/d[axis]; + let b = (u.volume_max[axis]-o[axis])/d[axis]; + enter=max(enter,min(a,b)); + leave=min(leave,max(a,b)); + } + if enter >= leave { return vec2(0.0); } + } + return vec2(enter,leave); +} diff --git a/crates/gpu/src/path/volume_tests.rs b/crates/gpu/src/path/volume_tests.rs index c1f2b3325..5090819a6 100644 --- a/crates/gpu/src/path/volume_tests.rs +++ b/crates/gpu/src/path/volume_tests.rs @@ -16,7 +16,13 @@ fn slab() -> HomogeneousVolume { fn settings(volume: HomogeneousVolume) -> JobOptions { JobOptions { volume: Some(volume), - lighting: Some(StudioLighting { environment: [1.0; 3], sun: None, area_lights: Default::default() }), + lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: Default::default(), + environment: [1.0; 3], + sun: None, + area_lights: Default::default(), + }), samples: 1024, max_depth: 1, seed: 3951, @@ -119,7 +125,7 @@ fn phase_reference(@builtin(global_invocation_id) gid: vec3) { for g in [-0.8, -0.00005, 0.0, 0.00005, 0.8] { let medium = HomogeneousVolume { anisotropy: g, ..slab() }; let mut task = Task::new(context.clone(), empty(), request(64), settings(medium), CancelToken::default()).unwrap(); - context.queue.write_buffer(&task.uniform, 0, &task.parameters(4096)); + context.queue.write_buffer(&task.uniform, 0, &task.parameters(4096).unwrap()); let mut encoder = context.device.create_command_encoder(&Default::default()); { let mut pass = encoder.begin_compute_pass(&Default::default()); @@ -139,3 +145,669 @@ fn phase_reference(@builtin(global_invocation_id) gid: vec3) { } } } + +#[test] +fn gpu_hard_directional_single_scatter_matches_independent_beer_slab_integral() { + use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights}; + let Some(executor) = executor() else { return }; + let medium = slab(); + let source = DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }; + let options = JobOptions { + lighting: Some(StudioLighting { directional_lights: DirectionalLights::new(&[source]).unwrap(), ..Default::default() }), + ..settings(medium) + }; + let mut task = Task::new(executor.context.clone(), empty(), camera(), options, CancelToken::default()).unwrap(); + while task.sample < options.samples { + task.complete_sample().unwrap(); + } + let pixels = task.read_linear().unwrap(); + // Integrate sigma*exp(-sigma*t) camera attenuation times exp(-sigma*t) + // light attenuation and isotropic phase 1/(4*pi), t in [0,2] mm. + let expected = 0.8 * 2.0 * (1.0 - (-2.0_f64).exp()) / (8.0 * std::f64::consts::PI); + for (channel, scale) in [(0, 1.0), (1, 0.5), (2, 0.25)] { + let mean = pixels.iter().map(|p| f64::from(p[channel])).sum::() / pixels.len() as f64; + assert!((mean - expected * scale).abs() < 0.025 * expected * scale, "channel{channel}: {mean} vs {}", expected * scale); + } +} + +// These fixtures distinguish the orthographic optical line from the unchanged +// forward geometry ray. No camera, mesh or render bounds are extended for fog. +#[derive(Clone, Copy, Debug)] +enum OpticalLineEndpoint { + None, + Emitter(f64), + Surface(f64), +} +#[derive(Clone, Copy, Debug)] +struct OpticalLineCase { + name: &'static str, + fog: [f64; 2], + target_z: f64, + distance: f64, + endpoint: OpticalLineEndpoint, + length: f64, +} +fn optical_line_fixture(case: OpticalLineCase) -> (ProductScene, ImageRequest, JobOptions) { + use solidcraft_render::job::{AreaLight, AreaLights, DirectionalLightOptions, DirectionalLights}; + let mut image = request(4); + image.camera.target = Vec3::new(0.0, 0.0, case.target_z); + image.camera.distance = case.distance; + image.camera.fov = 0.0; + image.background = [0; 3]; + image.transparent_background = true; + let mut source = empty(); + let mut lighting = StudioLighting { environment: [0.0; 3], sun: None, ..Default::default() }; + match case.endpoint { + OpticalLineEndpoint::None => {} + OpticalLineEndpoint::Emitter(z) => { + lighting.area_lights = + AreaLights::new(&[AreaLight { center: [0.0, 0.0, z], u: [1000.0, 0.0, 0.0], v: [0.0, 1000.0, 0.0], radiance: [2.0, 3.0, 5.0] }]) + .unwrap(); + } + OpticalLineEndpoint::Surface(z) => { + let mesh = solidcraft_geom::Mesh { + positions: vec![ + Vec3::new(-1000.0, -1000.0, z), + Vec3::new(1000.0, -1000.0, z), + Vec3::new(1000.0, 1000.0, z), + Vec3::new(-1000.0, 1000.0, z), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + source.bounds = mesh.bounds(); + source.meshes.push(solidcraft_render::ProductMesh { + name: "Existing forward-only surface".into(), + mesh: Arc::new(mesh), + color: [128, 64, 32], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.5, 0.25, 0.125), 0.0, 0.5, 1.0).unwrap()), + transmission: None, + faces: Vec::new(), + }); + lighting.directional_lights = + DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: std::f64::consts::PI }]) + .unwrap(); + } + } + let volume = HomogeneousVolume { + min_mm: [-10000.0, -10000.0, case.fog[0]], + max_mm: [10000.0, 10000.0, case.fog[1]], + extinction_per_mm: 1.0 / 128.0, + scattering_albedo: [0.0; 3], + anisotropy: 0.0, + }; + let options = + JobOptions { samples: 16, max_depth: 1, seed: 71, linear_exr: true, volume: Some(volume), lighting: Some(lighting), ..Default::default() }; + (source, image, options) +} +fn optical_line_collision(pixel: u32, ordinal: u32, seed: u32, optical_depth: f64) -> bool { + // Independent scalar PCG stream: two camera jitter draws precede the first + // exponential flight. No production camera/volume/sampler helper is used. + let mut state = pixel ^ ordinal.wrapping_mul(0x9e3779b9) ^ 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(); + let _ = random(); + let hazard = -(1.0 - random()).ln(); + // Thresholds are independently separated from a GPU log/rounding boundary; + // coverage remains exact, with no numerical acceptance band around it. + assert!((hazard - optical_depth).abs() > 1e-5 || optical_depth == 0.0); + optical_depth > 0.0 && hazard < optical_depth +} +fn optical_line_expected(case: OpticalLineCase, pixel: u32, samples: u32, seed: u32) -> [f64; 4] { + let hits = (0..samples).filter(|ordinal| optical_line_collision(pixel, *ordinal, seed, case.length / 128.0)).count() as u32; + let survival = f64::from(samples - hits) / f64::from(samples); + let visible = match case.endpoint { + OpticalLineEndpoint::None => false, + OpticalLineEndpoint::Emitter(z) | OpticalLineEndpoint::Surface(z) => z < case.target_z + case.distance * 4.0, + }; + let radiance = match case.endpoint { + OpticalLineEndpoint::Emitter(_) if visible => [2.0, 3.0, 5.0], + OpticalLineEndpoint::Surface(z) if visible => { + // Exact normal-incidence Lambert substrate (IOR1 removes specular), + // pi-radiance delta source, and its independent forward Beer segment. + let shadow = (case.fog[1] - case.fog[0].max(z)).max(0.0); + let attenuation = (-shadow / 128.0).exp(); + [0.5 * attenuation, 0.25 * attenuation, 0.125 * attenuation] + } + _ => [0.0; 3], + }; + [radiance[0] * survival, radiance[1] * survival, radiance[2] * survival, if visible { 1.0 } else { f64::from(hits) / f64::from(samples) }] +} +fn optical_line_check(case: OpticalLineCase, samples: u32, seed: u32, pixels: &[[f32; 4]], errors: &mut Vec) { + assert_eq!(pixels.len(), 16); + let mut failures = 0; + for (pixel, actual) in pixels.iter().enumerate() { + let expected = optical_line_expected(case, pixel as u32, samples, seed); + let alpha = expected[3] as f32; + if actual[3] != alpha || (0..3).any(|c| (f64::from(actual[c]) - expected[c]).abs() > 2e-6) { + failures += 1; + if errors.len() < 32 { + errors.push(format!("{} prefix{samples} pixel{pixel}: {actual:?} vs {expected:?}", case.name)); + } + } + } + eprintln!( + "orthographic signed optical line case={} prefix={samples} length={} failures={failures} first={:?}", + case.name, case.length, pixels[0] + ); +} + +fn optical_line_raw(bytes: &[u8], width: usize, height: usize) -> Vec<[f32; 4]> { + // Independent uncompressed FLOAT OpenEXR wire reader. The numerical oracle + // above never calls the production volume, sampler or image codec. + let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); + assert_eq!((word(0), word(4)), (20_000_630, 2)); + let string = |at: &mut usize| { + let start = *at; + *at += bytes[start..].iter().position(|b| *b == 0).unwrap() + 1; + &bytes[start..*at - 1] + }; + let mut at = 8; + let (mut channels, mut window, mut compression) = (false, false, false); + while bytes[at] != 0 { + let name = string(&mut at); + let kind = string(&mut at); + let len = word(at) as usize; + at += 4; + let data = &bytes[at..at + len]; + at += len; + match name { + b"channels" => { + assert_eq!(kind, b"chlist"); + let mut c = 0; + for name in [b"A", b"B", b"G", b"R"] { + assert_eq!(&data[c..c + 2], &[name[0], 0]); + c += 2; + assert_eq!(u32::from_le_bytes(data[c..c + 4].try_into().unwrap()), 2); + assert_eq!(&data[c + 4..c + 8], &[0; 4]); + assert_eq!(u32::from_le_bytes(data[c + 8..c + 12].try_into().unwrap()), 1); + assert_eq!(u32::from_le_bytes(data[c + 12..c + 16].try_into().unwrap()), 1); + c += 16; + } + assert_eq!(&data[c..], &[0]); + channels = true; + } + b"compression" => { + assert_eq!(kind, b"compression"); + assert_eq!(data, &[0]); + compression = true; + } + b"dataWindow" => { + assert_eq!(kind, b"box2i"); + let bounds: Vec<_> = data.as_chunks::<4>().0.iter().map(|x| i32::from_le_bytes(*x)).collect(); + assert_eq!(bounds, [0, 0, width as i32 - 1, height as i32 - 1]); + window = true; + } + _ => {} + } + } + assert!(channels && window && compression); + at += 1; + let mut pixels = vec![[0.0; 4]; width * height]; + for y in 0..height { + let offset = u64::from_le_bytes(bytes[at + y * 8..at + y * 8 + 8].try_into().unwrap()) as usize; + assert_eq!((word(offset) as usize, word(offset + 4) as usize), (y, width * 16)); + for x in 0..width { + for (channel, plane) in [(0, 3), (1, 2), (2, 1), (3, 0)] { + pixels[y * width + x][channel] = f32::from_bits(word(offset + 8 + (plane * width + x) * 4)); + } + } + } + pixels +} +fn optical_line_finish(task: &mut Task, units: usize) -> (Vec, Vec) { + for _ in 0..20000 { + if let TaskPoll::Complete(png) = task.step(units).unwrap() { + let raw = task.take_linear_exr().unwrap(); + assert!(task.take_linear_exr().is_none()); + return (png, raw); + } + } + panic!("bounded optical-line finishing did not complete") +} +fn optical_line_png_alpha(case: OpticalLineCase, samples: u32, seed: u32, png: &[u8], errors: &mut Vec) { + let image = image::load_from_memory(png).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (4, 4)); + for (pixel, actual) in image.pixels().enumerate() { + let alpha = optical_line_expected(case, pixel as u32, samples, seed)[3]; + let expected = (alpha * 255.0).round() as u8; + if actual[3] != expected && errors.len() < 32 { + errors.push(format!("{} PNG prefix{samples} alpha pixel{pixel}: {} vs {expected}", case.name, actual[3])); + } + } +} + +#[test] +fn gpu_orthographic_volume_signed_line_absorption_matches_every_complete_prefix() { + let Some(executor) = executor() else { return }; + let cases = [ + OpticalLineCase { + name: "empty_origin_inside_slab", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::None, + length: 200.0, + }, + OpticalLineCase { + name: "empty_box_entirely_before_origin", + fog: [450.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::None, + length: 50.0, + }, + OpticalLineCase { + name: "empty_box_after_origin", + fog: [-500.0, -300.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::None, + length: 200.0, + }, + OpticalLineCase { + name: "emitter_after_foreground_fog", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::Emitter(0.0), + length: 200.0, + }, + OpticalLineCase { + name: "emitter_terminates_inside_fog", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::Emitter(350.0), + length: 150.0, + }, + OpticalLineCase { + name: "opaque_terminates_inside_fog", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::Surface(350.0), + length: 150.0, + }, + OpticalLineCase { + name: "opaque_before_background_fog", + fog: [-500.0, -300.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::Surface(0.0), + length: 0.0, + }, + OpticalLineCase { + name: "negative_geometry_hit_stays_invisible", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::Surface(550.0), + length: 200.0, + }, + ]; + let mut errors = Vec::new(); + for case in cases { + let (source, image, options) = optical_line_fixture(case); + let original_camera = image.camera; + let mut task = Task::new(executor.context.clone(), source, image, options, CancelToken::default()).unwrap(); + let packed = task.parameters(16).unwrap(); + assert_eq!(f32::from_le_bytes(packed[44..48].try_into().unwrap()), 0.0); + assert_eq!(f64::from(f32::from_le_bytes(packed[40..44].try_into().unwrap())) + case.target_z, case.target_z + case.distance * 4.0); + for samples in 1..=options.samples { + task.complete_sample().unwrap(); + optical_line_check(case, samples, options.seed, &task.read_linear().unwrap(), &mut errors); + } + let linear = task.read_linear().unwrap(); + let (png, raw) = optical_line_finish(&mut task, 7); + let raw = optical_line_raw(&raw, 4, 4); + assert_eq!(raw, linear, "{} raw master preserves actual final film bits", case.name); + optical_line_check(case, options.samples, options.seed, &raw, &mut errors); + optical_line_png_alpha(case, options.samples, options.seed, &png, &mut errors); + assert_eq!(task.request.camera, original_camera, "fog must not mutate the authored camera"); + } + assert!(errors.is_empty(), "strict signed optical-line absorption failures: {errors:#?}"); +} + +// Preserve the existing GPU/shared Display contract: preview PNGs encode the +// exact stored f32 film coverage, then round8bit. Every film prefix is separately +// checked against the independent rational count with exact f32 equality. +fn optical_line_preview_png_alpha(case: OpticalLineCase, samples: u32, seed: u32, png: &[u8], errors: &mut Vec) { + let image = image::load_from_memory(png).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (4, 4)); + for (pixel, actual) in image.pixels().enumerate() { + let alpha = optical_line_expected(case, pixel as u32, samples, seed)[3] as f32; + let expected = (f64::from(alpha) * 255.0).round() as u8; + if actual[3] != expected && errors.len() < 32 { + errors.push(format!("{} PNG prefix{samples} alpha pixel{pixel}: {} vs {expected}", case.name, actual[3])); + } + } +} + +#[test] +fn gpu_orthographic_volume_axial_origin_changes_preserve_lines_framing_and_raw_prefixes() { + let Some(executor) = executor() else { return }; + let mut baseline = None; + let mut baseline_frame: Option> = None; + let mut errors = Vec::new(); + for (target_z, distance) in [(-200.0, 100.0), (0.0, 100.0), (200.0, 100.0), (0.0, 50.0), (0.0, 150.0)] { + let case = OpticalLineCase { + name: "translated_or_rescaled_infinite_line", + fog: [300.0, 500.0], + target_z, + distance, + endpoint: OpticalLineEndpoint::Emitter(0.0), + length: 200.0, + }; + let (source, image, options) = optical_line_fixture(case); + let camera = image.camera; + let mut task = Task::new(executor.context.clone(), source, image, options, CancelToken::default()).unwrap(); + let packet = task.parameters(16).unwrap(); + assert_eq!(f32::from_le_bytes(packet[48..52].try_into().unwrap()), (distance * 0.4) as f32); + if let Some(frame) = &baseline_frame { + if distance == 100.0 { + assert_eq!(&packet[48..96], frame.as_slice(), "axial target translation keeps exact right/up/back and orthographic framing"); + } else { + assert_ne!( + &packet[48..80], + &frame[..32], + "real distance change rescales the orthographic span; only uniform-coverage radiance is invariant" + ); + } + } else { + baseline_frame = Some(packet[48..96].to_vec()); + } + let mut prefixes = Vec::new(); + for count in 1..=options.samples { + task.complete_sample().unwrap(); + let pixels = task.read_linear().unwrap(); + optical_line_check(case, count, options.seed, &pixels, &mut errors); + prefixes.push(pixels); + } + let (png, raw) = optical_line_finish(&mut task, 7); + optical_line_check(case, options.samples, options.seed, &optical_line_raw(&raw, 4, 4), &mut errors); + assert_eq!(task.request.camera, camera); + let output = (prefixes, png, raw); + if let Some(baseline) = &baseline { + assert_eq!(&output, baseline, "only the arbitrary launch-plane location or homogeneous coverage scale changed"); + } else { + baseline = Some(output); + } + } + assert!(errors.is_empty(), "translated signed optical-line errors: {errors:#?}"); +} + +#[test] +fn gpu_orthographic_volume_every_preview_raw_and_cancel_are_quantum_safe() { + let Some(executor) = executor() else { return }; + let case = OpticalLineCase { + name: "quantum_complete_prefixes", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::None, + length: 200.0, + }; + let run = |units| { + let (source, image, options) = optical_line_fixture(case); + let mut task = Task::new(executor.context.clone(), source, image, options, CancelToken::default()).unwrap(); + task.preview_enabled = true; + let (mut prefixes, mut previews, mut uniforms, mut errors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for _ in 0..20000 { + if task.sample < options.samples && uniforms.len() == task.sample as usize { + uniforms.push(task.parameters(16).unwrap()); + } + let before = task.sample; + let poll = task.step(units).unwrap(); + if task.sample > before { + assert_eq!(task.sample, before + 1); + let pixels = task.read_linear().unwrap(); + optical_line_check(case, task.sample, options.seed, &pixels, &mut errors); + prefixes.push(pixels); + } + if let Some(preview) = task.take_preview() { + assert_eq!(preview.samples_per_pixel, previews.len() as u32 + 1); + optical_line_preview_png_alpha(case, preview.samples_per_pixel, options.seed, &preview.png, &mut errors); + previews.push(preview.png); + } + if let TaskPoll::Complete(png) = poll { + let raw = task.take_linear_exr().unwrap(); + assert!(task.take_linear_exr().is_none()); + assert_eq!((prefixes.len(), previews.len(), uniforms.len()), (16, 15, 16)); + assert_eq!(optical_line_raw(&raw, 4, 4), *prefixes.last().unwrap()); + optical_line_png_alpha(case, 16, options.seed, &png, &mut errors); + assert!(errors.is_empty(), "quantum{units}: {errors:#?}"); + return (prefixes, previews, uniforms, png, raw); + } + } + panic!("bounded progressive volume output did not complete") + }; + assert_eq!(run(1), run(16384), "all completed previews, full input packets, PNG/raw and film prefixes survive output quantum changes exactly"); + let (source, mut image, options) = optical_line_fixture(case); + image.width = 16; + image.height = 16; + let token = CancelToken::default(); + let mut task = Task::new(executor.context, source, image, options, token.clone()).unwrap(); + task.preview_enabled = true; + task.dispatch().unwrap(); + assert_eq!(task.sample, 0); + assert!(task.offset > 0 && task.offset < 256, "cancel a real partial pass"); + token.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert!(task.take_preview().is_none() && task.take_linear_exr().is_none()); +} + +#[test] +fn gpu_orthographic_volume_cancel_releases_work_before_exact_retained_metadata() { + use solidcraft_render::job::{JobId, Phase}; + let Some(executor) = executor() else { return }; + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + let case = OpticalLineCase { + name: "real_host_cancel", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::None, + length: 200.0, + }; + let (source, mut image, mut options) = optical_line_fixture(case); + image.width = 128; + image.height = 128; + options.samples = 4096; + let retained = options.retained_bytes().unwrap() + image.retained_resource_metadata_bytes(); + let admission = host.admit(&source, &image, options).unwrap(); + assert!(admission.estimated_total_bytes > retained); + assert_eq!(host.admitted_bytes(), 0, "preflight leaves no reserved work"); + let handle = host.submit_with_options(JobId { session: 918, serial: 1, generation: 1 }, 1, source, image, options).unwrap(); + handle.cancel().unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Cancelled); + let deadline = Instant::now() + std::time::Duration::from_secs(5); + while !handle.work_released() { + assert!(Instant::now() < deadline, "cancelled GPU volume work did not drain"); + std::thread::yield_now(); + } + assert!(handle.frame().unwrap().is_none() && handle.preview().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), retained, "only actual options and fixed request headers remain owned by Record"); + drop(handle); + while host.admitted_bytes() != 0 { + assert!(Instant::now() < deadline, "last Record did not release retained metadata"); + std::thread::yield_now(); + } + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn gpu_volume_signed_primary_preserves_old_perspective_lens_none_and_zero_bytes() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let old_hook = r#" let segment=volume_segment(o+o_low,d,min(hit.distance,emitter_distance));"#; + let new_hook = r#" var segment=vec2(0.0); + if bounce==0u && u.eye.w<=0.5 { + // The orthographic camera has no physical eye plane. Its fog + // line starts at the finite box entry, even before the artificial + // geometry origin; the existing forward endpoint stays fixed. + segment=volume_orthographic_segment(o+o_low,d,min(hit.distance,emitter_distance)); + } else { + segment=volume_segment(o+o_low,d,min(hit.distance,emitter_distance)); + }"#; + let helper = r#"// Only the primary orthographic optical line uses signed entry. Secondary, +// shadow and perspective rays retain volume_segment's physical forward origin. +// The caller supplies the original forward geometry/emitter endpoint unchanged. +fn volume_orthographic_segment(o: vec3, d: vec3, limit: f32) -> vec2 { + var enter = -FAR; + var leave = limit; + for (var axis = 0u; axis < 3u; axis += 1u) { + if d[axis] == 0.0 { + if o[axis] < u.volume_min[axis] || o[axis] > u.volume_max[axis] { return vec2(0.0); } + } else { + let a = (u.volume_min[axis]-o[axis])/d[axis]; + let b = (u.volume_max[axis]-o[axis])/d[axis]; + enter=max(enter,min(a,b)); + leave=min(leave,max(a,b)); + } + if enter >= leave { return vec2(0.0); } + } + return vec2(enter,leave); +} +"#; + // The archived pre-GPU12 control fingerprint remains historical evidence: + // f373400816e40e803691ceb847d8c9d7983fd4744c3874a322363810c14b6d6c. + // Upstream changed map filtering and producer specialization. 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 }; + assert_eq!(shader.matches(new_hook).count(), 1); + assert_eq!(shader.matches(helper).count(), 1); + let helper_block = format!("\n{helper}"); + let helper_offset = shader.find(&helper_block).unwrap(); + let original = shader.replacen(new_hook, old_hook, 1).replacen(&helper_block, "", 1); + assert_eq!(original.matches(old_hook).count(), 1); + let mut restored = original.replacen(old_hook, new_hook, 1); + restored.insert_str(helper_offset, &helper_block); + assert_eq!(restored, shader, "the whole-source inverse restores only the signed primary hook/helper"); + let creating = scopes(&context.device); + let module = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("exact old signed-line control"), + source: wgpu::ShaderSource::Wgsl(original.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: &module, + entry_point: Some("main"), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &[("OPAQUE_SCENE", f64::from(u8::from(opaque))), ("HAS_TEXTURES", 0.0)], + ..Default::default() + }, + cache: None, + }); + checked(creating).unwrap(); + warm_up(&context.device, &context.queue, &pipeline, &placeholder_bind(&context.device, &context.layout, 7).unwrap(), &context.healthy) + .unwrap(); + pipeline + }; + let pipelines = [old_pipeline(true), old_pipeline(false)]; + let mut inactive_baseline = None; + for mode in 0..8 { + let case = OpticalLineCase { + name: "unchanged_routes", + fog: [300.0, 500.0], + target_z: 0.0, + distance: 100.0, + endpoint: OpticalLineEndpoint::Emitter(0.0), + length: 0.0, + }; + let (source, mut image, mut options) = optical_line_fixture(case); + match mode { + 0 => options.volume = None, + 1 => options.volume.as_mut().unwrap().extinction_per_mm = 0.0, + 2 => image.camera.fov = 0.4, + 3 => { + image.camera.fov = 0.4; + options.lens = Some(solidcraft_render::job::ThinLens { aperture_radius_mm: 2.0, focus_distance_mm: 100.0 }); + } + 4 => { + let volume = options.volume.as_mut().unwrap(); + volume.min_mm[2] = 100.0; + volume.max_mm[2] = 300.0; + } + 5 => { + let volume = options.volume.as_mut().unwrap(); + volume.min_mm[0] = 1000.0; + volume.max_mm[0] = 2000.0; + } + 6 => { + image.camera.fov = 0.4; + let volume = options.volume.as_mut().unwrap(); + volume.min_mm[2] = 0.0; + volume.max_mm[2] = 200.0; + } + 7 => { + image.camera.fov = 0.4; + options.lens = Some(solidcraft_render::job::ThinLens { aperture_radius_mm: 2.0, focus_distance_mm: 100.0 }); + let volume = options.volume.as_mut().unwrap(); + volume.min_mm[2] = 0.0; + volume.max_mm[2] = 200.0; + } + _ => 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. + let opaque = mode < 2; + assert_eq!(use_opaque_pipeline(&source, options), opaque); + assert!(image.textures.is_none() && !options.nested_media); + let pipeline = &pipelines[usize::from(!opaque)]; + let run = |old: bool| { + let mut task = Task::new(context.clone(), source.clone(), image.clone(), options, CancelToken::default()).unwrap(); + assert_eq!((task.opaque_scene, task.has_textures, task.options.nested_media), (opaque, false, false)); + let (mut uniforms, mut prefixes) = (Vec::new(), Vec::new()); + for sample in 0..options.samples { + assert_eq!((task.sample, task.offset, task.lane), (sample, 0, 0)); + let params = task.parameters(16).unwrap(); + uniforms.push(params.clone()); + if old { + let checking = scopes(&context.device); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(16u32.div_ceil(PATH_WORKGROUP_SIZE), 1, 1); + } + let submission = context.queue.submit([encoder.finish()]); + checked(checking).unwrap(); + context.wait(submission, TIMEOUT).unwrap(); + task.sample += 1; + } else { + task.complete_sample().unwrap(); + } + prefixes.push(task.read_linear().unwrap()); + } + let (png, raw) = optical_line_finish(&mut task, 7); + assert_eq!(optical_line_raw(&raw, 4, 4), *prefixes.last().unwrap()); + (uniforms, prefixes, png, raw) + }; + let old = run(true); + let new = run(false); + assert_eq!(old, new, "mode{mode}: complete input packets, each film prefix and PNG/raw must remain byte-identical"); + if mode == 0 { + inactive_baseline = Some(new); + } else if mode == 1 { + assert_eq!(inactive_baseline.as_ref().unwrap(), &new, "Some(0) preserves full None uniforms, stream and outputs exactly"); + } + } +} diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 4d0380e65..b35af7bf2 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -24,6 +24,7 @@ pub use clouds::{CELL_SIZE, Cell, CloudFilter, CloudStyle, ColorMode, FILTERS, G #[cfg(not(target_arch = "wasm32"))] mod msaa_check; mod oit; +mod product_highlights; #[cfg(not(target_arch = "wasm32"))] pub use msaa_check::MsaaCheck; @@ -2159,6 +2160,10 @@ struct Cut { /// The viewport's pipelines and the scenes uploaded to one device, for one kind of target. pub struct Renderer { + /// Lazily created depth-only pipelines for feedback over a live product image. + product_depth: Option, + /// The offscreen cache contains transparent product highlights rather than shaded colour. + product_highlights: bool, /// What the last frame drew ([`Renderer::stats`]). stats: DrawStatsHandle, /// What the frame `prepare` drew offscreen (supersampled, or for see-through surfaces), @@ -3136,6 +3141,8 @@ impl Renderer { let (depth_reset, section_stencil) = resets.join(); let oit = oit.join(); Renderer { + product_depth: None, + product_highlights: false, ao: ao.join(), ground_ao: ground_ao.join(), ground_ao_key: None, @@ -3574,6 +3581,11 @@ impl Renderer { pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) { let res = self; let cb = frame; + if res.product_highlights { + res.product_highlights = false; + res.ss_key = None; + res.cached = None; + } let key = frame_key(cb); if can_reuse(res.ss_ready && res.ss.is_some(), res.ss_key, key) { // A still frame shows the picture as it is; the first one filters it down once. @@ -3587,28 +3599,8 @@ impl Renderer { } res.cached = None; if cb.product { - // A large product scene can exceed what the device will allocate. Its upload runs under - // its own error scopes, so the failure reaches the preview instead of the device's - // uncaptured-error handler, and nothing half-uploaded is drawn. - let scopes = - [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation].map(|f| device.push_error_scope(f)); - res.product.take(device, queue, &res.uniform, &res.uniform_bgl, cb.key, &cb.slot, None, false); - let mut failed = None; - for scope in scopes.into_iter().rev() { - if let Some(e) = crate::popped(scope.pop()) { - failed.get_or_insert(e.to_string()); - } - } - if let Some(error) = failed { - log::error!("product preview upload failed: {error}"); - res.product = Batches { key: Some(cb.key), ..Batches::default() }; - if let Some(Ok(mut sink)) = cb.upload_error.as_ref().map(|e| e.lock()) { - *sink = Some(error); - } - } + res.prepare_product_geometry(device, queue, cb); res.product.sort_glass(queue, cb.back); - res.highlight.take(device, queue, &res.uniform, &res.uniform_bgl, cb.hl_key, &cb.hl_slot, None, false); - queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out, res.target.reversed_depth())); // The product picture goes through the window's pass too: offscreen when the targets // differ or it is drawn smaller, else straight into the window's pass. res.ss_ready = (res.window_differs() || cb.ssaa != 1.0) && res.supersample(device, encoder, cb, false); @@ -4268,7 +4260,7 @@ impl Renderer { }; // See-through surfaces (order-independent transparency) and a window pass of another kind // (samples, depth) need a frame of their own, even at the viewport's own size. - let needs_own = see_through || self.window_differs(); + let needs_own = see_through || self.window_differs() || self.product_highlights; let samples = self.target.samples; let mut drawn = None; for _ in 0..FRAME_TRIES { @@ -4365,7 +4357,11 @@ impl Renderer { let (Some(p), Some(t), true) = (&self.oit, &self.oit_targets, see_through) else { let mut first = pass(encoder, true); first.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0); - self.draw(cb, &mut first, Phase::All, &tally); + if self.product_highlights { + self.draw_product_highlights(&mut first, &tally); + } else { + self.draw(cb, &mut first, Phase::All, &tally); + } drop(first); self.ss_stats = tally.stats(); return true; @@ -5355,6 +5351,18 @@ mod glass_tests { /// Render `frame` through `r` into a fresh 64 × 64 target and read the pixels back. fn render_frame(r: &mut Renderer, device: &wgpu::Device, queue: &wgpu::Queue, frame: &Frame, with_depth: bool) -> Vec { + render_frame_kind(r, device, queue, frame, with_depth, false, wgpu::Color::WHITE) + } + + fn render_frame_kind( + r: &mut Renderer, + device: &wgpu::Device, + queue: &wgpu::Queue, + frame: &Frame, + with_depth: bool, + highlights: bool, + background: wgpu::Color, + ) -> Vec { const SIZE: u32 = 64; let depth = crate::depth_format(device, true); let format = wgpu::TextureFormat::Rgba8Unorm; @@ -5375,7 +5383,11 @@ mod glass_tests { let depth_tex = with_depth.then(|| texture(depth, wgpu::TextureUsages::RENDER_ATTACHMENT)); let depth_view = depth_tex.as_ref().map(|t| t.create_view(&Default::default())); let mut encoder = device.create_command_encoder(&Default::default()); - r.prepare(device, queue, &mut encoder, frame); + if highlights { + r.prepare_product_highlights(device, queue, &mut encoder, frame); + } else { + r.prepare(device, queue, &mut encoder, frame); + } { let mut pass = encoder .begin_render_pass(&wgpu::RenderPassDescriptor { @@ -5384,7 +5396,7 @@ mod glass_tests { view: &color_view, depth_slice: None, resolve_target: None, - ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: wgpu::StoreOp::Store }, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(background), store: wgpu::StoreOp::Store }, })], depth_stencil_attachment: depth_view.as_ref().map(|view| wgpu::RenderPassDepthStencilAttachment { view, @@ -5401,7 +5413,11 @@ mod glass_tests { multiview_mask: None, }) .forget_lifetime(); - r.paint(frame, &mut pass, [0.0, 0.0, SIZE as f32, SIZE as f32]); + if highlights { + r.paint_product_highlights(frame, &mut pass, [0.0, 0.0, SIZE as f32, SIZE as f32]); + } else { + r.paint(frame, &mut pass, [0.0, 0.0, SIZE as f32, SIZE as f32]); + } } let read = device.create_buffer(&wgpu::BufferDescriptor { label: None, @@ -5474,6 +5490,186 @@ mod glass_tests { scene } + #[test] + fn product_highlights_keep_live_colour_and_occlude_faces_with_both_product_vertex_layouts_and_msaa() { + let (_, device, queue) = match crate::open_headless() { + Ok(opened) => opened, + Err(error) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("skipping: {error}"); + return; + } + Err(error) => panic!("required GPU unavailable: {error}"), + }; + let format = wgpu::TextureFormat::Rgba8Unorm; + let background = wgpu::Color { r: 17.0 / 255.0, g: 33.0 / 255.0, b: 65.0 / 255.0, a: 1.0 }; + let surface = solidcraft_render::surface::OpaqueSurface::new(Vec3::new(0.8, 0.1, 0.1), 0.0, 0.6, 1.5).unwrap(); + for depth in [wgpu::TextureFormat::Depth24PlusStencil8, crate::depth_format(&device, true)] { + for samples in [1, 4] { + let target = GpuTarget { format, depth: Some(depth), samples, tess: false, oit: false }; + let window = GpuTarget { format, depth: None, samples: 1, tess: false, oit: false }; + let mut renderer = Renderer::with_window_target(&device, target, window, None); + // Preserve the original built/PBR cases, and exercise the new + // upstream open-body batch with the same independent pixels. + for layout in 0_u64..3 { + let pbr = layout == 1; + let open = layout == 2; + let mut scene = GpuScene::default(); + let red = scene.color([255, 0, 0, 255]); + for p in [[-10.0, -10.0, 0.0], [10.0, -10.0, 0.0], [10.0, 10.0, 0.0], [-10.0, -10.0, 0.0], [10.0, 10.0, 0.0], [-10.0, 10.0, 0.0]] + { + if pbr { + scene.pbr_tri(p, [0.0, 0.0, 1.0], surface); + } else if open { + scene.open_tri(p, [0.0; 3], red); + } else { + scene.tri(p, [0.0; 3], red); + } + } + let mut highlight = GpuScene::default(); + let green = highlight.color([0, 255, 0, 128]); + let red = highlight.color([255, 0, 0, 255]); + for p in [[-8.0, -4.0, 1.0], [-1.0, -4.0, 1.0], [-4.5, 4.0, 1.0]] { + if open { + highlight.open_tri(p, [0.0; 3], green); + } else { + highlight.tri(p, [0.0; 3], green); + } + } + for p in [[1.0, -4.0, -1.0], [8.0, -4.0, -1.0], [4.5, 4.0, -1.0]] { + if open { + highlight.open_tri(p, [0.0; 3], red); + } else { + highlight.tri(p, [0.0; 3], red); + } + } + let mut frame = test_frame(scene, 1.0); + frame.product = true; + frame.key = 1 + layout; + frame.hl_key = 1 + layout; + frame.hl_slot = Arc::new(Mutex::new(Some(highlight))); + let normal = render_frame_kind(&mut renderer, &device, &queue, &frame, false, false, background); + let overlay = render_frame_kind(&mut renderer, &device, &queue, &frame, false, true, background); + let pixel = + |bytes: &[u8], x: usize, y: usize| -> [u8; 4] { bytes[((y * 64 + x) * 4)..((y * 64 + x) * 4 + 4)].try_into().unwrap() }; + let unchanged = [17, 33, 65, 255]; + assert_eq!( + pixel(&overlay, 32, 32), + unchanged, + "depth-only product colour must not replace live pixels: {depth:?}, {samples}x, layout={layout}" + ); + assert_eq!( + pixel(&overlay, 46, 32), + unchanged, + "the rear target is hidden by actual product depth: {depth:?}, {samples}x, layout={layout}" + ); + assert_eq!(pixel(&overlay, 3, 3), unchanged, "unselected product pixels remain exactly the live image colour"); + let selected = pixel(&overlay, 18, 32); + assert!( + selected[1] > 120 && selected[0] < 17 && selected[2] < 65, + "the visible target is transparently composited: {selected:?}" + ); + let again = render_frame_kind(&mut renderer, &device, &queue, &frame, false, true, background); + assert_eq!(overlay, again, "a cached overlay preserves its transparency"); + assert_eq!( + normal, + render_frame_kind(&mut renderer, &device, &queue, &frame, false, false, background), + "returning to ordinary product rendering cannot reuse the transparent overlay" + ); + assert_ne!(normal, overlay); + } + // Real imported-body feedback uses shared triangles and placements, + // not the loose triangle lists above. Compare both streams with a + // separately submitted face control over the same product depth. + for selected in [false, true] { + for flat in [false, true] { + let mut scene = GpuScene::default(); + let product_color = scene.color([255, 0, 0, 255]); + for p in + [[-10.0, -10.0, 0.0], [10.0, -10.0, 0.0], [10.0, 10.0, 0.0], [-10.0, -10.0, 0.0], [10.0, 10.0, 0.0], [-10.0, 10.0, 0.0]] + { + scene.tri(p, [0.0; 3], product_color); + } + let mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-3.5, -4.0, 0.0), Vec3::new(3.5, -4.0, 0.0), Vec3::new(0.0, 4.0, 0.0)], + normals: if flat { vec![Vec3::Z; 3] } else { vec![Vec3::Z, Vec3::new(0.6, 0.0, 0.8), Vec3::new(-0.6, 0.0, 0.8)] }, + triangles: vec![[0, 1, 2]], + ..Default::default() + }; + let shared = Arc::new(SharedTris::new(&mesh)); + assert_eq!(shared.flat, flat, "exercise both actual shared-triangle vertex layouts"); + let mut control = GpuScene::default(); + let front = control.color([0, 255, 0, 128]); + let rear = control.color([255, 0, 0, 255]); + let ignored_color = control.color([0, 0, 255, 255]); + let mut instances = InstancedMesh { + key: 1, + tris: shared, + instances: Vec::new(), + look: InstanceLook::Opaque, + levels: Vec::new(), + closed: false, + }; + for (x, z, color) in [(-4.5, 1.0, front), (4.5, -1.0, rear)] { + let rows = [[1.0, 0.0, 0.0, x], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, z]]; + instances.place(rows, color); + for (p, n) in mesh.positions.iter().zip(&mesh.normals) { + control.tri((*p + Vec3::new(f64::from(x), 0.0, f64::from(z))).to_f32(), n.to_f32(), color); + } + } + assert_eq!(instances.instances.len(), 2 * INSTANCE_SIZE, "front and occluded rear targets are actual placements"); + let mut ignored = instances.clone(); + ignored.look = InstanceLook::Faded; + ignored.instances.clear(); + ignored.place([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 2.0]], ignored_color); + let mut highlight = GpuScene { palette: control.palette.clone(), ..Default::default() }; + if selected { + highlight.selected_instanced = vec![instances, ignored]; + } else { + highlight.hover_instanced = vec![instances, ignored]; + } + let mut frame = test_frame(scene, 1.0); + frame.product = true; + frame.key = 100 + 2 * u64::from(selected) + u64::from(flat); + frame.hl_key = frame.key; + frame.hl_slot = Arc::new(Mutex::new(Some(control))); + let reference = render_frame_kind(&mut renderer, &device, &queue, &frame, false, true, background); + frame.hl_key += 1000; + frame.hl_slot = Arc::new(Mutex::new(Some(highlight))); + let overlay = render_frame_kind(&mut renderer, &device, &queue, &frame, false, true, background); + let pixel = + |bytes: &[u8], x: usize, y: usize| -> [u8; 4] { bytes[((y * 64 + x) * 4)..((y * 64 + x) * 4 + 4)].try_into().unwrap() }; + let unchanged = [17, 33, 65, 255]; + assert_eq!(pixel(&overlay, 3, 3), unchanged, "instanced feedback must not repaint the live image"); + assert_eq!(pixel(&overlay, 46, 32), unchanged, "product depth must hide the rear placement"); + assert_eq!(pixel(&overlay, 32, 32), unchanged, "non-opaque feedback placements are not part of this pass"); + let expected = pixel(&reference, 18, 32); + assert_ne!(expected, unchanged, "the independent face control must visibly composite its translucent front target"); + let actual = pixel(&overlay, 18, 32); + // Derivative flat normals and interpolated face normals can + // straddle one RGBA8 rounding step; alpha compositing must + // otherwise match the independently submitted face control. + assert!( + actual.iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 1), + "instanced feedback must draw and alpha-blend its visible target: selected={selected}, flat={flat}, {depth:?}, {samples}x: {actual:?} vs {expected:?}" + ); + assert_eq!( + overlay, + render_frame_kind(&mut renderer, &device, &queue, &frame, false, true, background), + "cached instanced feedback must retain identical pixels" + ); + frame.hl_key += 1; + frame.hl_slot = Arc::new(Mutex::new(Some(GpuScene::default()))); + let cleared = render_frame_kind(&mut renderer, &device, &queue, &frame, false, true, background); + assert!( + cleared.as_chunks::<4>().0.iter().all(|pixel| *pixel == unchanged), + "clearing the target restores every original live-image pixel" + ); + } + } + } + } + } + #[test] fn a_cached_cloud_picture_follows_its_style_without_uploading_again() { let Some((_, device, queue)) = crate::open_headless().ok() else { return }; diff --git a/crates/gpu/src/view/product_highlights.rs b/crates/gpu/src/view/product_highlights.rs new file mode 100644 index 000000000..267858de6 --- /dev/null +++ b/crates/gpu/src/view/product_highlights.rs @@ -0,0 +1,259 @@ +//! Depth-correct selection feedback over independently rendered product pixels. +//! The offscreen target contains only highlights; product colour is never drawn into it. +use super::*; + +const DEPTH_SHADER: &str = r#" +struct U { vp: mat4x4 }; +@group(0) @binding(0) var u: U; +@vertex +fn vs(@location(0) p: vec3) -> @builtin(position) vec4 { + return u.vp * vec4(p, 1.0); +} +@vertex +fn vs_inst(@location(0) p: vec3, @location(3) r0: vec4, @location(4) r1: vec4, @location(5) r2: vec4) -> @builtin(position) vec4 { + let q = vec4(p, 1.0); + return u.vp * vec4(dot(r0,q), dot(r1,q), dot(r2,q), 1.0); +} +@fragment +fn fs() -> @location(0) vec4 { return vec4(0.0); } +"#; + +pub(super) struct DepthPipelines { + built: wgpu::RenderPipeline, + pbr: wgpu::RenderPipeline, + planned: wgpu::RenderPipeline, + instanced: wgpu::RenderPipeline, + feedback_smooth: wgpu::RenderPipeline, + feedback_flat: wgpu::RenderPipeline, +} +impl DepthPipelines { + fn new(device: &wgpu::Device, uniform: &wgpu::BindGroupLayout, target: GpuTarget) -> Self { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("sc_product_highlight_depth"), + source: wgpu::ShaderSource::Wgsl(DEPTH_SHADER.into()), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_product_highlight_depth"), + bind_group_layouts: &[Some(uniform)], + immediate_size: 0, + }); + let pipeline = |buffers: &[Option>], instanced: bool| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_product_highlight_depth"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(if instanced { "vs_inst" } else { "vs" }), + buffers, + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: target.depth.map(|format| wgpu::DepthStencilState { + format, + depth_write_enabled: Some(true), + depth_compare: Some(depth_compare(target.reversed_depth(), wgpu::CompareFunction::Less)), + stencil: Default::default(), + bias: depth_bias(target.reversed_depth(), FACE_BIAS), + }), + multisample: wgpu::MultisampleState { count: target.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + targets: &[Some(wgpu::ColorTargetState { format: target.format, blend: None, write_mask: wgpu::ColorWrites::empty() })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + // Whole-body feedback keeps its shared mesh and placements on the GPU. + // Its palette may be translucent, unlike ordinary opaque model instances. + let feedback_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("sc_product_highlight_instanced"), + source: wgpu::ShaderSource::Wgsl(format!("{SHADER}\n{}", pbr::SOURCE).into()), + }); + let feedback = |source: TriSource| { + let fragment = source.fragment("fs_tri"); + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_product_highlight_instanced"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &feedback_module, + entry_point: Some(source.entry()), + buffers: &[Some(shared_layout()), Some(instance_layout())], + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: highlight_depth(target.depth), + multisample: wgpu::MultisampleState { count: target.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &feedback_module, + entry_point: Some(&fragment), + targets: &[Some(wgpu::ColorTargetState { + format: target.format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + Self { + built: pipeline(&[Some(tri_layout())], false), + pbr: pipeline(&[Some(pbr_layout())], false), + planned: pipeline(&[Some(planned_layout()), Some(color_layout())], false), + instanced: pipeline(&[Some(shared_layout()), Some(instance_layout())], true), + feedback_smooth: feedback(TriSource::Instanced), + feedback_flat: feedback(TriSource::InstancedFlat), + } + } +} + +impl Renderer { + /// Shared product upload and camera setup for ordinary colour and transparent feedback. + pub(super) fn prepare_product_geometry(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame: &Frame) -> bool { + let scopes = [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation] + .map(|filter| device.push_error_scope(filter)); + self.product.take(device, queue, &self.uniform, &self.uniform_bgl, frame.key, &frame.slot, None, false); + let mut failed = None; + for scope in scopes.into_iter().rev() { + if let Some(error) = crate::popped(scope.pop()) { + failed.get_or_insert(error.to_string()); + } + } + if let Some(error) = failed { + log::error!("product preview upload failed: {error}"); + self.product = Batches { key: Some(frame.key), ..Batches::default() }; + if let Some(Ok(mut sink)) = frame.upload_error.as_ref().map(|sink| sink.lock()) { + *sink = Some(error); + } + return false; + } + self.highlight.take(device, queue, &self.uniform, &self.uniform_bgl, frame.hl_key, &frame.hl_slot, None, false); + queue.write_buffer( + &self.uniform, + 0, + &uniform_bytes(frame, frame.size_px[0], frame.size_px[1], self.linear_out, self.target.reversed_depth()), + ); + true + } + + /// Prepare a transparent product selection/hover image with its own depth and MSAA. + /// Emit this instead of the ordinary product callback when live pixels are displayed. + pub fn prepare_product_highlights(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) { + let key = frame_key(frame); + if self.product_highlights && can_reuse(self.ss_ready && self.ss.is_some(), self.ss_key, key) { + let filter = self.ss_scaled && self.cached.is_none(); + if filter { + self.cache_picture(device, encoder, frame.size_px); + } + self.ss_stats = DrawStats { draw_calls: u32::from(filter), ..DrawStats::default() }; + return; + } + self.product_highlights = true; + self.cached = None; + self.ss_ready = false; + self.ss_key = None; + // Feedback without product depth would light occluded faces as if visible. + if !frame.product || self.target.depth.is_none() { + return; + } + if self.product_depth.is_none() { + self.product_depth = Some(DepthPipelines::new(device, &self.uniform_bgl, self.target)); + } + if !self.prepare_product_geometry(device, queue, frame) { + return; + } + self.ss_ready = self.supersample(device, encoder, frame, false); + self.ss_key = self.ss_ready.then_some(key); + } + + /// Alpha-blit only the prepared feedback. There is no shaded-model fallback. + pub fn paint_product_highlights(&self, frame: &Frame, pass: &mut wgpu::RenderPass<'static>, viewport: [f32; 4]) { + if self.product_highlights && self.ss_ready { + self.paint(frame, pass, viewport); + } + } + + pub(super) fn draw_product_highlights(&self, pass: &mut wgpu::RenderPass<'static>, tally: &Tally) { + let Some(depth) = &self.product_depth else { return }; + let triangles = |pass: &mut wgpu::RenderPass<'static>, pipeline: &wgpu::RenderPipeline, batch: &Option| { + if let Some(batch) = batch { + pass.set_pipeline(pipeline); + for (buffer, count) in &batch.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + tally.triangles(*count, 1); + } + } + }; + let lines = |pass: &mut wgpu::RenderPass<'static>, pipeline: &wgpu::RenderPipeline, batch: &Option| { + if let Some(batch) = batch { + pass.set_pipeline(pipeline); + for (buffer, count) in &batch.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..6, 0..*count); + tally.segments(*count); + } + } + }; + let model = &self.product; + pass.set_bind_group(0, scene_bind(model, &self.bind), &[]); + triangles(pass, &depth.built, &model.tris); + // Open bodies still occlude feedback; their new upstream batch only + // changes section crossing counts, which product feedback does not use. + triangles(pass, &depth.built, &model.open_tris); + triangles(pass, &depth.pbr, &model.pbr); + for key in &model.block_order { + if let Some(block) = model.blocks.get(key).filter(|block| block.class(TriClass::Opaque).is_some()) { + pass.set_pipeline(&depth.built); + block.draw(pass, TriClass::Opaque, tally); + } + } + for draw in model.planned.iter().filter(|draw| draw.class == TriClass::Opaque) { + pass.set_pipeline(&depth.planned); + pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); + pass.set_vertex_buffer(1, draw.colors.slice(..)); + pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); + tally.triangles(draw.mesh.index_count, 1); + } + for draw in model.instanced.iter().filter(|draw| draw.look == InstanceLook::Opaque) { + draw.draw(pass, &depth.instanced, &depth.instanced, tally); + } + // Render's build_highlight emits self-contained mesh triangles/edges, including + // whole bodies; it intentionally does not reference the Design model's GPU plans. + let highlight = &self.highlight; + pass.set_bind_group(0, scene_bind(highlight, &self.bind), &[]); + for draw in highlight.hover_instanced.iter().chain(&highlight.selected_instanced).filter(|draw| draw.look == InstanceLook::Opaque) { + draw.draw(pass, &depth.feedback_smooth, &depth.feedback_flat, tally); + } + for key in &highlight.block_order { + if let Some(block) = highlight.blocks.get(key).filter(|block| block.class(TriClass::Opaque).is_some()) { + pass.set_pipeline(&self.tri_hl); + block.draw(pass, TriClass::Opaque, tally); + } + } + triangles(pass, &self.tri_hl, &highlight.tris); + triangles(pass, &self.tri_hl, &highlight.open_tris); + lines(pass, &self.line_hidden, &highlight.hidden); + lines(pass, &self.line, &highlight.lines); + lines(pass, &self.guide_line, &highlight.guide_lines); + triangles(pass, &self.trans, &highlight.trans); + triangles(pass, &self.guide_trans, &highlight.guide_trans); + triangles(pass, &self.xray, &highlight.xray); + lines(pass, &self.overlay, &highlight.overlays); + } +} + +#[cfg(test)] +mod tests { + #[test] + fn product_depth_shader_uses_only_the_shared_camera_and_validates() { + let module = naga::front::wgsl::parse_str(super::DEPTH_SHADER).unwrap(); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap(); + assert_eq!(module.entry_points.len(), 3); + } +} diff --git a/crates/io/src/vfs.rs b/crates/io/src/vfs.rs index ac21126dd..1a9ed9d16 100644 --- a/crates/io/src/vfs.rs +++ b/crates/io/src/vfs.rs @@ -217,6 +217,18 @@ pub fn design_folder_refusal_in(dir: &std::path::Path, home: Option<&std::path:: } impl PathScope { + /// Actual owned path buffer capacities only. The enclosing owner accounts + /// its PathScope/Vec headers once with size_of, without revealing paths. + pub fn retained_heap_bytes(&self) -> Result { + let fail = || Error::new(ErrorKind::InvalidData, "path scope byte overflow"); + let slots = self.roots.capacity().checked_add(self.design_roots.capacity()).ok_or_else(fail)?; + let mut bytes = slots.checked_mul(std::mem::size_of::()).ok_or_else(fail)?; + for path in self.roots.iter().chain(&self.design_roots) { + bytes = bytes.checked_add(path.capacity()).ok_or_else(fail)?; + } + u64::try_from(bytes).map_err(|_| fail()) + } + /// Confine file access to `roots` (resolved now; folders that don't exist are left out, so an /// empty scope refuses every path). pub fn new(roots: impl IntoIterator) -> PathScope { @@ -1183,4 +1195,25 @@ mod tests { let dir = std::env::temp_dir().to_string_lossy().to_string(); assert!(super::read(&dir, 1024).is_err()); } + #[test] + fn retained_scope_heap_counts_actual_path_and_vector_capacities_without_exposing_or_changing_roots() { + let mut root = std::path::PathBuf::new(); + root.reserve(512); + root.push("/owned/root"); + let mut design = std::path::PathBuf::new(); + design.reserve(256); + design.push("/owned/design"); + let mut roots = Vec::with_capacity(4); + roots.push(root); + let mut design_roots = Vec::with_capacity(3); + design_roots.push(design); + let expected = ((roots.capacity() + design_roots.capacity()) * std::mem::size_of::() + + roots[0].capacity() + + design_roots[0].capacity()) as u64; + let scope = super::PathScope { roots, design_roots }; + let before = scope.clone(); + assert_eq!(scope.retained_heap_bytes().unwrap(), expected); + assert_eq!(scope, before); + assert_eq!(super::PathScope::default().retained_heap_bytes().unwrap(), 0); + } } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index bb8d17aaa..7ae0b9241 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -10,21 +10,23 @@ workspace = true [features] default = [] -raytrace-cpu = [] +raytrace-cpu = ["dep:robust"] [dependencies] solidcore-record = { workspace = true } solidcraft-geom = { workspace = true } serde = { workspace = true } +serde_json = { workspace = true } image = { workspace = true, features = ["jpeg"] } moxcms = { workspace = true } png = { workspace = true } +robust = { workspace = true, optional = true } sha2 = { workspace = true } web-time = { workspace = true } weezl = { workspace = true } [dev-dependencies] -serde_json = { workspace = true } +flate2 = "1" [[example]] name = "cpu_resource_smoke" diff --git a/crates/render/src/anisotropic_surface.rs b/crates/render/src/anisotropic_surface.rs index 25dfb47c9..0c284731f 100644 --- a/crates/render/src/anisotropic_surface.rs +++ b/crates/render/src/anisotropic_surface.rs @@ -111,7 +111,8 @@ impl VisualFrame { } } -/// A bounded opaque response with two perceptual roughness axes in [0.045, 1]. +/// An opaque response whose public constructor admits two roughness axes in [0.045, 1]. +/// The crate-private isotropic optical adapter also retains validated aging finishes down to 0.02. /// Alpha is roughness squared, matching [`OpaqueSurface`]. #[derive(Clone, Copy, Debug, PartialEq)] pub struct AnisotropicSurface { @@ -143,6 +144,14 @@ impl AnisotropicSurface { Ok(Self { base, roughness_y }) } + /// Reuse one validated opaque optical finish for an isotropic VNDF. The + /// authored runtime finish may have roughness 0.02; independently authored + /// anisotropic axes continue through new() with their unchanged 0.045 bound. + #[cfg(any(feature = "raytrace-cpu", test))] + pub(crate) fn from_isotropic_optical(base: OpaqueSurface) -> Self { + Self { base, roughness_y: base.roughness() } + } + /// Admitted perceptual roughness along visual X and Y. pub fn roughness(self) -> [f64; 2] { [self.base.roughness(), self.roughness_y] diff --git a/crates/render/src/anisotropic_surface_tests.rs b/crates/render/src/anisotropic_surface_tests.rs index 6e963aebb..980c07c2f 100644 --- a/crates/render/src/anisotropic_surface_tests.rs +++ b/crates/render/src/anisotropic_surface_tests.rs @@ -275,3 +275,23 @@ fn broad_lobe_importance_estimate_agrees_with_integrated_energy() { assert!(sampled.x > 0.0 && sampled.x <= 1.001); close_rgb(integrated, sampled, 0.003); } + +#[test] +fn authored_isotropic_optical_finish_keeps_point_zero_two_without_broadening_public_axes() { + let old = OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.2), 1.0, MIN_ROUGHNESS, 1.5).unwrap(); + let finish = old.with_authored_finish(old.base_color(), 1.0, 0.02).unwrap(); + assert_eq!(finish.roughness(), 0.02); + assert!(OpaqueSurface::new(old.base_color(), 1.0, 0.02, 1.5).is_err()); + assert!(AnisotropicSurface::new(old.base_color(), 1.0, 0.02, 0.02, 1.5).is_err()); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, 0.02f64.next_down(), 1.0f64.next_up()] { + assert!(old.with_authored_finish(old.base_color(), 1.0, bad).is_err()); + } + assert!(old.with_authored_finish(Vec3::new(f64::NAN, 0.0, 0.0), 1.0, 0.02).is_err()); + assert!(old.with_authored_finish(Vec3::X, -0.01, 0.02).is_err()); + let finish = AnisotropicSurface::from_isotropic_optical(finish); + assert_eq!(finish.roughness(), [0.02; 2]); + let d = 1.0 / (PI * 0.02_f64.powi(4)); + close(finish.distribution(frame(), Vec3::Z).unwrap(), d, 1e-14); + close(finish.visible_reflection_pdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap(), d / 4.0, 1e-14); + close_rgb(finish.specular_brdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap(), old.base_color() * (d / 4.0), 1e-14); +} diff --git a/crates/render/src/film.rs b/crates/render/src/film.rs index 95a7c1082..510dd0ee7 100644 --- a/crates/render/src/film.rs +++ b/crates/render/src/film.rs @@ -21,6 +21,10 @@ use crate::job::{CancelToken, ErrorCode, JobError, Result}; +// Standalone adaptive camera-film foundation. No CPU request/producer is installed. +#[path = "film_adaptive.rs"] +pub mod adaptive; + #[path = "film_png.rs"] pub mod png; diff --git a/crates/render/src/film_adaptive.rs b/crates/render/src/film_adaptive.rs new file mode 100644 index 000000000..6cac19967 --- /dev/null +++ b/crates/render/src/film_adaptive.rs @@ -0,0 +1,396 @@ +//! CPU camera film for the explicit independent-pilot image continuation. +//! Independent pilots allocate fixed production counts. Pilot radiance is discarded, +//! and complete passes borrow exact integer counts without retaining a new snapshot. +use super::{invalid, limit}; +use crate::job::{ + CancelToken, CpuBudget, CpuProgressiveOptions, ErrorCode, JobError, Result, + adaptive::{AdaptivePreview, AdaptiveSampling, PreviewStage, SamplingReport}, +}; + +#[derive(Clone, Copy, Default)] +struct Moments { + // Pilot: Welford RGBA mean/M2. Production: sum.rgb, with M2 unused. + value: [f64; 4], + m2: [f64; 4], +} +/// Exact counts have a separate, borrowed plane so image finishing need not +/// reconstruct integer coverage from FLOAT32 alpha or allocate another image. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PixelCounts { + covered: u16, + samples: u16, + planned: u16, +} +impl PixelCounts { + pub fn covered(self) -> u16 { + self.covered + } + pub fn samples(self) -> u16 { + self.samples + } + pub fn alpha8(self) -> Result { + let samples = u32::from(self.samples); + let covered = u32::from(self.covered); + if samples == 0 || covered > samples { + return Err(invalid("adaptive coverage has no valid sample denominator")); + } + u8::try_from((covered * 510 + samples) / (samples * 2)).map_err(|_| invalid("adaptive coverage exceeds one byte")) + } +} +pub struct CountsPlane { + values: Vec, +} +impl CountsPlane { + pub fn len(&self) -> usize { + self.values.len() + } + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } + pub fn pixel(&self, index: usize) -> Result { + self.values.get(index).copied().ok_or_else(|| invalid("adaptive count index is outside the complete plane")) + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Stage { + Pilot, + Reset, + Production, + Done, +} +/// A stream identity for an existing counter sampler. Production keeps the +/// original seed and zero-based ordinals. Pilots use a distinct fixed seed tag. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SamplingIdentity { + pub seed: u32, + pub ordinal: u32, + pub stage: PreviewStage, +} +/// Two prepaid arrays, one ordered update/skip per pixel per complete sweep. +/// ImageTask includes required_bytes in the SAME existing job lease. The counts +/// remain borrowed by finishing, never copied into an unbilled snapshot plane. +pub struct AdaptiveCameraFilm { + width: u32, + height: u32, + maximum: u32, + seed: u32, + options: AdaptiveSampling, + moments: Vec, + counts: CountsPlane, + count: usize, + completed: u32, + next_pixel: usize, + stage: Stage, + report: SamplingReport, + production_evaluations: u64, +} +/// Borrowing this view prevents reset/add/skip until finishing releases it. +/// It is neither an encoded image nor a transferable retained snapshot/lease. +pub struct AdaptivePass<'a> { + film: &'a AdaptiveCameraFilm, +} +impl AdaptivePass<'_> { + pub fn metadata(&self) -> AdaptivePreview { + let pilot = self.film.stage == Stage::Pilot; + AdaptivePreview { + stage: if pilot { PreviewStage::Pilot } else { PreviewStage::Production }, + completed: self.film.completed, + target: if pilot { self.film.options.pilot_samples } else { self.film.maximum }, + pilot_samples: self.film.options.pilot_samples, + minimum_production_samples: self.film.options.min_samples, + maximum_production_samples: self.film.maximum, + } + } + pub fn counts(&self) -> &CountsPlane { + &self.film.counts + } + /// Premultiplied linear radiance and coverage, before any float32 conversion, + /// denoising, exposure or display transform. The denominator is pixel-specific. + pub fn pixel(&self, index: usize) -> Result<([f64; 3], f64)> { + let counts = self.counts().pixel(index)?; + if counts.samples == 0 || counts.covered > counts.samples { + return Err(invalid("adaptive pass has invalid exact coverage")); + } + let value = self.film.moments.get(index).ok_or_else(|| invalid("adaptive resolve index exceeds admission"))?.value; + let divisor = if self.film.stage == Stage::Pilot { 1.0 } else { f64::from(counts.samples) }; + Ok(([value[0] / divisor, value[1] / divisor, value[2] / divisor], f64::from(counts.covered) / f64::from(counts.samples))) + } +} +impl AdaptiveCameraFilm { + /// The existing CPU profile includes all pilots plus the production cap. + /// GPU AdaptiveSampling chooses the statistical policy; no CPU cap is raised. + pub fn required_bytes(width: u32, height: u32, production: CpuProgressiveOptions, options: AdaptiveSampling, budget: CpuBudget) -> Result { + options.validate(production.samples_per_pixel)?; + let total = options.pilot_samples.checked_add(production.samples_per_pixel).ok_or_else(|| limit("adaptive camera target overflow"))?; + budget.validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: total, ..production }))?; + (u64::from(width) * u64::from(height)) + .checked_mul((std::mem::size_of::() + std::mem::size_of::()) as u64) + .and_then(|bytes| bytes.checked_add(std::mem::size_of::() as u64)) + .filter(|bytes| *bytes <= budget.limits().max_job_bytes) + .ok_or_else(|| limit("adaptive film storage exceeds the unchanged CPU profile")) + } + pub fn new( + width: u32, + height: u32, + production: CpuProgressiveOptions, + options: AdaptiveSampling, + budget: CpuBudget, + admitted_bytes: u64, + cancel: &CancelToken, + ) -> Result { + cancel.check()?; + let required = Self::required_bytes(width, height, production, options, budget)?; + if admitted_bytes < required { + return Err(limit("adaptive film is not prepaid by the owning image job")); + } + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| limit("adaptive film exceeds the address space"))?; + let mut moments = Vec::new(); + let mut counts = Vec::new(); + moments.try_reserve_exact(count).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve adaptive moments"))?; + cancel.check()?; + counts.try_reserve_exact(count).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve exact adaptive counts"))?; + if moments.capacity() != count || counts.capacity() != count { + return Err(limit("actual adaptive film capacity exceeds admission")); + } + cancel.check()?; + Ok(Self { + width, + height, + maximum: production.samples_per_pixel, + seed: production.seed, + options, + moments, + counts: CountsPlane { values: counts }, + count, + completed: 0, + next_pixel: 0, + stage: Stage::Pilot, + report: SamplingReport { + pilot_samples_per_pixel: options.pilot_samples, + minimum_production_samples: production.samples_per_pixel, + maximum_production_samples: 0, + production_samples: 0, + primary_path_evaluations: 0, + pixels_at_cap: 0, + transmission_strata: 1, + }, + production_evaluations: 0, + }) + } + pub fn dimensions(&self) -> [u32; 2] { + [self.width, self.height] + } + pub fn initialized(&self) -> usize { + self.counts.values.len() + } + pub fn ready(&self) -> bool { + self.initialized() == self.count && self.moments.len() == self.count + } + pub fn initialize_one(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + cancel.check()?; + if self.ready() || self.moments.len() != self.counts.values.len() { + return Err(invalid("adaptive film initialization is complete or inconsistent")); + } + charge()?; + cancel.check()?; + self.moments.push(Moments::default()); + self.counts.values.push(PixelCounts::default()); + Ok(()) + } + pub fn next_pixel(&self) -> usize { + self.next_pixel + } + pub fn completed_passes(&self) -> u32 { + if self.stage == Stage::Pilot { self.completed } else { self.options.pilot_samples + self.completed } + } + pub fn final_pass_target(&self) -> u32 { + self.options.pilot_samples + self.maximum + } + pub fn is_final(&self) -> bool { + self.stage == Stage::Done + } + fn ordered(&self, index: usize) -> Result { + if !self.ready() || self.stage == Stage::Reset || self.stage == Stage::Done || index != self.next_pixel { + return Err(invalid("adaptive film needs the next pixel in a sampling sweep")); + } + self.counts.pixel(index) + } + /// None means this production pixel has already reached its pilot allocation; + /// the caller must perform skip_one WITHOUT tracing or consuming a variate. + pub fn sampling_identity(&self, index: usize) -> Result> { + let counts = self.ordered(index)?; + if self.stage == Stage::Pilot { + if self.completed >= self.options.pilot_samples { + return Err(invalid("complete pilots require an explicit production reset")); + } + return Ok(Some(SamplingIdentity { seed: self.seed ^ 0xa511_e9b3, ordinal: self.completed, stage: PreviewStage::Pilot })); + } + if u32::from(counts.samples) >= u32::from(counts.planned) { + return Ok(None); + } + Ok(Some(SamplingIdentity { seed: self.seed, ordinal: self.completed, stage: PreviewStage::Production })) + } + fn advance(&mut self) { + self.next_pixel += 1; + if self.next_pixel == self.count { + self.next_pixel = 0; + self.completed += 1; + if self.stage == Stage::Production && self.completed == self.maximum { + self.stage = Stage::Done; + } + } + } + /// Pilot moments/production sums and exact counts form ONE transaction. Every + /// fallible check, work debit and cancellation check precedes both writes. + pub fn add( + &mut self, + index: usize, + identity: SamplingIdentity, + rgb: [f64; 3], + covered: bool, + cancel: &CancelToken, + charge: &mut impl FnMut() -> Result<()>, + ) -> Result<()> { + cancel.check()?; + let expected = self.sampling_identity(index)?.ok_or_else(|| invalid("stopped adaptive pixel cannot accept another sample"))?; + if identity != expected { + return Err(invalid("adaptive stream/ordinal does not match the captured sweep")); + } + if rgb.iter().any(|value| !value.is_finite() || !(0.0..=1e12).contains(value)) || (!covered && rgb != [0.0; 3]) { + return Err(invalid("invalid adaptive premultiplied camera radiance or coverage")); + } + let mut moments = self.moments.get(index).copied().ok_or_else(|| invalid("adaptive moments disappeared"))?; + let mut counts = self.counts.pixel(index)?; + let samples = counts.samples.checked_add(1).ok_or_else(|| limit("adaptive sample count overflow"))?; + if u32::from(samples) != self.completed + 1 { + return Err(invalid("adaptive pixel count disagrees with its active ordinal")); + } + let hits = + counts.covered.checked_add(u16::from(covered)).filter(|hits| *hits <= samples).ok_or_else(|| limit("adaptive coverage overflow"))?; + if self.stage == Stage::Pilot { + let value = [rgb[0], rgb[1], rgb[2], f64::from(u8::from(covered))]; + for ((mean, m2), value) in moments.value.iter_mut().zip(moments.m2.iter_mut()).zip(value) { + let delta = value - *mean; + *mean += delta / f64::from(samples); + *m2 += delta * (value - *mean); + } + if u32::from(samples) == self.options.pilot_samples { + counts.planned = u16::try_from(self.options.target(moments.value, moments.m2, self.maximum)?) + .map_err(|_| limit("adaptive target exceeds exact count representation"))?; + } + } else { + for (sum, value) in moments.value.iter_mut().take(3).zip(rgb) { + *sum += value; + if !sum.is_finite() || *sum < 0.0 || *sum > f64::from(self.maximum) * 1e12 { + return Err(invalid("adaptive production sum exceeds its finite bound")); + } + } + } + counts.samples = samples; + counts.covered = hits; + // Accumulate bounded report metadata with the existing pixel transaction; + // final publication never needs a synchronous image-sized report scan. + let mut report = self.report.clone(); + if self.stage == Stage::Pilot && u32::from(samples) == self.options.pilot_samples { + let target = u32::from(counts.planned); + report.minimum_production_samples = report.minimum_production_samples.min(target); + report.maximum_production_samples = report.maximum_production_samples.max(target); + report.production_samples = + report.production_samples.checked_add(u64::from(target)).ok_or_else(|| limit("adaptive report allocation overflow"))?; + report.pixels_at_cap += u64::from(target == self.maximum); + } + let evaluations = self + .production_evaluations + .checked_add(u64::from(self.stage == Stage::Production)) + .ok_or_else(|| limit("adaptive evaluation report overflow"))?; + let target_moments = self.moments.get_mut(index).ok_or_else(|| invalid("adaptive destination moments disappeared"))?; + let target_counts = self.counts.values.get_mut(index).ok_or_else(|| invalid("adaptive destination counts disappeared"))?; + charge()?; + cancel.check()?; + *target_moments = moments; + *target_counts = counts; + self.report = report; + self.production_evaluations = evaluations; + self.advance(); + Ok(()) + } + pub fn skip_one(&mut self, index: usize, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + cancel.check()?; + if self.stage != Stage::Production || self.sampling_identity(index)?.is_some() { + return Err(invalid("only a fully sampled production pixel may be skipped")); + } + charge()?; + cancel.check()?; + self.advance(); + Ok(()) + } + /// Borrow exact counts only at a complete, frozen pass. The caller may pass + /// this borrow into one finishing step without keeping a self-reference. + pub fn counts_plane(&self) -> Result<&CountsPlane> { + self.complete_pass()?; + Ok(&self.counts) + } + + pub fn complete_pass(&self) -> Result> { + if !self.ready() || self.next_pixel != 0 || self.completed == 0 || self.stage == Stage::Reset { + return Err(invalid("adaptive film has no complete sampling pass")); + } + Ok(AdaptivePass { film: self }) + } + /// Called only after last pilot finishing/publication is no longer borrowing + /// this film. Reset is cooperative and never exposes partially discarded pilots. + pub fn begin_production(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + cancel.check()?; + if self.stage != Stage::Pilot || self.next_pixel != 0 || self.completed != self.options.pilot_samples { + return Err(invalid("production requires all complete independent pilots")); + } + charge()?; + cancel.check()?; + self.stage = Stage::Reset; + self.completed = 0; + Ok(()) + } + pub fn resetting(&self) -> bool { + self.stage == Stage::Reset + } + pub fn reset_one(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + cancel.check()?; + if self.stage != Stage::Reset { + return Err(invalid("adaptive film is not resetting pilots")); + } + let index = self.next_pixel; + let moments = self.moments.get_mut(index).ok_or_else(|| invalid("adaptive reset index exceeds admission"))?; + let counts = self.counts.values.get_mut(index).ok_or_else(|| invalid("adaptive reset count disappeared"))?; + if !(self.options.min_samples..=self.maximum).contains(&u32::from(counts.planned)) { + return Err(invalid("adaptive reset has no admitted production allocation")); + } + charge()?; + cancel.check()?; + *moments = Moments::default(); + counts.covered = 0; + counts.samples = 0; + self.next_pixel += 1; + if self.next_pixel == self.count { + self.next_pixel = 0; + self.stage = Stage::Production; + } + Ok(()) + } + pub fn production_target(&self, index: usize) -> Result { + if self.stage == Stage::Pilot && (self.next_pixel != 0 || self.completed != self.options.pilot_samples) { + return Err(invalid("adaptive allocations require the complete pilot pass")); + } + Ok(u32::from(self.counts.pixel(index)?.planned)) + } + pub fn report(&self) -> Result { + if !self.is_final() { + return Err(invalid("adaptive sampling report requires complete production")); + } + if self.production_evaluations != self.report.production_samples { + return Err(invalid("adaptive final evaluation count disagrees with its pilot allocation")); + } + let mut report = self.report.clone(); + report.primary_path_evaluations = u64::from(self.options.pilot_samples) * self.count as u64 + self.production_evaluations; + Ok(report) + } +} diff --git a/crates/render/src/film_tests.rs b/crates/render/src/film_tests.rs index 8553de82d..3dbd1dd1a 100644 --- a/crates/render/src/film_tests.rs +++ b/crates/render/src/film_tests.rs @@ -275,3 +275,302 @@ fn primary_film_large_profile_keeps_every_sample_and_cancels_before_mutation() { assert!(film.add(0, 512, [0.0; 3], true, &cancel, &mut || Ok(())).is_err()); assert_eq!(film.samples(), 512); } + +mod cpu_adaptive_foundation { + use super::adaptive::{AdaptiveCameraFilm, SamplingIdentity}; + use super::*; + use crate::job::{ + CpuBudget, CpuProgressiveOptions, + adaptive::{AdaptiveSampling, PreviewStage}, + }; + + fn options() -> AdaptiveSampling { + AdaptiveSampling { pilot_samples: 16, min_samples: 16, relative_error: 0.0, absolute_error: 0.1, coverage_error: 0.25 } + } + fn film(maximum: u32) -> AdaptiveCameraFilm { + let production = CpuProgressiveOptions { samples_per_pixel: maximum, seed: 81 }; + let bytes = AdaptiveCameraFilm::required_bytes(2, 1, production, options(), CpuBudget::Compact).unwrap(); + AdaptiveCameraFilm::new(2, 1, production, options(), CpuBudget::Compact, bytes, &CancelToken::default()).unwrap() + } + fn source(index: usize, key: SamplingIdentity) -> ([f64; 3], bool) { + match (key.stage, index) { + (PreviewStage::Pilot, 0) => ([0.25, 0.5, 0.75], true), + (PreviewStage::Pilot, _) => { + if key.ordinal % 2 == 1 { + ([1.0, 0.0, 0.0], true) + } else { + ([0.0; 3], false) + } + } + (PreviewStage::Production, 0) => ([3.0, 1.0, 2.0], true), + (PreviewStage::Production, _) => { + if key.ordinal % 6 != 5 { + ([6.0, 0.0, 0.0], true) + } else { + ([0.0; 3], false) + } + } + } + } + fn step(film: &mut AdaptiveCameraFilm, work: &mut u64) { + let cancel = CancelToken::default(); + let mut charge = || { + *work += 1; + Ok(()) + }; + if !film.ready() { + film.initialize_one(&cancel, &mut charge).unwrap(); + } else if film.resetting() { + film.reset_one(&cancel, &mut charge).unwrap(); + } else if film.complete_pass().is_ok_and(|pass| pass.metadata().stage == PreviewStage::Pilot && pass.metadata().completed == 16) { + film.begin_production(&cancel, &mut charge).unwrap(); + } else { + let index = film.next_pixel(); + if let Some(identity) = film.sampling_identity(index).unwrap() { + let (rgb, covered) = source(index, identity); + film.add(index, identity, rgb, covered, &cancel, &mut charge).unwrap(); + } else { + film.skip_one(index, &cancel, &mut charge).unwrap(); + } + } + } + type Snapshot = (PreviewStage, u32, Vec<([f64; 3], f64, u16, u16)>); + fn snapshot(film: &AdaptiveCameraFilm) -> Option { + let pass = film.complete_pass().ok()?; + let metadata = pass.metadata(); + let pixels = (0..pass.counts().len()) + .map(|index| { + let (mean, alpha) = pass.pixel(index).unwrap(); + let count = pass.counts().pixel(index).unwrap(); + (mean, alpha, count.covered(), count.samples()) + }) + .collect(); + Some((metadata.stage, metadata.completed, pixels)) + } + fn complete(maximum: u32, quantum: usize) -> (Vec, crate::job::adaptive::SamplingReport, u64) { + let mut film = film(maximum); + let mut work = 0; + let mut snapshots = Vec::new(); + for _ in 0..10_000 { + for _ in 0..quantum { + if film.is_final() { + break; + } + step(&mut film, &mut work); + if let Some(next) = snapshot(&film) + && snapshots.last() != Some(&next) + { + snapshots.push(next); + } + } + if film.is_final() { + return (snapshots, film.report().unwrap(), work); + } + } + panic!("bounded adaptive foundation did not complete"); + } + #[test] + fn cpu_adaptive_film_independent_variance_allocation_discards_pilots_and_normalizes_heterogeneous_production() { + let mut film = film(48); + let mut work = 0; + while film.completed_passes() < 16 { + step(&mut film, &mut work); + } + let pilot = snapshot(&film).unwrap(); + assert_eq!(pilot.2[0], ([0.25, 0.5, 0.75], 1.0, 16, 16)); + assert_eq!(pilot.2[1], ([0.5, 0.0, 0.0], 0.5, 8, 16)); + assert_eq!(film.production_target(0).unwrap(), 16); + // Eight0/eight1 pilots have M2=4, sample variance4/15. With + // absolute RGB error0.1, ceil((4/15)/0.01)=27; alpha uses0.25. + assert_eq!(film.production_target(1).unwrap(), 27); + while !film.is_final() { + step(&mut film, &mut work); + } + let final_pass = film.complete_pass().unwrap(); + assert_eq!(final_pass.pixel(0).unwrap(), ([3.0, 1.0, 2.0], 1.0), "pilot radiance is discarded rather than stopped into production"); + assert_eq!((final_pass.counts().pixel(0).unwrap().samples(), final_pass.counts().pixel(1).unwrap().samples()), (16, 27)); + let (mean, alpha) = final_pass.pixel(1).unwrap(); + assert_eq!(mean, [138.0 / 27.0, 0.0, 0.0]); + assert_eq!(alpha, 23.0 / 27.0); + let report = film.report().unwrap(); + assert_eq!((report.pilot_samples_per_pixel, report.minimum_production_samples, report.maximum_production_samples), (16, 16, 27)); + assert_eq!((report.production_samples, report.primary_path_evaluations, report.pixels_at_cap, report.transmission_strata), (43, 75, 0, 1)); + assert_eq!(work, 133, "init/reset and each sampled/skipped pixel own one exact work unit"); + } + #[test] + fn cpu_adaptive_counts_keep_five_of_six_alpha_exact_without_quantizing_raw_radiance() { + let mut film = film(48); + let mut work = 0; + loop { + if let Some((PreviewStage::Production, 6, _)) = snapshot(&film) { + break; + } + step(&mut film, &mut work); + } + let pass = film.complete_pass().unwrap(); + let count = pass.counts().pixel(1).unwrap(); + assert_eq!((count.covered(), count.samples(), count.alpha8().unwrap()), (5, 6, 213)); + let (raw, alpha) = pass.pixel(1).unwrap(); + assert_eq!(raw, [5.0, 0.0, 0.0]); + assert_eq!(alpha, 5.0 / 6.0); + assert_eq!(alpha as f32, 5.0f32 / 6.0); + assert_ne!(alpha as f32, 213.0f32 / 255.0, "PNG byte rounding cannot alter the raw FLOAT32 alpha"); + } + #[test] + fn cpu_adaptive_all_complete_passes_and_production_prefixes_are_quantum_and_cap_independent() { + let (snapshots, report, work) = complete(48, 1); + assert_eq!((snapshots.clone(), report.clone(), work), complete(48, 16384)); + assert_eq!(snapshots.len(), 64); + assert_eq!(snapshots.iter().filter(|s| s.0 == PreviewStage::Pilot).count(), 16); + assert_eq!(snapshots.last().unwrap().1, 48); + for maximum in 16..=48 { + let (prefix, _, _) = complete(maximum, 7); + assert_eq!(&prefix[..16], &snapshots[..16], "the production cap never enters the pilot stream"); + assert_eq!(prefix.last().unwrap(), snapshots.iter().find(|s| s.0 == PreviewStage::Production && s.1 == maximum).unwrap()); + } + } + #[test] + fn cpu_adaptive_sample_identities_separate_pilots_and_preserve_original_production_ordinals() { + let mut film = film(48); + let mut work = 0; + while !film.ready() { + step(&mut film, &mut work); + } + let pilot = film.sampling_identity(0).unwrap().unwrap(); + assert_eq!((pilot.seed, pilot.ordinal, pilot.stage), (81 ^ 0xa511_e9b3, 0, PreviewStage::Pilot)); + while film.complete_pass().is_err() || film.complete_pass().unwrap().metadata().stage == PreviewStage::Pilot { + step(&mut film, &mut work); + } + // A complete first production pass has consumed ordinal0, so the next + // active pixel receives original seed81 and absolute production ordinal1. + let production = film.sampling_identity(0).unwrap().unwrap(); + assert_eq!((production.seed, production.ordinal, production.stage), (81, 1, PreviewStage::Production)); + assert_ne!(pilot.seed, production.seed); + while film.completed_passes() < 32 { + step(&mut film, &mut work); + } + assert!(film.sampling_identity(0).unwrap().is_none(), "a stopped pixel requests bookkeeping rather than another sample"); + assert!(film.complete_pass().unwrap().pixel(2).is_err()); + } + #[test] + fn cpu_adaptive_pilots_plus_production_obey_every_unchanged_profile_and_camera_work_cap() { + for budget in CpuBudget::ALL { + let maximum = budget.limits().max_samples_per_pixel; + let make = |production| CpuProgressiveOptions { samples_per_pixel: production, seed: 0 }; + assert!(AdaptiveCameraFilm::required_bytes(1, 1, make(maximum - 16), options(), budget).is_ok()); + assert!(AdaptiveCameraFilm::required_bytes(1, 1, make(maximum - 15), options(), budget).is_err()); + assert!(AdaptiveCameraFilm::required_bytes(1, 1, make(maximum), options(), budget).is_err()); + } + let production = CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }; + assert!(AdaptiveCameraFilm::required_bytes(1024, 512, production, options(), CpuBudget::Compact).is_ok()); + assert!( + AdaptiveCameraFilm::required_bytes(1024, 513, production, options(), CpuBudget::Compact).is_err(), + "pilot camera paths are included in the same total sample budget" + ); + let one = AdaptiveCameraFilm::required_bytes(1, 1, production, options(), CpuBudget::Compact).unwrap(); + let two = AdaptiveCameraFilm::required_bytes(2, 1, production, options(), CpuBudget::Compact).unwrap(); + assert_eq!(two - one, 70, "64-byte moments plus6-byte exact count/allocation plane, with no snapshot plane"); + assert!(AdaptiveCameraFilm::new(1, 1, production, options(), CpuBudget::Compact, one - 1, &CancelToken::default()).is_err()); + assert!(AdaptiveCameraFilm::required_bytes(0, 1, production, options(), CpuBudget::Compact).is_err()); + assert!( + AdaptiveCameraFilm::required_bytes(1, 1, production, AdaptiveSampling { pilot_samples: 15, ..options() }, CpuBudget::Compact).is_err() + ); + assert!( + AdaptiveCameraFilm::required_bytes(1, 1, production, AdaptiveSampling { relative_error: f64::NAN, ..options() }, CpuBudget::Compact) + .is_err() + ); + } + #[test] + fn cpu_adaptive_add_reset_skip_and_initialization_are_atomic_under_cancel_or_work_failure() { + for operation in ["initialize", "pilot", "reset", "production", "skip"] { + for cancelled in [false, true] { + let mut film = film(48); + let mut work = 0; + if operation != "initialize" { + while !film.ready() { + step(&mut film, &mut work); + } + } + if matches!(operation, "reset" | "production" | "skip") { + while film.completed_passes() < 16 { + step(&mut film, &mut work); + } + film.begin_production(&CancelToken::default(), &mut || Ok(())).unwrap(); + } + if matches!(operation, "production" | "skip") { + while film.resetting() { + step(&mut film, &mut work); + } + } + if operation == "skip" { + while film.completed_passes() < 32 { + step(&mut film, &mut work); + } + } + let before = ( + film.initialized(), + film.ready(), + film.next_pixel(), + film.completed_passes(), + snapshot(&film), + film.sampling_identity(film.next_pixel()).ok(), + ); + let cancel = CancelToken::default(); + let token = cancel.clone(); + let mut charge = || { + if cancelled { + token.cancel(); + Ok(()) + } else { + Err(JobError::new(ErrorCode::LimitExceeded, "test cumulative work exhausted")) + } + }; + let result = match operation { + "initialize" => film.initialize_one(&cancel, &mut charge), + "reset" => film.reset_one(&cancel, &mut charge), + "skip" => film.skip_one(0, &cancel, &mut charge), + _ => { + let key = film.sampling_identity(0).unwrap().unwrap(); + let (rgb, covered) = source(0, key); + film.add(0, key, rgb, covered, &cancel, &mut charge) + } + }; + assert_eq!(result.unwrap_err().code, if cancelled { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }, "{operation}"); + assert_eq!( + ( + film.initialized(), + film.ready(), + film.next_pixel(), + film.completed_passes(), + snapshot(&film), + film.sampling_identity(film.next_pixel()).ok() + ), + before, + "{operation} may not partially consume its cursor/count/stream" + ); + assert!(film.report().is_err()); + } + } + } + #[test] + fn cpu_adaptive_integration_requires_explicit_progressive_intent_and_preserves_strict_input() { + assert!(serde_json::to_value(crate::job::RaytraceOptions::default()).unwrap().get("adaptive").is_none()); + let invalid: crate::job::RaytraceOptions = serde_json::from_value(serde_json::json!({"adaptive":options()})).unwrap(); + assert!(invalid.validate().is_err(), "adaptive cannot silently introduce a camera film into a fixed saved setup"); + assert!(serde_json::from_value::(serde_json::json!({"adaptive":{"noise_guarantee":true}})).is_err()); + let mut film = film(48); + let mut work = 0; + while !film.ready() { + step(&mut film, &mut work); + } + assert!(film.complete_pass().is_err()); + assert!(film.begin_production(&CancelToken::default(), &mut || Ok(())).is_err()); + let key = film.sampling_identity(0).unwrap().unwrap(); + for (rgb, covered) in [([f64::NAN, 0.0, 0.0], true), ([f64::INFINITY, 0.0, 0.0], true), ([1.0, 0.0, 0.0], false)] { + assert!(film.add(0, key, rgb, covered, &CancelToken::default(), &mut || panic!("invalid input must not debit or mutate work")).is_err()); + assert_eq!(film.sampling_identity(0).unwrap().unwrap(), key); + } + assert!(film.add(1, key, [0.0; 3], false, &CancelToken::default(), &mut || Ok(())).is_err()); + assert!(film.skip_one(0, &CancelToken::default(), &mut || Ok(())).is_err()); + } +} diff --git a/crates/render/src/job/adaptive.rs b/crates/render/src/job/adaptive.rs index 0fc23ce31..cbb340680 100644 --- a/crates/render/src/job/adaptive.rs +++ b/crates/render/src/job/adaptive.rs @@ -66,6 +66,55 @@ pub struct SamplingReport { pub transmission_strata: u32, } +/// Display progress for an adaptive checkpoint. Production iterations do not imply +/// a uniform sample count: each pixel stops at its own independently chosen budget. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PreviewStage { + Pilot, + Production, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct AdaptivePreview { + pub stage: PreviewStage, + pub completed: u32, + pub target: u32, + pub pilot_samples: u32, + pub minimum_production_samples: u32, + pub maximum_production_samples: u32, +} +impl AdaptivePreview { + /// Derived only from captured sampling options and an absolute completed pass. + pub fn at(options: super::JobOptions, completed: u32) -> Result> { + let Some(adaptive) = options.adaptive else { return Ok(None) }; + options.preview_target()?; + Ok(Some(Self::captured(adaptive, options.samples, completed)?)) + } + /// The same captured statistical policy is shared by native CPU and GPU jobs. + /// The completed ordinal spans pilots plus production; it is not a per-pixel count. + pub fn captured(adaptive: AdaptiveSampling, maximum: u32, completed: u32) -> Result { + adaptive.validate(maximum)?; + let target = adaptive + .pilot_samples + .checked_add(maximum) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "adaptive checkpoint target overflow"))?; + if completed == 0 || completed > target { + return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint exceeds captured sampling passes")); + } + Ok({ + let pilot = completed <= adaptive.pilot_samples; + Self { + stage: if pilot { PreviewStage::Pilot } else { PreviewStage::Production }, + completed: if pilot { completed } else { completed - adaptive.pilot_samples }, + target: if pilot { adaptive.pilot_samples } else { maximum }, + pilot_samples: adaptive.pilot_samples, + minimum_production_samples: adaptive.min_samples, + maximum_production_samples: maximum, + } + }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -89,4 +138,35 @@ mod tests { assert!(AdaptiveSampling { absolute_error: 0.0, ..p }.validate(128).is_err()); assert!(serde_json::from_str::(r#"{"noise_guarantee":true}"#).is_err()); } + + #[test] + fn adaptive_checkpoint_metadata_tracks_pilots_and_variable_production_iterations() { + for maximum in [16, 64, 4096] { + for pilots in [16, 32, 256] { + let options = super::super::JobOptions { + samples: maximum, + adaptive: Some(AdaptiveSampling { pilot_samples: pilots, min_samples: 16, ..Default::default() }), + ..Default::default() + }; + let total = options.preview_target().unwrap(); + assert_eq!(total, pilots + maximum); + assert!(AdaptivePreview::at(options, 0).is_err()); + assert!(AdaptivePreview::at(options, total + 1).is_err()); + for ordinal in 1..=total { + let info = AdaptivePreview::at(options, ordinal).unwrap().unwrap(); + assert_eq!(info.pilot_samples, pilots); + assert_eq!((info.minimum_production_samples, info.maximum_production_samples), (16, maximum)); + if ordinal <= pilots { + assert_eq!((info.stage, info.completed, info.target), (PreviewStage::Pilot, ordinal, pilots)); + } else { + assert_eq!((info.stage, info.completed, info.target), (PreviewStage::Production, ordinal - pilots, maximum)); + } + } + } + } + assert!( + AdaptivePreview::at(super::super::JobOptions::default(), 4096).unwrap().is_none(), + "CPU profile checkpoints do not use GPU sampling options" + ); + } } diff --git a/crates/render/src/job/aging.rs b/crates/render/src/job/aging.rs index 579e956f5..bf6862496 100644 --- a/crates/render/src/job/aging.rs +++ b/crates/render/src/job/aging.rs @@ -282,7 +282,7 @@ impl AgingStack { Ok(()) } /// Five aligned vec4s per layer: id/target/class/seed, mask/scale, - /// rebased periodic origin, linear coat RGB/roughness, metallic/reserved. + /// rebased periodic origin/Scratch cell carry, linear coat RGB/roughness, metallic/reserved. pub fn gpu_layers(&self, target: [f64; 3]) -> Result<[[f32; 20]; MAX_AGING_LAYERS]> { self.validate()?; if target.iter().any(|v| !v.is_finite() || v.abs() > 1e9) { @@ -301,9 +301,20 @@ impl AgingStack { out[5] = layer.coverage as f32; out[6] = layer.scale_mm.recip() as f32; out[7] = layer.upward_bias as f32; + let mut scratch_carry = 0_u32; + let mut place = 1_u32; for axis in 0..3 { - out[8 + axis] = ((target[axis] - layer.origin_mm[axis]) / layer.scale_mm).rem_euclid(4096.0) as f32; + let coordinate = (target[axis] - layer.origin_mm[axis]) / layer.scale_mm; + out[8 + axis] = coordinate.rem_euclid(4096.0) as f32; + if layer.kind == AgingKind::Scratches { + // Noise repeats every4096 cells, while floor(4*q/5)'s + // hashed band also needs the removed quotient modulo5. + // Three base5 digits fit exactly in the reserved f32 lane. + scratch_carry += ((coordinate / 4096.0).floor().rem_euclid(5.0) as u32) * place; + place *= 5; + } } + out[11] = scratch_carry as f32; for axis in 0..3 { out[12 + axis] = srgb8_to_linear(layer.color_srgb[axis]) as f32; } @@ -389,4 +400,34 @@ mod tests { assert_eq!(stack.gpu_layers([0.0; 3]).unwrap(), [[0.0; 20]; 8]); assert!(!stack.active()); } + #[test] + fn scratch_rebase_carries_signed_camera_cells_on_all_axes_in_the_same_uniform_size() { + let origin = [128.0, -64.0, 32.0]; + let fraction = [0.125, 0.25, 0.5]; + let layer = AgingLayer { kind: AgingKind::Scratches, scale_mm: 2.0, origin_mm: origin, ..Default::default() }; + let mut stack = AgingStack::default(); + stack.push(layer).unwrap(); + assert_eq!(std::mem::size_of::<[[f32; 20]; MAX_AGING_LAYERS]>(), 640); + for k in [-122000_i32, -7, -1, 0, 1, 4, 5, 122000] { + let cells = [k, k + 2, -k]; + let target = std::array::from_fn(|axis| origin[axis] + 2.0 * (4096.0 * f64::from(cells[axis]) + fraction[axis])); + let packed = stack.gpu_layers(target).unwrap(); + assert_eq!(&packed[0][8..11], &[0.125, 0.25, 0.5]); + let expected = cells[0].rem_euclid(5) + 5 * cells[1].rem_euclid(5) + 25 * cells[2].rem_euclid(5); + assert_eq!(packed[0][11], expected as f32, "{cells:?}"); + assert!(packed[1..].iter().flatten().all(|value| value.to_bits() == 0)); + assert!(packed[0][17..].iter().all(|value| value.to_bits() == 0)); + // Non-Scratch layers keep their prior five-vec4 bytes. Only the + // kind and the Scratch-only reserved carry differ in this pair. + let mut ordinary = AgingStack::default(); + ordinary.push(AgingLayer { kind: AgingKind::Rust, ..layer }).unwrap(); + let mut expected = packed; + expected[0][0] = AgingKind::Rust.code() as f32; + expected[0][11] = 0.0; + assert_eq!(ordinary.gpu_layers(target).unwrap().map(|row| row.map(f32::to_bits)), expected.map(|row| row.map(f32::to_bits))); + } + stack.get_mut(0).unwrap().enabled = false; + assert!(stack.gpu_layers([999000000.0, -999000000.0, 0.0]).unwrap().iter().flatten().all(|value| value.to_bits() == 0)); + assert!(AgingStack::default().gpu_layers([999000000.0; 3]).unwrap().iter().flatten().all(|value| value.to_bits() == 0)); + } } diff --git a/crates/render/src/job/bloom.rs b/crates/render/src/job/bloom.rs index e1c8936b2..ed7953b72 100644 --- a/crates/render/src/job/bloom.rs +++ b/crates/render/src/job/bloom.rs @@ -88,6 +88,16 @@ impl BloomTask { let previous: usize = (0..self.phase).map(|p| if p == 0 || p % 2 == 1 { self.height } else { self.width }).sum(); (previous + self.line) as u64 } + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn next_line_pixels(&self) -> u64 { + if self.phase == 7 { + 0 + } else if self.phase == 0 || self.phase % 2 == 1 { + self.width as u64 + } else { + self.height as u64 + } + } /// Every call has bounded line and pixel loops, independent of kernel radius. pub fn step(&mut self, lines: usize) -> Result { self.cancel.check()?; diff --git a/crates/render/src/job/cpu_path.rs b/crates/render/src/job/cpu_path.rs new file mode 100644 index 000000000..2ba78ce71 --- /dev/null +++ b/crates/render/src/job/cpu_path.rs @@ -0,0 +1,84 @@ +//! Explicit finite-depth CPU opaque and certified dielectric path transport. Absence preserves the legacy producer. +use super::{ErrorCode, JobError, Result}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CpuPathOptions { + /// Number of shaded opaque surfaces, Glass boundaries and medium collisions, including the first event. + pub max_depth: u8, +} +impl Default for CpuPathOptions { + fn default() -> Self { + Self { max_depth: 8 } + } +} +impl CpuPathOptions { + pub fn validate(self) -> Result<()> { + if !(1..=16).contains(&self.max_depth) { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU path depth must be 1..16 surfaces, Glass boundaries or medium collisions")); + } + Ok(()) + } +} + +/// Positive-area overlapping same-facing coplanar supports cannot be represented +/// by a single closest-emitter label with separate per-emitter NEE. Refuse before +/// capture, rather than lose radiance or add an inconsistent MIS estimator. +pub(crate) fn validate_emitters(lights: &[super::RectangleLightOptions]) -> Result<()> { + use solidcore_record::Vec3; + use solidcraft_geom::prelude::*; + let invalid = || { + JobError::new( + ErrorCode::InvalidRequest, + "CPU opaque path transport refuses overlapping same-facing coplanar rectangle supports; preserve the emitters and separate them explicitly", + ) + }; + if lights.len() > 4 { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU opaque path transport supports at most four rectangle lights")); + } + let vector = |[x, y, z]: [f64; 3]| Vec3::new(x, y, z); + for (i, a) in lights.iter().enumerate() { + let au = vector(a.edge_u_mm); + let av = vector(a.edge_v_mm); + let ac = vector(a.center_mm); + let an = crate::surface::unit_direction(au.cross(av)).map_err(|_| invalid())?; + let x = crate::surface::unit_direction(au).map_err(|_| invalid())?; + let y = an.cross(x); + for b in lights.iter().skip(i + 1) { + let bu = vector(b.edge_u_mm); + let bv = vector(b.edge_v_mm); + let bc = vector(b.center_mm); + let bn = crate::surface::unit_direction(bu.cross(bv)).map_err(|_| invalid())?; + if an.dot(bn) <= 0.0 || an.cross(bn).len() > 64.0 * f64::EPSILON { + continue; + } + let scale = [ac, bc, au, av, bu, bv].into_iter().map(|p| p.x.abs().max(p.y.abs()).max(p.z.abs())).fold(1.0, f64::max); + if ((bc - ac).dot(an)).abs() > scale * 64.0 * f64::EPSILON { + continue; + } + // Plane-projected AABBs are deliberately conservative for rotated + // supports. No extra heap state or unbounded geometry search occurs. + let bounds = |center: Vec3, u: Vec3, v: Vec3| { + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for su in [-0.5, 0.5] { + for sv in [-0.5, 0.5] { + let p = center + u * su + v * sv; + for (axis, value) in [p.dot(x), p.dot(y)].into_iter().enumerate() { + lo[axis] = lo[axis].min(value); + hi[axis] = hi[axis].max(value); + } + } + } + (lo, hi) + }; + let (alo, ahi) = bounds(Vec3::ZERO, au, av); + let (blo, bhi) = bounds(bc - ac, bu, bv); + if (0..2).all(|axis| ahi[axis].min(bhi[axis]) - alo[axis].max(blo[axis]) > 0.0) { + return Err(invalid()); + } + } + } + Ok(()) +} diff --git a/crates/render/src/job/cpu_sky.rs b/crates/render/src/job/cpu_sky.rs new file mode 100644 index 000000000..f73774438 --- /dev/null +++ b/crates/render/src/job/cpu_sky.rs @@ -0,0 +1,40 @@ +//! Portable CPU consumer for the existing GPU gradient-sky radiance domain. +//! The GPU's generated512x256 image is constant along each row. Evaluate that +//! same row centre directly: no generated image, HDR quantization or hidden cache. +use super::{ErrorCode, JobError, Result}; +use crate::lighting::environment::SkyGradient; +use serde::{Deserialize, Serialize}; +use solidcore_record::Vec3; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CpuSky { + pub gradient: SkyGradient, + pub rotation_rad: f64, + pub intensity: f64, +} +impl Default for CpuSky { + fn default() -> Self { + Self { gradient: Default::default(), rotation_rad: 0.0, intensity: 1.0 } + } +} +impl CpuSky { + pub fn validate(self) -> Result<()> { + self.gradient.validate()?; + if !self.rotation_rad.is_finite() || self.rotation_rad.abs() > 1e6 || !self.intensity.is_finite() || !(0.0..=100.0).contains(&self.intensity) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU sky rotation must be finite within +/-1000000 radians and intensity0..100")); + } + Ok(()) + } + pub fn radiance(self, direction: Vec3) -> Result { + self.validate()?; + let d = crate::surface::unit_direction(direction).map_err(|_| JobError::new(ErrorCode::InvalidRequest, "invalid CPU sky direction"))?; + let row = ((d.z.clamp(-1.0, 1.0).acos() / std::f64::consts::PI * 256.0) as u32).min(255); + let z = (std::f64::consts::PI * (f64::from(row) + 0.5) / 256.0).cos(); + let [r, g, b] = self.gradient.evaluate(z); + // Rotation is retained/validated, as in GPU intent. This particular + // world-Z gradient is axisymmetric, so longitude rotation is an identity. + Ok(Vec3::new(f64::from(r), f64::from(g), f64::from(b)) * self.intensity) + } +} diff --git a/crates/render/src/job/denoise.rs b/crates/render/src/job/denoise.rs new file mode 100644 index 000000000..1186bb7b2 --- /dev/null +++ b/crates/render/src/job/denoise.rs @@ -0,0 +1,172 @@ +//! Original bounded CPU a-trous output filter. Raw film and transport are never borrowed mutably. +//! The independent f64 gather oracle remains in the renderer tests, outside this implementation. +use super::{CancelToken, ErrorCode, JobError, Result}; + +pub(crate) const GUIDE_BYTES: u64 = 48; +pub(crate) const MAX_STEP_PIXELS: usize = 256; + +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Guide { + pub albedo: [f32; 3], + /// Captured body ordinal plus one; zero means that first-hit guidance is unavailable. + pub body: u32, + pub normal: [f32; 3], + pub depth: f32, + /// Camera-relative position, converted only after the f64 subtraction. + pub position: [f32; 3], + pub footprint: f32, +} +const _: [(); GUIDE_BYTES as usize] = [(); std::mem::size_of::()]; + +fn invalid(message: &str) -> JobError { + JobError::new(ErrorCode::InvalidRequest, message) +} +impl Guide { + pub(crate) fn validate(self) -> Result<()> { + if self.body == 0 { + return Ok(()); + } + let normal_length: f64 = self.normal.into_iter().map(|v| f64::from(v).powi(2)).sum(); + if !self.albedo.into_iter().all(|v| v.is_finite() && (0.0..=1.0).contains(&v)) + || !self.normal.into_iter().chain(self.position).all(f32::is_finite) + || !(0.999..=1.001).contains(&normal_length) + || !self.depth.is_finite() + || !self.footprint.is_finite() + || self.footprint < 0.000001 + { + return Err(invalid("invalid CPU denoising guide")); + } + Ok(()) + } +} + +pub(crate) struct DenoiseTask { + width: usize, + height: usize, + source: Vec<[f32; 4]>, + destination: Vec<[f32; 4]>, + pixel: usize, + pass: usize, +} +impl DenoiseTask { + pub(crate) fn new(width: u32, height: u32, source: Vec<[f32; 4]>) -> Result { + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| invalid("CPU denoising dimensions overflow"))?; + if width == 0 || height == 0 || source.len() != count || source.capacity() != count { + return Err(invalid("CPU denoising requires one admitted complete linear pass")); + } + let mut destination = Vec::new(); + destination.try_reserve_exact(count).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "CPU denoising colour allocation failed"))?; + if destination.capacity() != count { + return Err(invalid("CPU denoising colour capacity exceeds admission")); + } + Ok(Self { width: width as usize, height: height as usize, source, destination, pixel: 0, pass: 0 }) + } + pub(crate) fn next_pixels(&self) -> usize { + (self.source.len() - self.pixel).min(MAX_STEP_PIXELS) + } + /// One work unit is one pixel visit with a fixed 25-tap gather, as for bounded finishing kernels. + /// The caller debits next_pixels before calling; no work, limit or cancellation is reset here. + pub(crate) fn step(&mut self, guides: &[Guide], cancel: &CancelToken) -> Result { + cancel.check()?; + if self.pass >= 3 || guides.len() != self.source.len() { + return Err(invalid("CPU denoising guide count or pass is invalid")); + } + let end = self.pixel + self.next_pixels(); + for pixel in self.pixel..end { + cancel.check()?; + let value = filter_pixel(self.width, self.height, &self.source, guides, pixel, 1 << self.pass)?; + if let Some(destination) = self.destination.get_mut(pixel) { + *destination = value; + } else if self.destination.len() == pixel && self.destination.len() < self.destination.capacity() { + self.destination.push(value); + } else { + return Err(invalid("CPU denoising destination exceeds admission")); + } + } + self.pixel = end; + if self.pixel == self.source.len() { + std::mem::swap(&mut self.source, &mut self.destination); + self.pixel = 0; + self.pass += 1; + } + cancel.check()?; + Ok(self.pass == 3) + } + pub(crate) fn finish(self) -> Result> { + if self.pass != 3 { + return Err(invalid("CPU denoising is incomplete")); + } + Ok(self.source) + } +} + +fn rgb(value: [f32; 4]) -> [f64; 3] { + [f64::from(value[0]), f64::from(value[1]), f64::from(value[2])] +} +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a.into_iter().zip(b).map(|(x, y)| x * y).sum() +} +fn difference(a: [f32; 3], b: [f32; 3]) -> [f64; 3] { + std::array::from_fn(|i| f64::from(a[i]) - f64::from(b[i])) +} +fn maximum(value: [f64; 3]) -> f64 { + value.into_iter().fold(0.0, f64::max) +} +fn checked_color(value: [f32; 4]) -> Result<[f32; 4]> { + if value.into_iter().any(|v| !v.is_finite() || v < 0.0) || value[3] > 1.0 { + return Err(invalid("invalid raw CPU radiance or coverage before denoising")); + } + Ok(value) +} +fn filter_pixel(width: usize, height: usize, source: &[[f32; 4]], guides: &[Guide], pixel: usize, step: usize) -> Result<[f32; 4]> { + let center = checked_color(*source.get(pixel).ok_or_else(|| invalid("CPU denoising source pixel missing"))?)?; + let a = *guides.get(pixel).ok_or_else(|| invalid("CPU denoising guide missing"))?; + a.validate()?; + if a.body == 0 || center[3] < 0.999 { + return Ok(center); + } + let mut mean = [0.0; 3]; + let mut total = 0.0; + let center_rgb = rgb(center); + let kernel = [1.0, 4.0, 6.0, 4.0, 1.0]; + for (ky, wy) in kernel.into_iter().enumerate() { + for (kx, wx) in kernel.into_iter().enumerate() { + let x = (pixel % width) as i64 + (kx as i64 - 2) * step as i64; + let y = (pixel / width) as i64 + (ky as i64 - 2) * step as i64; + if x < 0 || y < 0 || x >= width as i64 || y >= height as i64 { + continue; + } + let index = y as usize * width + x as usize; + let b = *guides.get(index).ok_or_else(|| invalid("CPU denoising neighbour guide missing"))?; + let value = checked_color(*source.get(index).ok_or_else(|| invalid("CPU denoising neighbour missing"))?)?; + if b.body != a.body || (f64::from(value[3]) - f64::from(center[3])).abs() > 0.01 { + continue; + } + b.validate()?; + let albedo = difference(a.albedo, b.albedo); + let position = difference(b.position, a.position); + let normal = a.normal.map(f64::from); + let neighbour_normal = b.normal.map(f64::from); + let plane = dot(position, normal).abs() + dot(position, neighbour_normal).abs(); + let footprint = f64::from(a.footprint.max(b.footprint)) * step as f64; + let depth = (f64::from(a.depth) - f64::from(b.depth)).abs() / (8.0 * footprint).max(0.000001); + let value_rgb = rgb(value); + let contrast = maximum(std::array::from_fn(|i| (center_rgb[i] - value_rgb[i]).abs())); + let color_scale = 0.25 + 0.5 * maximum(center_rgb).max(maximum(value_rgb)); + let weight = wx + * wy + * (-dot(albedo, albedo) / 0.04 - plane / (0.05 * footprint).max(0.000001) - depth - contrast / color_scale).exp() + * dot(normal, neighbour_normal).max(0.0).powi(32); + if weight > 0.0 { + total += weight; + for (channel, value) in mean.iter_mut().zip(value_rgb) { + *channel += (value - *channel) * (weight / total); + } + } + } + } + if !total.is_finite() || total <= 0.0 { + return Err(invalid("CPU denoising centre did not contribute")); + } + checked_color([mean[0] as f32, mean[1] as f32, mean[2] as f32, center[3]]) +} diff --git a/crates/render/src/job/host.rs b/crates/render/src/job/host.rs index e0eb901c9..f63a2645a 100644 --- a/crates/render/src/job/host.rs +++ b/crates/render/src/job/host.rs @@ -14,12 +14,15 @@ use sha2::{Digest, Sha256}; use super::{ Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageExecutor, ImageRequest, ImageTask, ImageWork, Integrator, - JobError, JobId, JobOptions, Phase, Progress, Result, TaskPoll, admit, + JobError, JobId, JobOptions, Phase, Progress, Result, TaskPoll, }; use crate::{ Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout, }; +#[cfg(test)] +use super::admit; + const MEMORY_LIMIT: u64 = 512 * 1024 * 1024; const QUEUE_LIMIT: usize = 2; @@ -108,7 +111,7 @@ impl Budget { } impl Reservation { /// Transfer an already admitted portion without changing the pool's total. - /// CPU progressive admission includes every possible checkpoint up front. + /// CPU progressive admission prepays at most two reusable checkpoint slots. fn split(&mut self, bytes: u64) -> Result { if bytes > self.bytes { return Err(JobError::new(ErrorCode::LimitExceeded, "preview exceeds its prepaid reservation")); @@ -117,6 +120,16 @@ impl Reservation { Ok(Self { budget: self.budget.clone(), bytes }) } + /// Return a lease to the same prepaid pool without reserving memory again. + fn merge_from(&mut self, other: &mut Self) -> Result<()> { + if !Arc::ptr_eq(&self.budget, &other.budget) { + return Err(JobError::new(ErrorCode::Internal, "checkpoint lease belongs to another pool")); + } + self.bytes = self.bytes.checked_add(other.bytes).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint lease overflow"))?; + other.bytes = 0; + Ok(()) + } + pub(crate) fn shrink(&mut self, bytes: u64) -> Result<()> { if bytes > self.bytes { return Err(JobError::new(ErrorCode::LimitExceeded, "completed PNG exceeds its reservation")); @@ -191,7 +204,7 @@ mod light_union_lease_tests { let mut host = CpuHost::for_platform().unwrap(); let budget = host.0.shared.budget.clone(); let request = request().unwrap(); - let bytes = retained_request_bytes(&request).unwrap(); + let bytes = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); let capacities = request .raytrace .as_ref() @@ -310,7 +323,10 @@ impl RenderFrame { #[derive(Clone, Debug, Serialize)] pub struct PreviewInfo { pub frame_sequence: u32, + /// Uniform SPP when adaptive is absent; otherwise absolute completed iteration. pub samples_per_pixel: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub adaptive: Option, pub frame: FrameInfo, } @@ -319,7 +335,88 @@ pub struct PreviewInfo { pub struct RenderPreview { pub info: PreviewInfo, png: Vec, - _reservation: Reservation, + _reservation: CheckpointLease, +} + +/// Two reusable, immutable complete-pass slots. No consumer acknowledgement or +/// queue: externally pinned slots are diagnosed and never stall final work. +struct CheckpointCredits { + state: Mutex, + slot_bytes: u64, + capacity: u64, +} +struct CheckpointCreditState { + free: Reservation, + closed: bool, +} +impl CheckpointCredits { + fn new(reservation: &mut Reservation, slot_bytes: u64, slots: u32) -> Result> { + if !(1..=2).contains(&slots) || slot_bytes == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint credits require one or two finite slots")); + } + let capacity = slot_bytes + .checked_mul(u64::from(slots)) + .and_then(|n| n.checked_add(FRAME_METADATA_BYTES)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit capacity overflow"))?; + let free = reservation.split(capacity)?; + Ok(Arc::new(Self { state: Mutex::new(CheckpointCreditState { free, closed: false }), slot_bytes, capacity })) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "checkpoint credit lock poisoned"))?; + if state.closed { + return Err(JobError::new(ErrorCode::Cancelled, "checkpoint credits are closed")); + } + let needed = self + .slot_bytes + .checked_add(FRAME_METADATA_BYTES) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit bound overflow"))?; + if state.free.bytes < needed { + return Ok(None); + } + let reservation = state.free.split(self.slot_bytes)?; + Ok(Some(CheckpointLease { reservation, credits: self.clone() })) + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + let _ = state.free.shrink(0); + } +} +struct CheckpointLease { + reservation: Reservation, + credits: Arc, +} +impl std::ops::Deref for CheckpointLease { + type Target = Reservation; + fn deref(&self) -> &Reservation { + &self.reservation + } +} +impl Drop for CheckpointLease { + fn drop(&mut self) { + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if !state.closed { + if self.reservation.bytes <= self.credits.slot_bytes + && state.free.bytes.checked_add(self.reservation.bytes).is_some_and(|n| n <= self.credits.capacity) + && state.free.merge_from(&mut self.reservation).is_ok() + { + return; + } + state.closed = true; + let _ = state.free.shrink(0); + } + } } impl RenderPreview { @@ -338,6 +435,12 @@ pub enum JobEnvironmentInfo { #[derive(Clone, Debug, Serialize)] pub struct JobStatus { + /// Complete passes omitted only when both prepaid snapshots are externally retained. + /// Final rendering continues; this is not a dropped sample or a stalled job. + pub preview_retention_skips: u32, + /// This request still renders final output, but has no intermediate-image route. + #[serde(skip_serializing_if = "Option::is_none")] + pub preview_unavailable_reason: Option<&'static str>, #[serde(skip_serializing_if = "Option::is_none")] pub punctual_diagnostics: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -362,6 +465,7 @@ pub struct JobStatus { } struct Data { + preview_retention_skips: u32, completed_duration: Option, punctual_diagnostics: Option, sampling: Option, @@ -371,10 +475,12 @@ struct Data { preview: Option>, } struct Record { + work_released: AtomicBool, + preview_unavailable_reason: Option<&'static str>, started: web_time::Instant, presentation: Option>, textures: Option, - options: JobOptions, + options: Option, environment: Option, _request_reservation: Option, id: JobId, @@ -388,6 +494,12 @@ struct Record { } impl Record { + fn options(&self) -> Result { + match &self.options { + None => Ok(JobOptions::default()), + Some(slot) => slot.0.first().copied().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing retained render options")), + } + } fn notify(&self) { #[cfg(not(target_arch = "wasm32"))] self.done.notify_all(); @@ -401,6 +513,13 @@ impl JobHandle { pub fn id(&self) -> JobId { self.0.id } + /// True only after queued/running captures, tasks and their work reservations + /// have been dropped. A terminal phase alone does not prove resource release. + /// Retained final/preview images and status-input leases remain owned by their + /// observers; callers retiring a job must drop those handles after this barrier. + pub fn work_released(&self) -> bool { + self.0.work_released.load(Ordering::Acquire) + } /// Submission-to-publication time, captured once by the host, independent of UI polling. pub fn completed_duration(&self) -> Result> { self.0.data.lock().map(|data| data.completed_duration).map_err(|_| JobError::new(ErrorCode::Internal, "render duration lock poisoned")) @@ -408,13 +527,15 @@ impl JobHandle { pub fn status(&self) -> Result { let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; Ok(JobStatus { + preview_retention_skips: data.preview_retention_skips, + preview_unavailable_reason: self.0.preview_unavailable_reason, punctual_diagnostics: data.punctual_diagnostics, presentation: self.0.presentation.as_deref().map(|retained| retained.info.clone()), sampling: data.sampling.clone(), linear_master: data.frame.as_ref().and_then(|frame| frame.linear_master_info().cloned()), preview: data.preview.as_ref().map(|preview| preview.info.clone()), textures: self.0.textures.clone(), - options: self.0.options, + options: self.0.options()?, environment: self.0.environment.clone(), job: self.0.id, scene_generation: self.0.scene_generation, @@ -473,29 +594,242 @@ impl JobHandle { } } +/// The last field of Work and Running. Rust drops earlier fields first, so +/// observers cannot see this barrier until captured inputs, executor tasks, +/// pending PNGs, reservations and checkpoint credits have actually been released. +struct WorkRelease(Weak); +impl Drop for WorkRelease { + fn drop(&mut self) { + if let Some(record) = self.0.upgrade() { + record.work_released.store(true, Ordering::Release); + record.notify(); + } + } +} + +/// Independently prepaid captured metadata, retained beyond any one Work/frame. +/// The owner must place its backing before this field so backing drops first. +pub struct RetainedMetadata(Reservation); +impl RetainedMetadata { + pub fn bytes(&self) -> u64 { + self.0.bytes + } +} + +/// The explicit execution envelope for NEW common map capture. Registered +/// executors use their actual host limit and never a synthetic CPU profile. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CaptureProfile { + CpuRaytrace(super::CpuBudget), + Registered, +} +impl CaptureProfile { + fn integrator(self) -> Integrator { + match self { + Self::CpuRaytrace(_) => Integrator::Raytrace, + Self::Registered => Integrator::Raster, + } + } + fn budget(self) -> super::CpuBudget { + match self { + Self::CpuRaytrace(budget) => budget, + Self::Registered => super::CpuBudget::Compact, + } + } +} + +// Serialize metadata directly into the existing hash state: no captured source, +// descriptor JSON Value or retained descriptor Vec/String clone is created. +fn capture_fingerprint(value: &impl Serialize) -> Result<[u8; 32]> { + struct HashWriter(Sha256); + impl std::io::Write for HashWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.update(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut writer = HashWriter(Sha256::new()); + serde_json::to_writer(&mut writer, value).map_err(|e| JobError::new(ErrorCode::Internal, format!("capture descriptor: {e}")))?; + Ok(writer.0.finalize().into()) +} + +/// Move-only same-pool high-water credit acquired BEFORE common captured map +/// backing. Its enclosing caller must drop that backing before this lease. +/// Submission consumes it into the ordinary PreparedSubmission reservations. +/// Any high-water excess over the final layout remains billed as preparation +/// backing until Work releases; Record retains only its normal summary lease. +pub struct CaptureLease<'a> { + host: ImageHost, + profile: CaptureProfile, + descriptor: [u8; 32], + execution: [u8; 32], + retained: Option<&'a RetainedMetadata>, + cancel: CancelToken, + reservation: Reservation, + consumed: bool, +} +impl CaptureLease<'_> { + pub fn bytes(&self) -> u64 { + self.reservation.bytes + } + fn check(&self, cancel: &CancelToken) -> Result<()> { + if self.consumed { + return Err(JobError::new(ErrorCode::InvalidRequest, "capture credit was already consumed")); + } + if !Arc::ptr_eq(&self.cancel.0, &cancel.0) { + return Err(JobError::new(ErrorCode::WrongOwner, "capture cancellation owner changed")); + } + self.cancel.check()?; + cancel.check()?; + let descriptor = self.host.capture_descriptor(self.profile)?; + if capture_fingerprint(&descriptor)? != self.descriptor { + return Err(JobError::new(ErrorCode::HostUnavailable, "capture executor metadata changed")); + } + Ok(()) + } + /// Add only the difference between the next live peak and existing credit. + /// Retired duplicate/pending buffers reuse this high-water lease; no release + /// or reacquisition is needed between capture phases. + pub fn try_extend(&mut self, bytes: u64, cancel: &CancelToken) -> Result<()> { + self.check(cancel)?; + let total = self.bytes().checked_add(bytes).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "capture credit overflow"))?; + self.host.check_request_sum(total, self.retained.map_or(0, RetainedMetadata::bytes), self.profile.budget())?; + let mut extra = self.host.0.shared.budget.reserve(bytes)?; + self.reservation.merge_from(&mut extra) + } + fn check_request(&self, host: &ImageHost, request: &ImageRequest, cancel: &CancelToken, retained: Option<&RetainedMetadata>) -> Result<()> { + if !self.host.same_host(host) { + return Err(JobError::new(ErrorCode::WrongOwner, "capture credit belongs to a different installed host")); + } + self.check(cancel)?; + let selected = if host.0.executor.is_some() { CaptureProfile::Registered } else { CaptureProfile::CpuRaytrace(request.cpu_budget()) }; + if self.profile != selected || request.integrator != self.profile.integrator() { + return Err(JobError::new(ErrorCode::WrongOwner, "capture execution profile changed")); + } + host.capture_retained_context(retained)?; + let same_retained = match (self.retained, retained) { + (None, None) => true, + (Some(before), Some(after)) => std::ptr::eq(before, after), + _ => false, + }; + if !same_retained { + return Err(JobError::new(ErrorCode::WrongOwner, "capture retained-metadata context changed")); + } + let bytes = request + .textures + .as_ref() + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "capture credit requires common texture backing"))? + .captured_bytes()?; + if bytes > self.bytes() { + return Err(JobError::new(ErrorCode::LimitExceeded, "captured texture backing exceeds its prepaid credit")); + } + Ok(()) + } +} + +/// Captured, completely validated input under the existing host budget. This +/// has no job identity, document or camera mutation, and cannot be cloned. +pub struct PreparedSubmission { + scene: ProductScene, + public_request: ImageRequest, + work_request: Option, + options: Option, + environment: Option, + environment_info: Option, + textures: Option, + resolved: crate::ResolvedRequest, + admission: Admission, + cancel: CancelToken, + #[cfg(feature = "raytrace-cpu")] + proof: Vec, + request_reservation: Option, + reservation: Reservation, + host: ImageHost, +} +impl PreparedSubmission { + /// Check a simultaneously retained metadata owner under the same unchanged + /// per-job/profile cap. It is not funded by a Work/frame lease. + pub fn check_retained_metadata(&self, bytes: u64) -> Result<()> { + let retained = self + .request_reservation + .as_ref() + .map_or(0, |r| r.bytes) + .checked_add(bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained metadata byte overflow"))?; + self.host.check_request_sum(self.reservation.bytes, retained, self.request().cpu_budget()) + } + pub fn reserve_retained_metadata(&self, bytes: u64) -> Result { + self.check_retained_metadata(bytes)?; + self.host.0.shared.budget.reserve(bytes).map(RetainedMetadata) + } + pub fn request(&self) -> &ImageRequest { + self.work_request.as_ref().unwrap_or(&self.public_request) + } + pub fn admission(&self) -> Admission { + self.admission + } + pub fn check_cancel(&self) -> Result<()> { + self.cancel.check() + } + pub fn executor(&self) -> &crate::ExecutorId { + &self.resolved.executor + } + pub fn host(&self) -> &ImageHost { + &self.host + } + pub fn options(&self) -> Result { + match &self.options { + None => Ok(JobOptions::default()), + Some(slot) => slot.0.first().copied().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing prepared render options")), + } + } +} + struct Work { + #[cfg(feature = "raytrace-cpu")] + proof: Vec, regrade: Option<(Arc, super::presentation::Presentation)>, request: Option, executor: Option>, environment: Option, scene: ProductScene, handle: JobHandle, + encoded_limit: u64, reservation: Reservation, + // Must remain last: see WorkRelease. + _work_release: WorkRelease, } +// A queued request moves into the task at begin; no task allocation exists yet. +// Its fixed queue metadata must fit the same already prepaid task allowance, +// independently of the separate retained-Record header reservation. +const _: [(); 1] = [(); (std::mem::size_of::() <= 4096) as usize]; // One host advance hashes at most four 16 KiB chunks, independently of the // integrator's quantum. The unchanged work reservation covers the sole PNG and // this fixed state until publication; it is not another image task or pool. const PNG_HASH_CHUNK_BYTES: usize = 16_384; const PNG_HASH_CHUNKS_PER_ADVANCE: usize = 4; pub(crate) const FRAME_METADATA_BYTES: u64 = 1024; +#[cfg(feature = "raytrace-cpu")] +const PREPARED_PROOF_HEADER_BYTES: usize = std::mem::size_of::>(); +#[cfg(not(feature = "raytrace-cpu"))] +const PREPARED_PROOF_HEADER_BYTES: usize = 0; +// Preparation/enqueue only moves fixed headers. All source/resource capacities +// and optical proof backing have independent admission; none survives without +// the owning work/request lease. Keep the existing preparation allowance. +const _: [(); 1] = + [(); (std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::() + <= super::image::PREPARATION_METADATA_BYTES as usize) as usize]; struct PendingPng { png: Vec, digest: Sha256, + png_digest: Option>, hashed: usize, preview_samples: Option, exr: Option>, - exr_digest: Sha256, exr_hashed: usize, } // Keep the new fixed completion state within the existing metadata allowance @@ -504,6 +838,7 @@ const _: [(); 1] = [(); (std::mem::size_of::() <= 512) as usize]; const _: [(); 1] = [(); (std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::() + + PREPARED_PROOF_HEADER_BYTES + 64 + 2 * crate::MAX_RENDER_ID_BYTES + 32 @@ -511,10 +846,9 @@ const _: [(); 1] = [(); (std::mem::size_of::() impl PendingPng { fn new(png: Vec) -> Self { - Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, exr_digest: Sha256::new(), exr_hashed: 0 } + Self { png, digest: Sha256::new(), png_digest: None, hashed: 0, preview_samples: None, exr: None, exr_hashed: 0 } } - #[cfg(feature = "raytrace-cpu")] fn preview(png: Vec, samples: u32) -> Self { Self { preview_samples: Some(samples), ..Self::new(png) } } @@ -522,20 +856,29 @@ impl PendingPng { fn step(&mut self, units: usize, cancel: &CancelToken) -> Result { cancel.check()?; for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) { - let (bytes, hashed, digest) = if self.hashed < self.png.len() { - (&self.png, &mut self.hashed, &mut self.digest) + self.finish_png_digest(); + let (bytes, hashed) = if self.hashed < self.png.len() { + (&self.png, &mut self.hashed) } else if let Some(exr) = self.exr.as_ref().filter(|exr| self.exr_hashed < exr.len()) { - (exr, &mut self.exr_hashed, &mut self.exr_digest) + (exr, &mut self.exr_hashed) } else { break; }; let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len()); - digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?); + self.digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?); *hashed = end; cancel.check()?; } + self.finish_png_digest(); Ok(self.hashed == self.png.len() && self.exr.as_ref().is_none_or(|exr| self.exr_hashed == exr.len())) } + fn finish_png_digest(&mut self) { + if self.hashed == self.png.len() && self.png_digest.is_none() { + // PNG and EXR are scanned sequentially. Keep only its fixed digest + // while resetting the same SHA state for the optional raw companion. + self.png_digest = Some(self.digest.finalize_reset()); + } + } fn progress(&self) -> Progress { Progress { phase: Phase::Encoding, @@ -552,8 +895,40 @@ struct Running { handle: JobHandle, reservation: Option, next_preview_sequence: u32, + next_checkpoint_pass: u32, + checkpoint_target: u32, + checkpoints: Option>, + // Must remain last: see WorkRelease. + _work_release: WorkRelease, } +impl Drop for Running { + fn drop(&mut self) { + if let Some(credits) = &self.checkpoints { + credits.close(); + } + } +} + +/// One independently prepaid options value. Exact defaults have no slot; authored +/// option/effect presence is structural and is never normalized into that case. +/// The containing Record is smaller than its previous inline JobOptions field. +/// This lease survives work release and frame eviction through retained handles. +struct RetainedOptions(Vec); +impl RetainedOptions { + fn new(options: JobOptions) -> Result { + let _ = options.retained_bytes()?; + let mut values = Vec::new(); + values.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve retained render options"))?; + if values.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "retained render options exceed their prepaid capacity")); + } + values.push(options); + Ok(Self(values)) + } +} +const _: [(); 1] = [(); (std::mem::size_of::>() <= std::mem::size_of::()) as usize]; + /// One fallibly allocated task, keeping the dispatch enum small in either build. /// Its bounded metadata allocation fits the existing per-job task allowance. struct TaskSlot(Vec); @@ -584,11 +959,7 @@ enum WorkTask { enum WorkPoll { Existing(TaskPoll), - #[cfg(feature = "raytrace-cpu")] - Preview { - png: Vec, - samples_per_pixel: u32, - }, + Preview { png: Vec, samples_per_pixel: u32 }, } impl WorkTask { @@ -596,6 +967,7 @@ impl WorkTask { match self { #[cfg(feature = "raytrace-cpu")] Self::Raytrace(slot) => slot.0.first().and_then(|task| task.punctual_diagnostics()), + Self::Registered(task) => task.punctual_diagnostics(), _ => None, } } @@ -611,12 +983,16 @@ impl WorkTask { fn sampling_report(&self) -> Option { match self { Self::Registered(task) => task.sampling_report(), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.sampling_report()), _ => None, } } fn take_linear_exr(&mut self) -> Option> { match self { Self::Registered(task) => task.take_linear_exr(), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.0.first_mut().and_then(|task| task.take_linear_exr()), _ => None, } } @@ -625,6 +1001,7 @@ impl WorkTask { request: ImageRequest, cancel: CancelToken, environment: Option, + #[cfg(feature = "raytrace-cpu")] proof: Option, ) -> Result { let _ = &environment; match request.integrator { @@ -633,7 +1010,7 @@ impl WorkTask { #[cfg(feature = "raytrace-cpu")] { let options = request.raytrace.clone().unwrap_or_default(); - crate::raytrace::image::ImageTask::new_with_environment(scene, request, cancel, options, environment) + crate::raytrace::image::ImageTask::new_prepared(scene, request, cancel, options, environment, proof) .and_then(TaskSlot::new) .map(Self::Raytrace) } @@ -648,7 +1025,17 @@ impl WorkTask { fn step(&mut self, units: usize) -> Result { match self { Self::Regrade(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), - Self::Registered(task) => task.step(units).map(WorkPoll::Existing), + Self::Registered(task) => { + let poll = task.step(units)?; + if let Some(preview) = task.take_preview() { + if !matches!(poll, TaskPoll::Pending(_)) { + return Err(JobError::new(ErrorCode::Internal, "executor published provisional and final output together")); + } + Ok(WorkPoll::Preview { png: preview.png, samples_per_pixel: preview.samples_per_pixel }) + } else { + Ok(WorkPoll::Existing(poll)) + } + } Self::Raster(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), #[cfg(feature = "raytrace-cpu")] Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_previews(units)? { @@ -679,7 +1066,41 @@ fn terminal(handle: &JobHandle, error: JobError) { } impl Running { - fn begin(work: Work) -> Option { + fn begin(mut work: Work) -> Option { + let options = match work.handle.0.options() { + Ok(options) => options, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + let checkpoint_target = if work.regrade.is_some() { + 0 + } else if let Some(executor) = &work.executor { + executor.preview_samples(options).unwrap_or(0) + } else if work.handle.0.request.integrator == Integrator::Raytrace { + work.handle.0.request.raytrace.as_ref().map_or(Ok(0), super::RaytraceOptions::preview_target).unwrap_or(0) + } else { + 0 + }; + let checkpoints = (|| { + let slots = checkpoint_target.saturating_sub(1).min(2); + if slots == 0 { + return Ok(None); + } + let slot_bytes = work + .encoded_limit + .checked_add(FRAME_METADATA_BYTES) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint slot overflow"))?; + CheckpointCredits::new(&mut work.reservation, slot_bytes, slots).map(Some) + })(); + let checkpoints = match checkpoints { + Ok(credits) => credits, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; if work.handle.0.cancel.is_cancelled() { terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render cancelled")); return None; @@ -694,10 +1115,19 @@ impl Running { super::regrade::RegradeTask::new(source, presentation, work.handle.0.cancel.clone()).and_then(TaskSlot::new).map(WorkTask::Regrade) } else if let Some(executor) = work.executor { let request = work.request.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing registered executor request"))?; - executor.begin(work.scene, request, work.handle.0.options, work.handle.0.cancel.clone()).map(WorkTask::Registered) + executor.begin(work.scene, request, options, work.handle.0.cancel.clone()).map(WorkTask::Registered) } else { + // CPU textures are work-owned just like registered resources. The + // public/status request has already had those Arcs removed. let request = work.request.unwrap_or_else(|| work.handle.0.request.clone()); - WorkTask::new(work.scene, request, work.handle.0.cancel.clone(), work.environment) + WorkTask::new( + work.scene, + request, + work.handle.0.cancel.clone(), + work.environment, + #[cfg(feature = "raytrace-cpu")] + work.proof.pop(), + ) } })) .unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job"))); @@ -709,6 +1139,10 @@ impl Running { handle: work.handle, reservation: Some(work.reservation), next_preview_sequence: 1, + next_checkpoint_pass: 1, + checkpoint_target, + checkpoints, + _work_release: work._work_release, }), Err(e) => { terminal(&work.handle, e); @@ -744,7 +1178,15 @@ impl Running { self.source_master = self.task.as_ref().map(WorkTask::source_master).transpose()?.flatten(); data.sampling = self.task.as_ref().and_then(WorkTask::sampling_report); let exr = self.task.as_mut().and_then(WorkTask::take_linear_exr); - if exr.is_some() != self.handle.0.options.linear_exr { + let retain_exr = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.output.as_deref()) + .map_or(self.handle.0.options()?.linear_exr, |output| output.linear_exr); + if exr.is_some() != retain_exr { return Err(JobError::new(ErrorCode::Internal, "linear master availability differs from the admitted request")); } if let Some(bytes) = &exr { @@ -760,7 +1202,6 @@ impl Running { self.pending_png = Some(pending); Ok(true) } - #[cfg(feature = "raytrace-cpu")] WorkPoll::Preview { png, samples_per_pixel } => { // Retain the integrator/film and the entire remaining work lease. // Hash the checkpoint before making immutable bytes observable. @@ -782,7 +1223,7 @@ impl Running { data.progress = progress; return Ok(true); } - let PendingPng { png, digest, preview_samples, exr, exr_digest, .. } = + let PendingPng { png, digest, png_digest, preview_samples, exr, .. } = self.pending_png.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed PNG digest"))?; let info = FrameInfo { job: self.handle.0.id, @@ -794,13 +1235,17 @@ impl Running { encoding: ColourEncoding::Srgb, alpha: AlphaConvention::Straight, png_bytes: png.len() as u64, - png_sha256: format!("{:x}", digest.finalize()), + png_sha256: format!("{:x}", png_digest.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed PNG digest"))?), }; // Include the working digest/Vec metadata, completed frame layout, // actual hex allocation, bounded copied IDs and Arc/header allowance. // The PNG allocation itself is retained once and billed by capacity below. let frame_layout = if preview_samples.is_some() { std::mem::size_of::() } else { std::mem::size_of::() }; - let fixed_metadata = std::mem::size_of::() + frame_layout + 2 * crate::MAX_RENDER_ID_BYTES + 32; + // A retained checkpoint keeps its shared credit ledger alive even after + // the running job closes it. Bill that fixed Arc payload/header through + // the checkpoint's own metadata allowance as well as its PNG capacity. + let checkpoint_metadata = if preview_samples.is_some() { std::mem::size_of::() + 32 } else { 0 }; + let fixed_metadata = std::mem::size_of::() + frame_layout + checkpoint_metadata + 2 * crate::MAX_RENDER_ID_BYTES + 32; let linear_digest_bytes = if exr.is_some() { 64 } else { 0 }; if fixed_metadata .checked_add(info.png_sha256.capacity()) @@ -815,47 +1260,92 @@ impl Running { // while the final-only path has already released it. self.handle.0.cancel.check()?; if let Some(samples_per_pixel) = preview_samples { - let options = self - .handle - .0 - .request - .raytrace - .as_ref() - .and_then(|options| options.progressive) - .ok_or_else(|| JobError::new(ErrorCode::Internal, "preview requires CPU progressive intent"))?; + let target_samples = self.checkpoint_target; let frame_sequence = self.next_preview_sequence; - let expected = frame_sequence.checked_sub(1).and_then(|n| 1_u32.checked_shl(n)); - if expected != Some(samples_per_pixel) || samples_per_pixel >= options.samples_per_pixel || self.task.is_none() { + let expected = Some(self.next_checkpoint_pass); + if expected != Some(samples_per_pixel) || samples_per_pixel >= target_samples || self.task.is_none() { return Err(JobError::new(ErrorCode::Internal, "invalid progressive checkpoint sequence")); } let next_sequence = frame_sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::Internal, "preview sequence exhausted"))?; - let reservation = self - .reservation - .as_mut() - .ok_or_else(|| JobError::new(ErrorCode::Internal, "missing progressive reservation"))? - .split(png.capacity() as u64 + FRAME_METADATA_BYTES)?; + let credits = self.checkpoints.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing checkpoint credits"))?; + if (png.capacity() as u64).checked_add(FRAME_METADATA_BYTES).is_none_or(|bytes| bytes > credits.slot_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "checkpoint PNG exceeds its admitted slot")); + } + let mut reservation = credits.acquire()?; + if reservation.is_none() { + // Reclaim a host-only snapshot without removing a consumer's pinned + // latest pass. Unwrap under the data lock so a racing Weak upgrade + // either pins the Arc we restore or observes its payload released. + let released = match data.preview.take().map(Arc::try_unwrap) { + Some(Ok(preview)) => Some(preview), + Some(Err(preview)) => { + data.preview = Some(preview); + None + } + None => None, + }; + drop(data); + // Returning its lease locks the credit ledger; keep that outside + // the status/publication lock before retrying the free slot. + drop(released); + reservation = credits.acquire()?; + data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; + self.handle.0.cancel.check()?; + } + self.next_checkpoint_pass = self + .next_checkpoint_pass + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; + let Some(reservation) = reservation else { + data.preview_retention_skips = data + .preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint retention diagnostic overflow"))?; + return Ok(true); + }; data.preview = Some(Arc::new(RenderPreview { - info: PreviewInfo { frame_sequence, samples_per_pixel, frame: info }, + info: PreviewInfo { + frame_sequence, + samples_per_pixel, + adaptive: match self.handle.0.request.raytrace.as_ref().filter(|_| self.handle.0.request.integrator == Integrator::Raytrace) { + Some(options) => options + .adaptive + .as_deref() + .map(|adaptive| { + let maximum = options + .progressive + .ok_or_else(|| JobError::new(ErrorCode::Internal, "adaptive CPU preview has no captured film"))? + .samples_per_pixel; + super::adaptive::AdaptivePreview::captured(*adaptive, maximum, samples_per_pixel) + }) + .transpose()?, + None => super::adaptive::AdaptivePreview::at(self.handle.0.options()?, samples_per_pixel)?, + }, + frame: info, + }, png, _reservation: reservation, })); self.next_preview_sequence = next_sequence; let pixels = u64::from(self.handle.0.request.width) * u64::from(self.handle.0.request.height); data.progress = - Progress { phase: Phase::Running, done: pixels * u64::from(samples_per_pixel), total: pixels * u64::from(options.samples_per_pixel) }; + Progress { phase: Phase::Running, done: pixels * u64::from(samples_per_pixel), total: pixels * u64::from(target_samples) }; self.handle.0.notify(); return Ok(true); } let exr = exr.map(|bytes| { let info = LinearMasterInfo { bytes: bytes.len() as u64, - sha256: format!("{:x}", exr_digest.finalize()), + sha256: format!("{:x}", digest.finalize()), encoding: LinearColourEncoding::SceneLinearSrgbD65, alpha: LinearAlphaConvention::CoveragePremultiplied, }; (bytes, info) }); let retained = png.capacity() as u64 + exr.as_ref().map_or(0, |(bytes, _)| bytes.capacity() as u64) + FRAME_METADATA_BYTES; + if let Some(credits) = &self.checkpoints { + credits.close(); + } let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?; reservation.shrink(retained)?; data.frame = Some(Arc::new(RenderFrame { @@ -1059,7 +1549,78 @@ impl ImageHost { self.0.shared.budget.limit } + fn capture_retained_context(&self, retained: Option<&RetainedMetadata>) -> Result> { + if retained.is_some_and(|lease| !Arc::ptr_eq(&lease.0.budget, &self.0.shared.budget)) { + return Err(JobError::new(ErrorCode::WrongOwner, "retained metadata belongs to a different host pool")); + } + Ok(retained.map(RetainedMetadata::bytes)) + } + fn capture_descriptor(&self, profile: CaptureProfile) -> Result { + if matches!(profile, CaptureProfile::Registered) != self.0.executor.is_some() { + return Err(JobError::new(ErrorCode::WrongOwner, "capture profile does not match the installed host")); + } + self.validate_integrator(profile.integrator())?; + if let CaptureProfile::CpuRaytrace(budget) = profile { + budget.validate_execution()?; + } + let descriptor = self.descriptor_for(profile.integrator())?; + if descriptor.availability != Availability::Available || descriptor.profiles.len() != 1 { + return Err(JobError::new(ErrorCode::HostUnavailable, "capture executor is unavailable")); + } + Ok(descriptor) + } + /// Fund the next capture peak without a scene/request, fake job or renderer + /// allocation. The independent Plan lease is counted, never transferred. + pub fn reserve_capture<'a>( + &self, + bytes: u64, + profile: CaptureProfile, + cancel: &CancelToken, + retained: Option<&'a RetainedMetadata>, + ) -> Result> { + cancel.check()?; + let mut descriptor = self.capture_descriptor(profile)?; + let context = self.capture_retained_context(retained)?; + self.check_request_sum(bytes, context.unwrap_or(0), profile.budget())?; + let descriptor_hash = capture_fingerprint(&descriptor)?; + // Resolution canonicalizes these enum lists. Pin its same value order + // without cloning/allocating another profile or altering the raw hash. + for profile in &mut descriptor.profiles { + profile.formats.sort_unstable(); + profile.features.sort_unstable(); + } + let execution = capture_fingerprint(&(&descriptor.id, descriptor.profiles.first()))?; + let reservation = self.0.shared.budget.reserve(bytes)?; + Ok(CaptureLease { + host: self.clone(), + profile, + descriptor: descriptor_hash, + execution, + retained, + cancel: cancel.clone(), + reservation, + consumed: false, + }) + } + + /// Strict blocking API. Native UI callers prepare beside the window. The + /// temporary lease exists before any new box proof backing is allocated. pub fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + let admission = self.admit_layout(scene, request, options)?; + #[cfg(feature = "raytrace-cpu")] + if self.0.executor.is_none() && request.integrator == Integrator::Raytrace { + let defaults = super::RaytraceOptions::default(); + let raytrace = request.raytrace.as_ref().unwrap_or(&defaults); + let bytes = crate::raytrace::image::certification_bytes(scene, raytrace)?; + if bytes != 0 { + let _validation = self.0.shared.budget.reserve(bytes)?; + crate::raytrace::image::certify_for_request(scene, request, raytrace, &CancelToken::default())?; + } + } + Ok(admission) + } + + fn admit_layout(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { let scatter = |t: Option| t.and_then(|v| v.subsurface()).is_some_and(|s| s.active()); if scene.meshes.iter().any(|b| scatter(b.transmission) || b.faces.iter().any(|f| scatter(f.transmission))) && !self.0.executor.as_ref().is_some_and(|executor| executor.supports_subsurface()) @@ -1100,7 +1661,25 @@ impl ImageHost { if (!options.finishing.is_identity() || options.backdrop.is_some()) && !executor.supports_finishing() { return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply the requested finishing/backdrop")); } - let admission = executor.admit(scene, request, options)?; + let mut admission = executor.admit(scene, request, options)?; + if let Some(samples) = executor.preview_samples(options) { + if !(1..=options.preview_target()?).contains(&samples) { + return Err(JobError::new(ErrorCode::InvalidRequest, "executor preview target exceeds captured sampling passes")); + } + let slots = samples.saturating_sub(1).min(2); + if slots != 0 { + let previews = admission + .encoded_limit + .checked_add(FRAME_METADATA_BYTES) + .and_then(|bytes| bytes.checked_mul(u64::from(slots))) + .and_then(|bytes| bytes.checked_add(FRAME_METADATA_BYTES)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "executor preview admission overflow"))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(previews) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "executor preview admission overflow"))?; + } + } if admission.estimated_total_bytes > self.job_limit_bytes() { return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); } @@ -1110,7 +1689,7 @@ impl ImageHost { if options != JobOptions::default() { return Err(JobError::new(ErrorCode::InvalidRequest, "CPU images use raytrace options, not progressive sampling controls")); } - admit(scene, request) + super::image::admit_layout(scene, request) } } @@ -1245,6 +1824,74 @@ impl ImageHost { options: JobOptions, environment: Option, ) -> Result { + if id.session == 0 || id.serial == 0 || id.generation == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); + } + let prepared = self.prepare_submission(scene, request, options, environment, CancelToken::default())?; + self.submit_prepared(id, scene_generation, prepared) + } + + /// Strict captured preparation. All new certificate backing is reserved + /// before allocation; the opaque capsule owns resources and leases to enqueue. + pub fn prepare_submission( + &self, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + cancel: CancelToken, + ) -> Result { + self.prepare_submission_with_metadata(scene, request, options, environment, cancel, None) + } + /// The external owner already holds this independent same-pool lease. Count + /// its simultaneous backing before certificate/renderer allocation, without + /// reserving it twice or transferring its lifetime into Work. + pub fn prepare_submission_with_metadata( + &self, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + cancel: CancelToken, + retained: Option<&RetainedMetadata>, + ) -> Result { + self.prepare_submission_inner(scene, request, options, environment, cancel, retained, None) + } + /// Consume already-owned capture credit. On any inner refusal/unwind, its + /// typed inputs drop before this outer lease. After PreparedSubmission owns + /// those inputs, merge credit and use the original Work/request split. + pub fn prepare_submission_with_capture( + &self, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + cancel: CancelToken, + retained: Option<&RetainedMetadata>, + mut capture: CaptureLease<'_>, + ) -> Result { + self.prepare_submission_inner(scene, request, options, environment, cancel, retained, Some(&mut capture)) + } + fn prepare_submission_inner( + &self, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + cancel: CancelToken, + retained: Option<&RetainedMetadata>, + capture: Option<&mut CaptureLease<'_>>, + ) -> Result { + if let Some(credit) = capture.as_deref() { + credit.check_request(self, &request, &cancel, retained)?; + } + cancel.check()?; + if retained.is_some_and(|lease| !Arc::ptr_eq(&lease.0.budget, &self.0.shared.budget)) { + return Err(JobError::new(ErrorCode::WrongOwner, "retained metadata belongs to a different host pool")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } if self.0.executor.is_some() && environment.is_some() { return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU environments")); } @@ -1255,9 +1902,6 @@ impl ImageHost { if environment.is_some() { request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(&scene)?; } - if id.session == 0 || id.serial == 0 || id.generation == 0 { - return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); - } let environment_info = environment .as_ref() .map(|e| JobEnvironmentInfo::Cpu(e.metadata())) @@ -1267,7 +1911,8 @@ impl ImageHost { if environment.is_some() { std::mem::size_of::() as u64 } else { 0 } + request.retained_resource_metadata_bytes(); let request_bytes = retained_request_bytes(&request)? - .checked_add(metadata_bytes) + .checked_add(options.retained_bytes()?) + .and_then(|bytes| bytes.checked_add(metadata_bytes)) .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?; let mut features = scene.required_features(); if environment.is_some() || request.environment.is_some() { @@ -1279,15 +1924,25 @@ impl ImageHost { { features.push(crate::RenderFeature::Refraction); } - let Admission { estimated_total_bytes, .. } = self.admit(&scene, &request, options)?; + let mut admission = self.admit_layout(&scene, &request, options)?; + let estimated_total_bytes = admission.estimated_total_bytes; let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; let estimated_total_bytes = estimated_total_bytes .checked_add(environment_bytes) .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; - self.check_request_sum(estimated_total_bytes, request_bytes, request.cpu_budget())?; + let simultaneous = request_bytes + .checked_add(retained.map_or(0, RetainedMetadata::bytes)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained preparation byte overflow"))?; + self.check_request_sum(estimated_total_bytes, simultaneous, request.cpu_budget())?; let mut backend = crate::builtin_backend(); let descriptor = self.descriptor_for_request(&request)?; + if let Some(credit) = capture.as_deref() + && credit.profile == CaptureProfile::Registered + && capture_fingerprint(&descriptor)? != credit.descriptor + { + return Err(JobError::new(ErrorCode::HostUnavailable, "resolved capture executor metadata changed")); + } let expected_executor = descriptor.id.clone(); backend.executors = vec![descriptor]; let resolved = crate::resolve_request( @@ -1307,37 +1962,160 @@ impl ImageHost { if resolved.executor != expected_executor { return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product executor is unavailable")); } - let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; - if self.0.shared.stop.load(Ordering::Acquire) { - return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + // Reap cancelled queued captures on the preparation caller, before a + // replacement competes for their still-held credit. Never hold this + // lock while geometry is certified. + { + let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); } - queue.retain(|work| !work.handle.0.cancel.is_cancelled()); - if queue.len() >= QUEUE_LIMIT { - return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + let combined_bytes = estimated_total_bytes + .checked_add(request_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "prepared work/request byte overflow"))?; + if let Some(credit) = capture.as_deref() + && capture_fingerprint(&(&resolved.executor, Some(&resolved.profile)))? != credit.execution + { + return Err(JobError::new(ErrorCode::WrongOwner, "resolved capture executor/profile changed")); } - self.check_request_sum(estimated_total_bytes, request_bytes, request.cpu_budget())?; - let reservation = self.0.shared.budget.reserve(estimated_total_bytes)?; - let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; + let already_held = capture.as_deref().map_or(0, CaptureLease::bytes); + // A retired pending duplicate/validator can make capture's high-water + // peak larger than the final renderer layout. Keep that conservative + // excess in Work until release, and report it as preparation backing. + // The independent Plan is still counted once under the same cap. + if already_held > combined_bytes { + self.check_request_sum(already_held, retained.map_or(0, RetainedMetadata::bytes), request.cpu_budget())?; + let extra = already_held - combined_bytes; + admission.preparation_bytes = admission + .preparation_bytes + .checked_add(extra) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "capture preparation admission overflow"))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(extra) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "capture work admission overflow"))?; + } + let mut reservation = self.0.shared.budget.reserve(combined_bytes.saturating_sub(already_held))?; + // The legacy None branch keeps its original debit and split. Captured + // inputs first move under PreparedSubmission's drop order, while the + // outer caller still owns already_held, before transfer/split can fail. + let request_reservation = if capture.is_some() || request_bytes == 0 { None } else { Some(reservation.split(request_bytes)?) }; // Preserve the original CPU option capacities in the retained request and its lease. - // Registered executors instead move resource Arcs into work and keep a small public copy. + // Registered executors and textured CPU jobs move resource Arcs into work + // and keep a small public copy under the retained metadata lease. let (public_request, work_request) = if self.0.executor.is_some() || request.textures.is_some() { (ImageRequest { environment: None, textures: None, ..request.clone() }, Some(request)) } else { (request, None) }; + + // Move all captured ownership under fields that drop before the leases + // before any remaining fallible certificate/options allocation. + let mut prepared = PreparedSubmission { + scene, + public_request, + work_request, + options: None, + environment, + environment_info, + textures, + resolved, + admission, + cancel, + #[cfg(feature = "raytrace-cpu")] + proof: Vec::new(), + request_reservation, + reservation, + host: self.clone(), + }; + if let Some(credit) = capture { + prepared.reservation.merge_from(&mut credit.reservation)?; + credit.consumed = true; + prepared.request_reservation = if request_bytes == 0 { None } else { Some(prepared.reservation.split(request_bytes)?) }; + } + #[cfg(feature = "raytrace-cpu")] + if self.0.executor.is_none() && prepared.request().integrator == Integrator::Raytrace { + let captured = prepared.request(); + let defaults = super::RaytraceOptions::default(); + let raytrace = captured.raytrace.as_ref().unwrap_or(&defaults); + if let Some(certified) = crate::raytrace::image::certify_for_request(&prepared.scene, captured, raytrace, &prepared.cancel)? { + prepared + .proof + .try_reserve_exact(1) + .map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not retain certified optical result"))?; + if prepared.proof.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "optical proof capacity exceeds admission")); + } + prepared.proof.push(certified); + } + } + prepared.cancel.check()?; + prepared.options = if options.is_structural_default() { None } else { Some(RetainedOptions::new(options)?) }; + Ok(prepared) + } + + /// Bounded publication into the existing queue. The real owning Session + /// supplies identity only after source/host revalidation; no proof is redrained. + pub fn submit_prepared(&self, id: JobId, scene_generation: u64, prepared: PreparedSubmission) -> Result { + self.try_submit_prepared(id, scene_generation, &mut Some(prepared)) + } + + /// Non-consuming failure path for native completion. On refusal the caller + /// retains the complete capsule and its leases for worker-side retirement. + /// Success takes it once, after all fallible queue/identity checks. + pub fn try_submit_prepared(&self, id: JobId, scene_generation: u64, slot: &mut Option) -> Result { + let prepared = slot.as_ref().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "prepared render was already consumed"))?; + if id.session == 0 || id.serial == 0 || id.generation == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); + } + if !self.same_host(&prepared.host) { + return Err(JobError::new(ErrorCode::WrongOwner, "prepared render belongs to a different installed host")); + } + prepared.cancel.check()?; + let options = prepared.options()?; + let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; + if self.0.shared.stop.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + // Background preparation/worker owns cancelled capture retirement. + // A racing cancellation may keep this bounded queue full until drain; + // completion must not destroy large request/source backing on the UI. + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + let prepared = slot.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "prepared render vanished before enqueue"))?; + let PreparedSubmission { + scene, + public_request, + work_request, + options: retained_options, + environment, + environment_info, + textures, + resolved, + admission, + cancel, + #[cfg(feature = "raytrace-cpu")] + proof, + request_reservation, + reservation, + host: _, + } = prepared; let handle = JobHandle(Arc::new(Record { + work_released: AtomicBool::new(false), + preview_unavailable_reason: self.0.executor.as_ref().and_then(|executor| executor.preview_unavailable_reason(options)), started: web_time::Instant::now(), presentation: None, textures, - options, + options: retained_options, environment: environment_info, _request_reservation: request_reservation, id, scene_generation, request: public_request, resolved, - cancel: CancelToken::default(), + cancel, data: Mutex::new(Data { + preview_retention_skips: 0, completed_duration: None, punctual_diagnostics: None, sampling: None, @@ -1351,12 +2129,16 @@ impl ImageHost { })); queue.push_back(Work { regrade: None, + #[cfg(feature = "raytrace-cpu")] + proof, request: work_request, executor: self.0.executor.clone(), scene, handle: handle.clone(), + encoded_limit: admission.encoded_limit, reservation, environment, + _work_release: WorkRelease(Arc::downgrade(&handle.0)), }); drop(queue); #[cfg(not(target_arch = "wasm32"))] @@ -1381,8 +2163,19 @@ impl ImageHost { presentation, denoise_applied: false, }; + let options = JobOptions { + finishing: presentation.finishing, + backdrop: presentation.backdrop, + exposure_ev: presentation.exposure_ev, + tone_map: presentation.tone_map, + ..Default::default() + }; + let option_bytes = options.retained_bytes()?; + let request_bytes = option_bytes + .checked_add(ImageRequest::fixed_cpu_metadata_bytes()) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "master request metadata overflow"))?; let metadata_bytes = (std::mem::size_of::() + origin.master_sha256.capacity() + 32) as u64; - if bytes.checked_add(metadata_bytes).is_none_or(|n| n > self.job_limit_bytes()) { + if bytes.checked_add(metadata_bytes).and_then(|n| n.checked_add(request_bytes)).is_none_or(|n| n > self.job_limit_bytes()) { return Err(JobError::new(ErrorCode::LimitExceeded, "master presentation exceeds the installed host's resource budget")); } let limits = RenderLimits { max_scratch_bytes: self.job_limit_bytes(), ..super::GPU_PATH_LIMITS }; @@ -1426,13 +2219,6 @@ impl ImageHost { integrator: Integrator::Raster, raytrace: None, }; - let options = JobOptions { - finishing: presentation.finishing, - backdrop: presentation.backdrop, - exposure_ev: presentation.exposure_ev, - tone_map: presentation.tone_map, - ..Default::default() - }; let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; if self.0.shared.stop.load(Ordering::Acquire) { return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); @@ -1443,20 +2229,24 @@ impl ImageHost { } let reservation = self.0.shared.budget.reserve(bytes)?; let metadata = self.0.shared.budget.reserve(metadata_bytes)?; + let option_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); let handle = JobHandle(Arc::new(Record { + work_released: AtomicBool::new(false), + preview_unavailable_reason: None, started: web_time::Instant::now(), presentation: Some(origin), textures: None, - options, + options: if options.is_structural_default() { None } else { Some(RetainedOptions::new(options)?) }, environment: None, - _request_reservation: None, + _request_reservation: option_reservation, id, scene_generation: frame.info.scene_generation, request, resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + preview_retention_skips: 0, completed_duration: None, punctual_diagnostics: None, sampling: None, @@ -1469,13 +2259,18 @@ impl ImageHost { done: Condvar::new(), })); queue.push_back(Work { + #[cfg(feature = "raytrace-cpu")] + proof: Vec::new(), regrade: Some((master, presentation)), request: None, executor: None, environment: None, scene: ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, handle: handle.clone(), + // Regrades are final-only and never create checkpoint slots. + encoded_limit: 0, reservation, + _work_release: WorkRelease(Arc::downgrade(&handle.0)), }); drop(queue); #[cfg(not(target_arch = "wasm32"))] @@ -1536,7 +2331,9 @@ fn native_worker(shared: Arc) { } let work = queue.pop_front(); drop(queue); - let Some(mut running) = work.and_then(Running::begin) else { continue }; + let Some(mut running) = work.and_then(Running::begin) else { + continue; + }; if let Ok(mut active) = shared.active.lock() { *active = Some(Arc::downgrade(&running.handle.0)); } @@ -1556,6 +2353,200 @@ fn native_worker(shared: Arc) { #[cfg(test)] mod retained_request_tests { use super::*; + + #[test] + fn retained_native_options_charge_actual_single_capacity_only_for_structural_nondefaults() { + assert_eq!(JobOptions::default().retained_bytes().unwrap(), 0); + let explicit = JobOptions { lighting: Some(super::super::StudioLighting::default()), ..Default::default() }; + let expected = std::mem::size_of::() as u64; + assert_eq!(explicit.retained_bytes().unwrap(), expected); + let slot = RetainedOptions::new(explicit).unwrap(); + assert_eq!(slot.0.capacity(), 1); + assert_eq!(slot.0.len(), 1); + assert_eq!(slot.0[0], explicit); + assert_ne!(slot.0[0], JobOptions::default(), "Some(black studio) must not become an absent default studio"); + assert!(std::mem::size_of::>() <= std::mem::size_of::()); + let mut vignette = JobOptions::default(); + vignette.finishing.vignette = -0.0; + let mut grain = JobOptions::default(); + grain.finishing.photographic.grain = -0.0; + for options in [JobOptions { exposure_ev: -0.0, ..Default::default() }, vignette, grain] { + assert!(!options.is_structural_default()); + assert_eq!(options.retained_bytes().unwrap(), expected); + assert_eq!(RetainedOptions::new(options).unwrap().0[0].exposure_ev.to_bits(), options.exposure_ev.to_bits()); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn retained_gpu_options_lease_survives_work_release_frame_eviction_and_cloned_handles() { + struct OptionsExecutor; + impl ImageExecutor for OptionsExecutor { + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + options.validate()?; + admit(scene, request) + } + fn begin(&self, scene: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result> { + options.validate()?; + CpuExecutor.begin(scene, request, options, cancel) + } + } + for options in [ + JobOptions::default(), + JobOptions { exposure_ev: -0.0, ..Default::default() }, + JobOptions { lighting: Some(super::super::StudioLighting::default()), ..Default::default() }, + ] { + let mut host = ImageHost::with_executor(Arc::new(OptionsExecutor)).unwrap(); + let mut image = request(); + image.integrator = Integrator::Raster; + image.raytrace = None; + let expected = options.retained_bytes().unwrap(); + let job = host + .submit_with_options( + JobId { session: 901, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + image, + options, + ) + .unwrap(); + assert_eq!(job.status().unwrap().options, options); + assert_eq!(job.status().unwrap().options.exposure_ev.to_bits(), options.exposure_ev.to_bits()); + assert_eq!(job.0.options.is_some(), expected != 0); + if let Some(slot) = &job.0.options { + assert_eq!(slot.0.capacity() as u64 * std::mem::size_of::() as u64, expected); + } + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + assert!(job.work_released()); + let frame = job.frame().unwrap().unwrap(); + let held = job.clone(); + assert!(Arc::ptr_eq(&held.0, &job.0)); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), expected + ImageRequest::fixed_cpu_metadata_bytes()); + assert_eq!(held.status().unwrap().options, options); + drop(job); + assert_eq!(host.admitted_bytes(), expected + ImageRequest::fixed_cpu_metadata_bytes()); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn cancelled_gpu_options_are_retained_once_without_work_or_frame_credit() { + struct Pending(CancelToken); + impl ImageWork for Pending { + fn step(&mut self, _: usize) -> Result { + self.0.check()?; + Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: 0, total: 1 })) + } + } + struct Executor(std::sync::mpsc::SyncSender<()>); + impl ImageExecutor for Executor { + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + options.validate()?; + admit(scene, request) + } + fn begin(&self, _: ProductScene, _: ImageRequest, _: JobOptions, cancel: CancelToken) -> Result> { + self.0.send(()).unwrap(); + Ok(Box::new(Pending(cancel))) + } + } + let light = super::super::DirectionalLightOptions { direction: [0.0, 0.0, 2.0], color: [0.25, 0.5, 1.0], intensity: 0.0 }; + let options = JobOptions { + lighting: Some(super::super::StudioLighting { + directional_lights: super::super::DirectionalLights::new(&[light; 8]).unwrap(), + ..Default::default() + }), + ..Default::default() + }; + let (began, received) = std::sync::mpsc::sync_channel(1); + let mut host = ImageHost::with_executor(Arc::new(Executor(began))).unwrap(); + let mut image = request(); + image.integrator = Integrator::Raster; + image.raytrace = None; + let job = host + .submit_with_options( + JobId { session: 902, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + image, + options, + ) + .unwrap(); + // Raw worker-stop below does not drain Shared::queue (Owner::drop does). + // Establish actual begin before cancellation so join proves this active + // work has dropped, independently of native worker scheduling. + received.recv_timeout(std::time::Duration::from_secs(60)).unwrap(); + job.cancel().unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Cancelled); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + assert!(job.work_released()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(job.status().unwrap().options, options); + assert_eq!(host.admitted_bytes(), options.retained_bytes().unwrap() + ImageRequest::fixed_cpu_metadata_bytes()); + let held = job.clone(); + drop(job); + assert_eq!(held.status().unwrap().options, options); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn cpu_master_regrade_retains_exact_options_and_raw_bytes_under_separate_metadata_leases() { + let mut host = CpuHost::for_platform().unwrap(); + let mut image = request(); + image.raytrace.as_mut().unwrap().output = Some(Box::new(super::super::OutputOptions { linear_exr: true, ..Default::default() })); + let original = host + .submit( + JobId { session: 903, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + image, + ) + .unwrap(); + assert_eq!(original.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + assert!(original.0.options.is_none(), "CPU transport options retain their existing request lease, not a second native options slot"); + let original_frame = original.frame().unwrap().unwrap(); + let presentation = super::super::presentation::Presentation { exposure_ev: 1.0, ..Default::default() }; + let derivative = host.submit_regrade(JobId { session: 903, serial: 2, generation: 2 }, &original, presentation).unwrap(); + assert_eq!(derivative.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = derivative.frame().unwrap().unwrap(); + assert_eq!(frame.linear_exr().unwrap(), original_frame.linear_exr().unwrap()); + assert_eq!(derivative.status().unwrap().options.exposure_ev, 1.0); + let option_bytes = derivative.0.options().unwrap().retained_bytes().unwrap(); + let request_bytes = option_bytes + ImageRequest::fixed_cpu_metadata_bytes(); + assert_eq!(derivative.0._request_reservation.as_ref().unwrap().bytes, request_bytes); + let presentation_bytes = derivative.0.presentation.as_ref().unwrap()._reservation.bytes; + derivative.0.data.lock().unwrap().frame = None; + original.0.data.lock().unwrap().frame = None; + drop(frame); + drop(original_frame); + drop(original); + assert_eq!(host.admitted_bytes(), request_bytes + presentation_bytes); + let held = derivative.clone(); + drop(derivative); + assert_eq!(held.status().unwrap().options.exposure_ev, 1.0); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] fn retained_emitters_bill_vector_and_original_name_capacities_in_same_pool() { let mut request = request(); @@ -1599,7 +2590,7 @@ mod retained_request_tests { sides: super::super::EmissionSides::Both, }); request.raytrace.as_mut().unwrap().emissions = Some(values); - let expected = retained_request_bytes(&request).unwrap(); + let expected = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); let mesh = solidcraft_geom::Mesh { positions: vec![solidcore_record::Vec3::ZERO, solidcore_record::Vec3::X, solidcore_record::Vec3::Y], normals: vec![solidcore_record::Vec3::Z; 3], @@ -1637,6 +2628,200 @@ mod retained_request_tests { drop(held); assert_eq!(host.admitted_bytes(), 0); } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn cpu_map_capture_fixture(mapped: bool, corrupt: bool) -> (ProductScene, ImageRequest, std::sync::Weak>) { + use super::super::textures::{BaseColorMode, PlanarFrame, RuntimeTextures, TextureBinding, TextureMap}; + use image::ImageEncoder; + use solidcore_record::Vec3; + use solidcraft_geom::Mesh; + let mut encoded = Vec::new(); + image::codecs::png::PngEncoder::new(&mut encoded).write_image(&[128, 64, 255, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap(); + if corrupt { + let idat = encoded.windows(4).position(|w| w == b"IDAT").unwrap(); + encoded[idat + 4] ^= 0xff; + } + let map = TextureMap::new(encoded, crate::texture_input::MapRole::BaseColor).unwrap(); + let weak = map.source().encoded_weak(); + let surface = if mapped { + Vec3::new(0.5, 0.5, 0.5) + } else { + let v = [128, 64, 255].map(|v| crate::surface::srgb8_to_linear(v) as f32 as f64); + Vec3::new(v[0], v[1], v[2]) + }; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "mapped".into(), + mesh, + color: [255; 3], + opacity: 1.0, + transmission: None, + surface: Some(crate::surface::OpaqueSurface::new(surface, 0.0, 1.0, 1.0).unwrap()), + faces: vec![], + }], + }; + let options = super::super::RaytraceOptions { + lights: Some(vec![super::super::DirectionalLightOptions { + direction: [0.0, 0.0, 1.0], + color: [1.0; 3], + intensity: std::f64::consts::PI, + }]), + progressive: Some(super::super::CpuProgressiveOptions { samples_per_pixel: 3, seed: 9 }), + output: Some(Box::new(super::super::OutputOptions { linear_exr: true, ..Default::default() })), + ..Default::default() + }; + let request = ImageRequest { + width: 1, + height: 1, + camera: crate::Camera { distance: 1.0, fov: 0.0, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..Default::default() }, + background: [0; 3], + transparent_background: false, + integrator: Integrator::Raytrace, + raytrace: Some(options), + environment: None, + studio_weights: None, + textures: if mapped { + Some(Arc::new( + RuntimeTextures::new(vec![TextureBinding { + body_index: 0, + body_name: "mapped".into(), + frame: PlanarFrame { origin: [0.0; 3], u: [100.0, 0.0, 0.0], v: [0.0, 100.0, 0.0] }, + base_color: Some(map), + normal: None, + roughness: None, + metallic: None, + normal_strength: 1.0, + base_color_mode: BaseColorMode::Replace, + flip_v: false, + }]) + .unwrap(), + )) + } else { + None + }, + }; + (scene, request, weak) + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn cpu_map_manual_native_queue() -> ImageHost { + // Deterministic queued/cancel/error boundary test using the real builtin + // CPU factory and work leases; no substitute registered executor or render. + ImageHost(Arc::new(Owner { + executor: None, + shared: ImageHost::shared(super::super::NATIVE_CPU_POOL_BYTES), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn cpu_map_native_factory_consumes_full_work_capture_and_releases_sources_before_retained_frames() { + let (scene, request, weak) = cpu_map_capture_fixture(true, false); + let mut host = ImageHost::for_platform().unwrap(); + let job = host.submit(JobId { session: 3301, serial: 1, generation: 1 }, 1, scene, request).unwrap(); + assert!(job.0.request.textures.is_none(), "Record must never retain a work-only texture Arc"); + let completed = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(completed.progress.phase, Phase::Completed); + assert_eq!(completed.textures.unwrap().bodies, 1); + let (scene, request, _) = cpu_map_capture_fixture(false, false); + let reference = host.submit(JobId { session: 3301, serial: 2, generation: 2 }, 1, scene, request).unwrap(); + assert_eq!(reference.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.join_worker_for_test().unwrap(); + assert!(job.work_released()); + assert!(weak.upgrade().is_none(), "all original encoded Arcs drop even while job/frame handles survive"); + let frame = job.frame().unwrap().unwrap(); + let expected = reference.frame().unwrap().unwrap(); + assert_eq!(frame.png(), expected.png(), "builtin CPU factory must consume full Work.request, not stripped public metadata"); + assert_eq!(frame.linear_exr(), expected.linear_exr()); + assert!(frame.linear_exr().is_some()); + let color = [128, 64, 255].map(|v| { + let x = crate::surface::srgb8_to_linear(v) as f32 as f64; + solidcraft_geom::srgb::encode8(x / (1.0 + x)) + }); + assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [color[0], color[1], color[2], 255]); + let held = job.clone(); + job.0.data.lock().unwrap().frame = None; + reference.0.data.lock().unwrap().frame = None; + drop(frame); + drop(expected); + drop(job); + assert!(weak.upgrade().is_none()); + drop(held); + drop(reference); + assert_eq!(host.admitted_bytes(), 0); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn cpu_map_queued_cancel_failed_decode_and_late_cancel_keep_full_work_barrier_and_no_publication() { + for mode in ["queued_cancel", "failed_decode", "late_cancel"] { + let host = cpu_map_manual_native_queue(); + let (scene, request, weak) = cpu_map_capture_fixture(true, mode == "failed_decode"); + let retained = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); + let job = host.submit(JobId { session: 3302, serial: 1, generation: 1 }, 1, scene, request).unwrap(); + assert!(job.0.request.textures.is_none()); + assert!(weak.upgrade().is_some()); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert!(work.request.as_ref().unwrap().textures.is_some()); + if mode == "queued_cancel" { + job.cancel().unwrap(); + assert!(!job.work_released()); + assert!(Running::begin(work).is_none()); + } else { + let mut running = Running::begin(work).unwrap(); + let mut stopped = false; + for _ in 0..200_000 { + if mode == "late_cancel" && running.pending_png.as_ref().is_some_and(|pending| pending.preview_samples.is_none()) { + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + stopped = true; + break; + } + if !running.guarded_step(1) { + stopped = true; + break; + } + } + assert!(stopped); + assert!(!job.work_released(), "terminal phase cannot release an undropped work lease"); + drop(running); + } + assert!(job.work_released()); + assert!(weak.upgrade().is_none()); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, if mode == "failed_decode" { Phase::Failed } else { Phase::Cancelled }); + assert!(job.frame().unwrap().is_none()); + assert!(job.preview().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), retained, "only exact small public request/summary ownership survives work release"); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), retained); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn cpu_map_source_and_peak_decode_prepaid_pool_refusal_releases_all_captures_before_queueing() { + let (scene, request, weak) = cpu_map_capture_fixture(true, false); + let admission = super::super::admit(&scene, &request).unwrap(); + let total = admission.estimated_total_bytes + retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); + let mut host = cpu_map_manual_native_queue(); + Arc::get_mut(&mut host.0).unwrap().shared = ImageHost::shared(total - 1); + assert_eq!(host.submit(JobId { session: 3303, serial: 1, generation: 1 }, 1, scene, request).err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), 0); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + assert!(weak.upgrade().is_none(), "a failed prepaid capture cannot retain hidden encoded resources or queue a decoder"); + } + fn request() -> ImageRequest { let mut lights = Vec::with_capacity(8); lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); @@ -1668,7 +2853,7 @@ mod retained_request_tests { fn retained_lights_keep_the_same_pool_lease_after_png_eviction() { let host = CpuHost::for_platform().unwrap(); let request = request(); - let expected = retained_request_bytes(&request).unwrap(); + let expected = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); let job = host .submit( JobId { session: 99, serial: 1, generation: 1 }, @@ -1707,7 +2892,7 @@ mod environment_metadata_lease_tests { } let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap(); let metadata = input.metadata(); - let expected = std::mem::size_of::() as u64; + let expected = std::mem::size_of::() as u64 + ImageRequest::fixed_cpu_metadata_bytes(); let mut host = CpuHost::for_platform().unwrap(); let budget = host.0.shared.budget.clone(); let request = ImageRequest { @@ -1791,7 +2976,7 @@ mod surface_request_metadata_tests { let mut request = request(); request.integrator = Integrator::Raytrace; request.raytrace = Some(super::super::RaytraceOptions { surface_effects: Some(effects), ..Default::default() }); - let metadata = retained_request_bytes(&request).unwrap(); + let metadata = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); assert!(metadata >= 32 * 256); let mut oversized = request.clone(); let mut overallocated = Vec::with_capacity(64); diff --git a/crates/render/src/job/host_regrade_tests.rs b/crates/render/src/job/host_regrade_tests.rs index e6ddbaf7f..241b46c2b 100644 --- a/crates/render/src/job/host_regrade_tests.rs +++ b/crates/render/src/job/host_regrade_tests.rs @@ -92,6 +92,38 @@ fn an_empty_pixel_shows_the_background_code_unchanged() { assert_eq!(rgba, [40, 80, 120, 255]); } +#[test] +fn png_and_linear_master_publication_fit_the_existing_metadata_allowance() { + let (host, source, _, _) = fixture(true); + let frame = source.frame().unwrap().unwrap(); + let (_, master) = frame.exr.as_ref().unwrap(); + let metadata = std::mem::size_of::() + + std::mem::size_of::() + + frame.info.png_sha256.capacity() + + master.sha256.capacity() + + 2 * crate::MAX_RENDER_ID_BYTES + + 32; + assert!(metadata <= FRAME_METADATA_BYTES as usize, "actual PNG+EXR metadata {metadata} exceeds {}", FRAME_METADATA_BYTES); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(master.sha256, format!("{:x}", Sha256::digest(frame.linear_exr().unwrap()))); + let image_bytes = frame.png.capacity() as u64 + frame.exr.as_ref().unwrap().0.capacity() as u64 + FRAME_METADATA_BYTES; + let options = source.0.options().unwrap(); + assert!(options.linear_exr, "the fixture retains explicit nondefault output intent"); + let slot = source.0.options.as_ref().unwrap(); + assert_eq!(slot.0.capacity(), 1); + let option_bytes = std::mem::size_of::() as u64; + assert_eq!(options.retained_bytes().unwrap(), option_bytes); + assert_eq!( + host.admitted_bytes(), + image_bytes + option_bytes + ImageRequest::fixed_cpu_metadata_bytes(), + "the source record owns its separately prepaid options slot and fixed request header" + ); + drop(source); + assert_eq!(host.admitted_bytes(), image_bytes, "the held frame retains PNG/raw metadata, not request options"); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + #[test] fn regrade_is_exact_nondestructive_geometry_free_and_flattens_repeated_master_ownership() { let (host, source, begins, settings) = fixture(true); @@ -169,3 +201,50 @@ fn regrade_rejects_foreign_missing_or_invalid_masters_and_cancellation_never_pub drop(source); assert_eq!(host.admitted_bytes(), 0); } + +#[test] +fn fixed_cpu_volume_request_header_is_prepaid_on_completed_and_cancelled_regrades_until_the_last_handle() { + let header = ImageRequest::fixed_cpu_metadata_bytes(); + assert_eq!( + header, + (std::mem::size_of::>() + + std::mem::size_of::>>() + + std::mem::size_of::>>()) as u64 + ); + assert!(header > 0); + let (host, source, _, presentation) = fixture(true); + let before = host.admitted_bytes(); + for (serial, cancel) in [(980, true), (981, false)] { + let job = host.submit_regrade(identity(serial), &source, presentation).unwrap(); + let own = job.0.presentation.as_ref().unwrap(); + let bytes = header + + job.0.options().unwrap().retained_bytes().unwrap() + + (std::mem::size_of::() + own.info.master_sha256.capacity() + 32) as u64; + if cancel { + job.cancel().unwrap(); + for _ in 0..128 { + host.pump(1).unwrap(); + if job.work_released() { + break; + } + } + } else { + finish(&host, &job); + let frame = job.frame().unwrap().unwrap(); + assert!(frame.linear_exr().is_some()); + job.0.data.lock().unwrap().frame = None; + drop(frame); + } + assert!(job.work_released()); + assert_eq!(job.status().unwrap().progress.phase, if cancel { Phase::Cancelled } else { Phase::Completed }); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), before + bytes, "fixed request metadata stays prepaid even with no published frame or running work"); + let clone = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), before + bytes, "a retained status handle still owns the request layout"); + drop(clone); + assert_eq!(host.admitted_bytes(), before); + } + drop(source); + assert_eq!(host.admitted_bytes(), 0); +} diff --git a/crates/render/src/job/host_tests.rs b/crates/render/src/job/host_tests.rs index cae42ce25..f7a1ce410 100644 --- a/crates/render/src/job/host_tests.rs +++ b/crates/render/src/job/host_tests.rs @@ -1,6 +1,10 @@ use super::*; use solidcraft_geom::{Aabb3, Mesh}; +fn fixed_request_metadata_bytes() -> u64 { + request().retained_resource_metadata_bytes() +} + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] mod progressive_checkpoints { use super::*; @@ -27,7 +31,7 @@ mod progressive_checkpoints { height: 4, ..request() }; - let expected = admit(&empty(), &request).unwrap().estimated_total_bytes; + let expected = admit(&empty(), &request).unwrap().estimated_total_bytes + request.retained_resource_metadata_bytes(); let job = host.submit(id(7300, 1), 19, empty(), request).unwrap(); assert_eq!(host.admitted_bytes(), expected); let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); @@ -80,7 +84,7 @@ mod progressive_checkpoints { let frame = job.frame().unwrap().unwrap(); assert_eq!(frame.info.job, job.id()); let retained: u64 = held.iter().map(|p| p._reservation.bytes).sum(); - assert_eq!(host.admitted_bytes(), retained + frame._reservation.bytes); + assert_eq!(host.admitted_bytes(), retained + frame._reservation.bytes + fixed_request_metadata_bytes()); drop(running); drop(job); drop(frame); @@ -94,6 +98,153 @@ mod progressive_checkpoints { assert_eq!(host.admitted_bytes(), 0); } + #[test] + fn two_pass_target_retains_one_snapshot_slot_without_blocking_final() { + let (host, job, mut running) = fixture(2); + let credits = running.checkpoints.as_ref().unwrap(); + assert_eq!(credits.capacity, credits.slot_bytes + FRAME_METADATA_BYTES); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let preview = job.preview().unwrap().unwrap(); + assert_eq!(preview.info.frame_sequence, 1); + assert_eq!(preview.info.samples_per_pixel, 1); + let before = preview.png().to_vec(); + while running.advance(1).unwrap() {} + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().preview_retention_skips, 0); + assert!(job.preview().unwrap().is_none()); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, job.id()); + assert_eq!(preview.png(), before, "the sole retained checkpoint remains immutable"); + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + preview._reservation.bytes + fixed_request_metadata_bytes()); + drop(running); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), preview._reservation.bytes); + drop(preview); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn checkpoint_memory_is_independent_of_target_after_two_prepaid_slots() { + let mut estimated = Vec::new(); + for samples in [3, 8, 64] { + let (host, job, running) = fixture(samples); + estimated.push(host.admitted_bytes()); + assert_eq!(running.checkpoints.as_ref().unwrap().capacity, 2 * running.checkpoints.as_ref().unwrap().slot_bytes + FRAME_METADATA_BYTES); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + assert!(estimated.windows(2).all(|pair| pair[0] == pair[1])); + assert!(std::mem::size_of::() + 32 <= FRAME_METADATA_BYTES as usize); + } + + #[test] + fn every_pass_reuses_two_slots_without_consumer_acknowledgement() { + let (host, job, mut running) = fixture(8); + let initial = host.admitted_bytes(); + let mut prefixes = Vec::new(); + for samples in 1..8 { + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let preview = job.preview().unwrap().unwrap(); + assert_eq!(preview.info.samples_per_pixel, samples); + assert_eq!(preview.info.frame_sequence, samples); + assert_eq!(preview.info.frame.job, job.id()); + assert_eq!(preview.info.frame.scene_generation, 19); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + prefixes.push(preview.png().to_vec()); + assert_eq!(host.admitted_bytes(), initial); + assert_eq!(job.status().unwrap().preview_retention_skips, 0); + // This temporary consumer drops its Arc; the host's old snapshot is + // reclaimed by the next publication without an acknowledgement API. + } + while running.advance(1).unwrap() {} + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, job.id()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + fixed_request_metadata_bytes()); + assert_eq!(prefixes.len(), 7); + drop(running); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn pinned_snapshots_skip_publication_then_resume_without_stalling_final_work() { + let (host, job, mut running) = fixture(8); + let initial = host.admitted_bytes(); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let first = job.preview().unwrap().unwrap(); + let first_bytes = first.png().to_vec(); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let second = job.preview().unwrap().unwrap(); + let second_bytes = second.png().to_vec(); + before_preview(&mut running); + assert_eq!(running.pending_png.as_ref().unwrap().preview_samples, Some(3)); + assert!(running.advance(1).unwrap()); + assert_eq!(job.status().unwrap().preview_retention_skips, 1); + let retained = job.preview().unwrap().expect("a skipped publication must keep the latest published preview available"); + assert!(Arc::ptr_eq(&retained, &second), "a pinned latest preview must retain its existing allocation and lease"); + let status = job.status().unwrap(); + let preview = status.preview.expect("status must still identify the latest published complete pass"); + assert_eq!(preview.frame_sequence, 2); + assert_eq!(preview.samples_per_pixel, 2); + assert_eq!(preview.frame.png_sha256, second.info.frame.png_sha256); + drop(retained); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), initial); + assert_eq!(first.png(), first_bytes); + assert_eq!(second.png(), second_bytes); + drop(first); + for samples in 4..8 { + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let preview = job.preview().unwrap().unwrap(); + assert_eq!(preview.info.samples_per_pixel, samples); + assert_eq!(preview.info.frame_sequence, samples - 1, "sequence counts real publications"); + assert_eq!(host.admitted_bytes(), initial); + } + while running.advance(1).unwrap() {} + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().preview_retention_skips, 1); + assert!(job.preview().unwrap().is_none()); + assert_eq!(second.png(), second_bytes, "old snapshots remain immutable through final publication"); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + second._reservation.bytes + fixed_request_metadata_bytes()); + drop(running); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), second._reservation.bytes); + drop(second); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn retaining_both_slots_never_prevents_completion() { + let (host, job, mut running) = fixture(8); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let first = job.preview().unwrap().unwrap(); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let second = job.preview().unwrap().unwrap(); + while running.advance(1).unwrap() {} + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().preview_retention_skips, 5); + assert_eq!(first.info.samples_per_pixel, 1); + assert_eq!(second.info.samples_per_pixel, 2); + drop(running); + drop(job); + drop(first); + drop(second); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] fn cancellation_before_or_after_digest_cannot_publish_a_late_preview() { for finish_digest in [false, true] { @@ -262,6 +413,8 @@ fn queue_is_bounded_and_cancelled_entries_release_their_reservations() { drop(c); assert!(host.admitted_bytes() > 0, "an externally retained frame retains its lease"); drop(frame); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(a); assert_eq!(host.admitted_bytes(), 0); } @@ -281,6 +434,8 @@ fn cancellation_while_encoding_cannot_publish_a_late_frame() { drain(&host); assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); assert_eq!(host.admitted_bytes(), 0); } @@ -318,6 +473,9 @@ fn closing_the_host_cancels_active_and_queued_work() { drop(host); assert_eq!(active.status().unwrap().progress.phase, Phase::Cancelled); assert_eq!(queued.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(budget.used.load(Ordering::Acquire), 2 * fixed_request_metadata_bytes()); + drop(active); + drop(queued); assert_eq!(budget.used.load(Ordering::Acquire), 0); } @@ -449,7 +607,7 @@ fn png_digest_is_incremental_and_keeps_the_original_allocation_and_lease_until_c let actual_metadata = std::mem::size_of::() + std::mem::size_of::() + frame.info.png_sha256.capacity() + 2 * crate::MAX_RENDER_ID_BYTES + 32; assert!(actual_metadata <= FRAME_METADATA_BYTES as usize, "digest Vec/offset/state and actual hex allocation must be admitted"); - assert_eq!(host.admitted_bytes(), frame.png.capacity() as u64 + FRAME_METADATA_BYTES); + assert_eq!(host.admitted_bytes(), frame.png.capacity() as u64 + FRAME_METADATA_BYTES + fixed_request_metadata_bytes()); for _ in 0..3 { let current = job.status().unwrap(); assert_eq!(current.frame.unwrap().png_sha256, frame.info.png_sha256); @@ -481,6 +639,8 @@ fn cancellation_during_png_hashing_and_host_disposal_cannot_publish_a_frame() { } assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); assert!(job.frame().unwrap().is_none()); + assert_eq!(budget.used.load(Ordering::Acquire), fixed_request_metadata_bytes()); + drop(job); assert_eq!(budget.used.load(Ordering::Acquire), 0); } } @@ -496,25 +656,72 @@ fn a_cancel_after_the_last_digest_chunk_still_wins_the_publication_lock() { assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); assert!(job.frame().unwrap().is_none()); drop(running); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); assert_eq!(host.admitted_bytes(), 0); } +#[test] +fn png_and_exr_reuse_one_sha_state_without_mixing_chunk_boundaries() { + let png: Vec = (0..PNG_HASH_CHUNK_BYTES + 7).map(|i| (i % 251) as u8).collect(); + let exr: Vec = (0..PNG_HASH_CHUNK_BYTES * 2 + 19).map(|i| (i % 239) as u8).collect(); + let mut pending = PendingPng::new(png.clone()); + pending.exr = Some(exr.clone()); + let cancel = CancelToken::default(); + assert!(!pending.step(1, &cancel).unwrap()); + assert!(pending.png_digest.is_none()); + assert!(!pending.step(1, &cancel).unwrap()); + assert_eq!(pending.png_digest.as_ref().unwrap(), &Sha256::digest(&png)); + assert_eq!(pending.exr_hashed, 0); + while !pending.step(1, &cancel).unwrap() {} + assert_eq!(pending.digest.finalize(), Sha256::digest(&exr)); + let metadata = std::mem::size_of::() + + std::mem::size_of::() + + std::mem::size_of::() + + PREPARED_PROOF_HEADER_BYTES + + 64 + + 2 * crate::MAX_RENDER_ID_BYTES + + 32; + assert!(metadata <= FRAME_METADATA_BYTES as usize); + eprintln!( + "fixed completion metadata: Running {}, final {}, preview {}, combined {metadata}/{}", + std::mem::size_of::(), + std::mem::size_of::(), + std::mem::size_of::(), + FRAME_METADATA_BYTES + ); +} + #[test] fn png_digest_metadata_fits_the_existing_allowance_without_changing_admission() { // Fixed digest/offset state and the completed frame (including its bounded // hex string and backend/executor IDs) fit the existing 1024-byte allowance. assert!(std::mem::size_of::() <= 512); - assert!( - std::mem::size_of::() + std::mem::size_of::() + 64 + 2 * crate::MAX_RENDER_ID_BYTES + 32 - <= FRAME_METADATA_BYTES as usize - ); + for linear_master in [false, true] { + let metadata = std::mem::size_of::() + + std::mem::size_of::() + + PREPARED_PROOF_HEADER_BYTES + + 64 + + u32::from(linear_master) as usize * 64 + + 2 * crate::MAX_RENDER_ID_BYTES + + 32; + assert!( + metadata <= FRAME_METADATA_BYTES as usize, + "PNG/EXR completion metadata {metadata} exceeds {} (Running {}, Frame {}, linear_master {linear_master})", + FRAME_METADATA_BYTES, + std::mem::size_of::(), + std::mem::size_of::() + ); + } let host = CpuHost::cooperative(); - let expected = admit(&empty(), &request()).unwrap().estimated_total_bytes; + let expected = admit(&empty(), &request()).unwrap().estimated_total_bytes + fixed_request_metadata_bytes(); let job = host.submit(id(70, 1), 1, empty(), request()).unwrap(); assert_eq!(host.admitted_bytes(), expected); assert!(job.status().unwrap().frame.is_none()); job.cancel().unwrap(); drain(&host); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); assert_eq!(host.admitted_bytes(), 0); } @@ -582,7 +789,7 @@ fn a_completed_task_is_dropped_while_its_full_reservation_still_pays_for_it() { drain(&host); assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); // While the task (and its scratch) was being dropped, its whole charge was still held. - assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated); + assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated + fixed_request_metadata_bytes()); // Afterwards only the PNG's lease remains, and the frame keeps it. let frame = job.frame().unwrap().unwrap(); assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < estimated, "{}", host.admitted_bytes()); @@ -603,7 +810,9 @@ fn a_cancel_on_the_final_step_publishes_no_frame_and_drops_the_task() { drain(&host); assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); assert!(job.frame().unwrap().is_none()); - assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated, "the task went before its charge"); + assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated + fixed_request_metadata_bytes(), "the task went before its charge"); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); assert_eq!(host.admitted_bytes(), 0); } @@ -820,6 +1029,1456 @@ fn registered_large_pool_is_explicit_finite_and_accounted() { drop(lease); assert_eq!(host.admitted_bytes(), 0); } +/// A registered executor exercises the shared publication boundary without a device. +/// Each pass encodes a real, distinct PNG; no final is returned with a preview. +struct CheckpointExecutor; +struct CheckpointWork { + request: ImageRequest, + cancel: CancelToken, + samples: u32, + target: u32, + preview: Option, +} +impl ImageWork for CheckpointWork { + fn take_preview(&mut self) -> Option { + self.preview.take() + } + fn step(&mut self, _: usize) -> Result { + self.cancel.check()?; + self.samples += 1; + let rgba = vec![self.samples as u8; (self.request.width * self.request.height * 4) as usize]; + let mut task = super::super::PngTask::new(&self.request, rgba, self.cancel.clone())?; + let TaskPoll::Complete(png) = task.step(4)? else { + return Err(JobError::new(ErrorCode::Internal, "small checkpoint fixture did not encode")); + }; + if self.samples == self.target { + Ok(TaskPoll::Complete(png)) + } else { + self.preview = Some(super::super::ImageWorkPreview { png, samples_per_pixel: self.samples }); + Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: u64::from(self.samples), total: u64::from(self.target) })) + } + } +} +impl ImageExecutor for CheckpointExecutor { + fn preview_samples(&self, options: JobOptions) -> Option { + Some(options.samples) + } + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + admit(scene, request) + } + fn begin(&self, _: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result> { + Ok(Box::new(CheckpointWork { request, cancel, samples: 0, target: options.samples, preview: None })) + } +} + +/// A valid registered producer need not use the built-in dimension-based PNG bound. +struct BoundedCheckpointExecutor { + encoded_limit: usize, +} +struct BoundedCheckpointWork { + inner: CheckpointWork, + encoded_limit: usize, +} +impl BoundedCheckpointWork { + fn retain_png(&self, png: Vec) -> Vec { + assert!(png.len() <= self.encoded_limit); + let mut retained = Vec::with_capacity(self.encoded_limit); + retained.extend_from_slice(&png); + assert_eq!(retained.capacity(), self.encoded_limit); + retained + } +} +impl ImageWork for BoundedCheckpointWork { + fn take_preview(&mut self) -> Option { + self.inner.take_preview() + } + fn step(&mut self, units: usize) -> Result { + let poll = self.inner.step(units)?; + if let Some(mut preview) = self.inner.preview.take() { + preview.png = self.retain_png(preview.png); + self.inner.preview = Some(preview); + } + Ok(match poll { + TaskPoll::Complete(png) => TaskPoll::Complete(self.retain_png(png)), + pending => pending, + }) + } +} +impl ImageExecutor for BoundedCheckpointExecutor { + fn preview_samples(&self, options: JobOptions) -> Option { + Some(options.samples) + } + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + // Pay the complete built-in encoder envelope and the overlapping repack + // allocation independently of the custom retained-output bound. + let mut admission = admit(scene, request)?; + let repack_bytes = self.encoded_limit as u64 + 4096; + admission.preparation_bytes += repack_bytes; + admission.estimated_total_bytes += repack_bytes; + admission.encoded_limit = self.encoded_limit as u64; + Ok(admission) + } + fn begin(&self, _: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result> { + Ok(Box::new(BoundedCheckpointWork { + inner: CheckpointWork { request, cancel, samples: 0, target: options.samples, preview: None }, + encoded_limit: self.encoded_limit, + })) + } +} + +fn registered_checkpoint_encoded_bound(encoded_limit: usize) { + for cancel in [false, true] { + let host = ImageHost::cooperative_with(Arc::new(BoundedCheckpointExecutor { encoded_limit })); + let request = ImageRequest { width: 2, height: 2, ..request() }; + let options = JobOptions { samples: 5, ..Default::default() }; + let work_bytes = admit(&empty(), &request).unwrap().estimated_total_bytes + encoded_limit as u64 + 4096; + let slot_bytes = encoded_limit as u64 + FRAME_METADATA_BYTES; + let admission = host.admit(&empty(), &request, options).unwrap(); + assert_eq!(admission.encoded_limit, encoded_limit as u64); + assert_eq!(admission.estimated_total_bytes, work_bytes + 2 * slot_bytes + FRAME_METADATA_BYTES); + let job = host.submit_with_options(id(9023, 1), 57, empty(), request, options).unwrap(); + let admitted = host.admitted_bytes(); + let mut held = Vec::new(); + for samples in 1..=2 { + for _ in 0..8 { + host.pump(1).unwrap(); + let status = job.status().unwrap(); + assert_ne!(status.progress.phase, Phase::Failed, "custom encoded limit {encoded_limit}: {:?}", status.error); + if job.preview().unwrap().is_some_and(|preview| preview.info.samples_per_pixel == samples) { + break; + } + } + let preview = job.preview().unwrap().expect("an admitted custom PNG bound must publish its complete pass"); + assert_eq!(preview.info.samples_per_pixel, samples); + assert_eq!(preview.png.capacity(), encoded_limit); + assert_eq!(preview._reservation.bytes, slot_bytes); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + let decoded = image::load_from_memory(preview.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (2, 2)); + assert_eq!(decoded.as_raw(), &vec![samples as u8; 16]); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), admitted, "publication only transfers admitted credit"); + let running = host.0.running.lock().unwrap(); + let running = running.as_ref().unwrap(); + assert_eq!(running.reservation.as_ref().unwrap().bytes, work_bytes, "preview credits must not consume executor work"); + assert_eq!(running.checkpoints.as_ref().unwrap().slot_bytes, slot_bytes); + held.push(preview); + } + if cancel { + job.cancel().unwrap(); + } + drain(&host); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, if cancel { Phase::Cancelled } else { Phase::Completed }); + assert_eq!(status.preview_retention_skips, if cancel { 0 } else { 2 }); + assert!(job.preview().unwrap().is_none()); + assert!(job.work_released()); + let frame = job.frame().unwrap(); + if cancel { + assert!(frame.is_none()); + } else { + let frame = frame.as_ref().unwrap(); + assert_eq!(frame.png.capacity(), encoded_limit); + assert_eq!(frame._reservation.bytes, slot_bytes); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().as_raw(), &vec![5; 16]); + } + for (index, preview) in held.iter().enumerate() { + assert_eq!(preview.info.samples_per_pixel as usize, index + 1); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + assert_eq!(image::load_from_memory(preview.png()).unwrap().to_rgba8().as_raw(), &vec![(index + 1) as u8; 16]); + } + drop(frame); + drop(job); + assert_eq!(host.admitted_bytes(), 2 * slot_bytes, "only externally pinned checkpoints retain admission"); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[test] +fn registered_executor_checkpoint_slots_follow_smaller_admitted_encoded_limit() { + registered_checkpoint_encoded_bound(4096); +} + +#[test] +fn registered_executor_checkpoint_slots_follow_larger_admitted_encoded_limit() { + registered_checkpoint_encoded_bound(131_072); +} + +#[test] +fn registered_executor_checkpoints_are_bounded_immutable_and_never_final() { + let host = ImageHost::cooperative_with(Arc::new(CheckpointExecutor)); + let request = ImageRequest { width: 2, height: 2, ..request() }; + let options = JobOptions { samples: 5, ..Default::default() }; + let base = admit(&empty(), &request).unwrap(); + let expected = base.estimated_total_bytes + 2 * (base.encoded_limit + FRAME_METADATA_BYTES) + FRAME_METADATA_BYTES; + assert_eq!(host.admit(&empty(), &request, options).unwrap().estimated_total_bytes, expected); + let job = host.submit_with_options(id(9021, 1), 55, empty(), request, options).unwrap(); + let mut held = Vec::new(); + for samples in 1..3 { + for _ in 0..8 { + host.pump(1).unwrap(); + if job.preview().unwrap().is_some_and(|preview| preview.info.samples_per_pixel == samples) { + break; + } + } + let preview = job.preview().unwrap().unwrap(); + assert_eq!(preview.info.samples_per_pixel, samples); + assert_eq!(preview.info.frame.job, job.id()); + assert_eq!(preview.info.frame.scene_generation, 55); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + assert!(job.frame().unwrap().is_none()); + held.push(preview); + } + while host.pump(1).unwrap() {} + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().preview_retention_skips, 2); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, job.id()); + for snapshot in &held { + assert_ne!(snapshot.png(), frame.png()); + assert_eq!(snapshot.info.frame.png_sha256, format!("{:x}", Sha256::digest(snapshot.png()))); + } + drop(frame); + drop(job); + assert!(host.admitted_bytes() > 0); + drop(held); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cancelling_registered_checkpoint_work_preserves_held_snapshot_without_final() { + let host = ImageHost::cooperative_with(Arc::new(CheckpointExecutor)); + let job = host + .submit_with_options( + id(9022, 1), + 56, + empty(), + ImageRequest { width: 2, height: 2, ..request() }, + JobOptions { samples: 5, ..Default::default() }, + ) + .unwrap(); + while job.preview().unwrap().is_none() { + host.pump(1).unwrap(); + } + let held = job.preview().unwrap().unwrap(); + job.cancel().unwrap(); + while host.pump(1).unwrap() {} + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(held.info.samples_per_pixel, 1); + drop(job); + assert_eq!(host.admitted_bytes(), held._reservation.bytes); + drop(held); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cancellation_phase_precedes_the_actual_work_release_barrier() { + let (host, job, mut running, _) = pending_digest_fixture(); + assert!(!job.work_released()); + assert!(host.admitted_bytes() > 0); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(!job.work_released(), "terminal status cannot admit a competing near-pool-sized job yet"); + assert!(host.admitted_bytes() > 0, "the Running owner still holds its work reservation"); + drop(running); + assert!(job.work_released()); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn queued_cancellation_releases_only_when_its_capture_and_reservation_drop() { + let host = CpuHost::cooperative(); + let job = host.submit(id(9030, 1), 60, empty(), request()).unwrap(); + assert_eq!(job.cancel().unwrap().progress.phase, Phase::Cancelled); + assert!(!job.work_released()); + assert!(host.admitted_bytes() > 0); + assert!(!host.pump(1).unwrap()); + assert!(job.work_released()); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn completed_work_barrier_does_not_claim_external_final_images_are_free() { + let (host, job, mut running, _) = pending_digest_fixture(); + while running.advance(4096).unwrap() {} + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert!(!job.work_released()); + let frame = job.frame().unwrap().unwrap(); + drop(running); + assert!(job.work_released()); + assert!(host.admitted_bytes() > 0, "completed images have their own retained leases"); + drop(job); + assert!(host.admitted_bytes() > 0); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn host_shutdown_releases_both_queued_and_active_work_before_signalling() { + let (host, active, running, _) = pending_digest_fixture(); + *host.0.running.lock().unwrap() = Some(running); + let queued = host.submit(id(9031, 1), 61, empty(), request()).unwrap(); + assert!(!active.work_released()); + assert!(!queued.work_released()); + let budget = host.0.shared.budget.clone(); + drop(host); + assert!(active.work_released()); + assert!(queued.work_released()); + assert_eq!(budget.used.load(Ordering::Acquire), 2 * fixed_request_metadata_bytes()); + drop(active); + drop(queued); + assert_eq!(budget.used.load(Ordering::Acquire), 0); +} + +struct FailingBeginExecutor; +impl ImageExecutor for FailingBeginExecutor { + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + admit(scene, request) + } + fn begin(&self, _scene: ProductScene, _: ImageRequest, _: JobOptions, _: CancelToken) -> Result> { + Err(JobError::new(ErrorCode::InvalidScene, "original failing executor fixture")) + } +} + +#[test] +fn failed_begin_releases_captured_scene_and_reservation_before_signalling() { + let host = ImageHost::cooperative_with(Arc::new(FailingBeginExecutor)); + let mesh = Arc::new(Mesh { + positions: vec![solidcore_record::Vec3::ZERO, solidcore_record::Vec3::X, solidcore_record::Vec3::Y], + normals: vec![solidcore_record::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + ..Default::default() + }); + let captured = Arc::downgrade(&mesh); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "original capture".into(), + mesh, + color: [128; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + }; + let job = host.submit(id(9032, 1), 62, scene, request()).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert!(!job.work_released()); + assert!(captured.upgrade().is_some()); + assert!(Running::begin(work).is_none()); + assert!(captured.upgrade().is_none(), "the actual captured mesh must be released before the barrier"); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Failed); + assert_eq!(status.error.unwrap().message, "original failing executor fixture", "the fixture must reach executor begin"); + assert!(job.work_released()); + assert_eq!(host.admitted_bytes(), fixed_request_metadata_bytes()); + drop(job); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod cpu_output_masters { + use super::*; + use crate::job::{CpuProgressiveOptions, OutputOptions, RaytraceOptions}; + fn fixture(host: &CpuHost, serial: u64) -> (JobHandle, Running) { + let settings = OutputOptions { + linear_exr: true, + tone_map: crate::job::ToneMap::AcesFitted, + finishing: crate::job::finishing::Finishing { + bloom: Some(crate::job::bloom::Bloom { strength: 0.2, threshold: 0.0, radius: 1 }), + ..Default::default() + }, + ..Default::default() + }; + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 9 }), + output: Some(Box::new(settings)), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 2, + height: 2, + ..request() + }; + let job = host.submit(id(9040, serial), 63, empty(), request).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (job, running) + } + fn host() -> CpuHost { + ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + fn hold_checkpoints(job: &JobHandle, running: &mut Running) -> Vec> { + let mut held = Vec::new(); + for _ in 0..100_000 { + if let Some(preview) = job.preview().unwrap() + && held.last().is_none_or(|last: &Arc| last.info.frame_sequence != preview.info.frame_sequence) + { + held.push(preview); + } + if running.pending_png.as_ref().is_some_and(|png| png.exr.is_some()) { + return held; + } + assert!(running.advance(1).unwrap()); + } + panic!("small CPU master did not reach its final digest"); + } + #[test] + fn cpu_master_and_every_retained_preview_keep_exact_independent_leases() { + let host = host(); + let (job, mut running) = fixture(&host, 1); + let held = hold_checkpoints(&job, &mut running); + assert_eq!(held.len(), 2); + assert!(job.frame().unwrap().is_none()); + while running.advance(1).unwrap() {} + let frame = job.frame().unwrap().unwrap(); + let raw = frame.linear_exr().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert_eq!(frame.linear_master_info().unwrap().sha256, format!("{:x}", Sha256::digest(raw))); + assert_eq!(frame._reservation.bytes, frame.png.capacity() as u64 + frame.exr.as_ref().unwrap().0.capacity() as u64 + FRAME_METADATA_BYTES); + let preview_bytes: u64 = held.iter().map(|preview| preview._reservation.bytes).sum(); + let frame_bytes = frame._reservation.bytes; + drop(running); + assert!(job.work_released()); + drop(job); + assert_eq!(host.admitted_bytes(), frame_bytes + preview_bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), preview_bytes); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn cancelling_cpu_master_digest_preserves_previous_final_and_pinned_preview_ownership() { + let host = host(); + let (previous, mut previous_running) = fixture(&host, 1); + while previous_running.advance(1).unwrap() {} + drop(previous_running); + let final_frame = previous.frame().unwrap().unwrap(); + let previous_png = final_frame.png().to_vec(); + let previous_raw = final_frame.linear_exr().unwrap().to_vec(); + let (job, mut running) = fixture(&host, 2); + let held = hold_checkpoints(&job, &mut running); + assert!(job.frame().unwrap().is_none()); + job.cancel().unwrap(); + assert_eq!(running.advance(1).unwrap_err().code, ErrorCode::Cancelled); + drop(running); + assert!(job.work_released()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(final_frame.png(), previous_png); + assert_eq!(final_frame.linear_exr().unwrap(), previous_raw); + drop(job); + drop(previous); + let preview_bytes: u64 = held.iter().map(|preview| preview._reservation.bytes).sum(); + assert_eq!(host.admitted_bytes(), final_frame._reservation.bytes + preview_bytes); + drop(final_frame); + assert_eq!(host.admitted_bytes(), preview_bytes); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[test] +fn registered_punctual_diagnostics_survive_work_release_and_retained_status_handles() { + struct DiagnosticExecutor; + struct DiagnosticWork(ImageTask); + let counts = super::super::PunctualDiagnostics { near_source: 1_u64 << 33, radiance_limit: 7, shadow_offset_crossed: 11 }; + impl ImageWork for DiagnosticWork { + fn punctual_diagnostics(&self) -> Option { + Some(super::super::PunctualDiagnostics { near_source: 1_u64 << 33, radiance_limit: 7, shadow_offset_crossed: 11 }) + } + fn step(&mut self, units: usize) -> Result { + self.0.step(units) + } + } + impl ImageExecutor for DiagnosticExecutor { + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + admit(scene, request) + } + fn begin(&self, scene: ProductScene, request: ImageRequest, _: JobOptions, cancel: CancelToken) -> Result> { + Ok(Box::new(DiagnosticWork(ImageTask::new(scene, request, cancel)?))) + } + } + let host = CpuHost::cooperative_with(Arc::new(DiagnosticExecutor)); + let job = host.submit(id(9027, 1), 71, empty(), request()).unwrap(); + let retained = job.clone(); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().punctual_diagnostics, Some(counts)); + assert!(job.work_released()); + assert!(job.frame().unwrap().is_some()); + drop(job); + assert_eq!(retained.status().unwrap().punctual_diagnostics, Some(counts)); + drop(retained); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod cpu_adaptive_checkpoints { + use super::*; + use crate::job::{ + CpuProgressiveOptions, OutputOptions, RaytraceOptions, + adaptive::{AdaptiveSampling, PreviewStage}, + }; + #[test] + fn cpu_adaptive_bounded_snapshots_span_pilot_reset_and_production_without_lending_the_final_master() { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + width: 1, + height: 1, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 48, seed: 81 }), + adaptive: Some(Box::new(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })), + output: Some(Box::new(OutputOptions { linear_exr: true, ..Default::default() })), + lights: Some(Vec::new()), + ..Default::default() + }), + ..request() + }; + let request_bytes = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); + assert_eq!( + request_bytes, + (std::mem::size_of::() + std::mem::size_of::()) as u64 + fixed_request_metadata_bytes() + ); + let expected = admit(&empty(), &request).unwrap().estimated_total_bytes + request_bytes; + let job = host.submit(id(9120, 1), 91, empty(), request).unwrap(); + assert_eq!(host.admitted_bytes(), expected); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + assert_eq!(running.checkpoint_target, 64); + let credits = running.checkpoints.as_ref().unwrap(); + assert_eq!(credits.capacity, 2 * credits.slot_bytes + FRAME_METADATA_BYTES); + let mut held: Vec> = Vec::new(); + let mut saw_reset_production = false; + let mut published = Vec::new(); + for _ in 0..200_000 { + if let Some(png) = running.pending_png.as_ref() + && let Some(absolute) = png.preview_samples + { + assert!(job.frame().unwrap().is_none()); + if absolute == 17 { + drop(held.remove(0)); + } + let before = job.status().unwrap(); + assert!(running.advance(1).unwrap()); + let status = job.status().unwrap(); + let preview = job.preview().unwrap().expect("publication or retention keeps a complete pass available"); + if status.preview_retention_skips != before.preview_retention_skips { + assert!((3..=16).contains(&absolute), "only the two pinned pilot snapshots skip publication"); + assert_eq!(status.preview_retention_skips, before.preview_retention_skips + 1); + let retained = held.last().unwrap(); + assert_eq!(retained.info.samples_per_pixel, 2); + assert!(Arc::ptr_eq(&preview, retained), "a skipped pass keeps the pinned second publication"); + assert_eq!(serde_json::to_value(&preview.info).unwrap(), serde_json::to_value(&retained.info).unwrap()); + assert_eq!(serde_json::to_value(&status.preview).unwrap(), serde_json::to_value(&before.preview).unwrap()); + assert_eq!(serde_json::to_value(status.preview.as_ref().unwrap()).unwrap(), serde_json::to_value(&retained.info).unwrap()); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + } else { + let metadata = preview.info.adaptive.unwrap(); + assert_eq!(preview.info.samples_per_pixel, absolute); + assert_eq!(metadata.pilot_samples, 16); + assert_eq!((metadata.minimum_production_samples, metadata.maximum_production_samples), (16, 48)); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + if absolute <= 16 { + assert_eq!((metadata.stage, metadata.completed, metadata.target), (PreviewStage::Pilot, absolute, 16)); + } else { + assert_eq!((metadata.stage, metadata.completed, metadata.target), (PreviewStage::Production, absolute - 16, 48)); + saw_reset_production = true; + } + published.push(absolute); + if absolute <= 2 { + held.push(preview); + } + } + assert_eq!(host.admitted_bytes(), expected); + continue; + } + if !running.advance(1).unwrap() { + break; + } + } + assert!(saw_reset_production); + assert_eq!(&published[..2], &[1, 2]); + assert!(published.contains(&17) && published.contains(&63)); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.preview_retention_skips, 14); + assert!(job.preview().unwrap().is_none()); + let report = status.sampling.unwrap(); + assert_eq!((report.pilot_samples_per_pixel, report.minimum_production_samples, report.maximum_production_samples), (16, 16, 16)); + assert_eq!((report.production_samples, report.primary_path_evaluations, report.pixels_at_cap), (16, 32, 0)); + drop(running); + assert!(job.work_released()); + let frame = job.frame().unwrap().unwrap(); + assert!(frame.linear_exr().is_some()); + let retained = held.iter().map(|p| p._reservation.bytes).sum::(); + assert_eq!( + host.admitted_bytes(), + retained + frame._reservation.bytes + request_bytes, + "the original captured adaptive/output boxes retain their independent request lease" + ); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), retained); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn celestial_cancelled_capture_retains_only_exact_boxes_and_fixed_header_until_last_handle_drop() { + use super::super::{CpuPathOptions, CpuProgressiveOptions, CpuSky, RaytraceOptions, Sun}; + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let options = RaytraceOptions { + path: Some(CpuPathOptions { max_depth: 2 }), + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 81 }), + sun: Some(Box::new(Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.02, radiance: [3.0, 2.0, 1.0] })), + sky: Some(Box::new(CpuSky::default())), + ..Default::default() + }; + let fixed = ImageRequest::fixed_cpu_metadata_bytes(); + assert_eq!( + fixed, + (std::mem::size_of::>>() + + std::mem::size_of::>>() + + std::mem::size_of::>()) as u64 + ); + let captured = ImageRequest { integrator: Integrator::Raytrace, raytrace: Some(options.clone()), ..request() }; + assert_eq!(captured.retained_resource_metadata_bytes(), fixed); + let retained = options.retained_bytes().unwrap() + fixed; + let job = host.submit(id(9170, 1), 101, empty(), captured).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + job.cancel().unwrap(); + assert!(!job.work_released()); + drop(work); + assert!(job.work_released()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), retained, "fixed request headers cannot borrow a released Work or absent final-frame lease"); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, retained); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), retained); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + // Omitted boxes introduce no source buffer, but their actual inline header + // growth remains explicitly billed even for the embedded None variant. + let plain = request(); + assert!(plain.raytrace.is_none()); + assert_eq!(plain.retained_resource_metadata_bytes(), fixed); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod prepared_optical_submission { + use super::*; + use crate::job::{DielectricBoundary, DielectricOptions, RaytraceOptions}; + use solidcore_record::Vec3; + + fn host(limit: u64) -> CpuHost { + ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(limit), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + fn capture() -> (ProductScene, ImageRequest) { + let mesh = Arc::new(Mesh { + positions: (0..8) + .map(|i| Vec3::new(if i & 1 == 0 { -1.0 } else { 1.0 }, if i & 2 == 0 { -1.0 } else { 1.0 }, if i & 4 == 0 { 0.0 } else { 2.0 })) + .collect(), + triangles: vec![ + [0, 2, 3], + [0, 3, 1], + [4, 5, 7], + [4, 7, 6], + [0, 4, 6], + [0, 6, 2], + [1, 3, 7], + [1, 7, 5], + [0, 1, 5], + [0, 5, 4], + [2, 6, 7], + [2, 7, 3], + ], + ..Default::default() + }); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "captured box".into(), + mesh, + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + transmission: None, + }], + }; + let mut request = ImageRequest { integrator: Integrator::Raytrace, width: 1, height: 1, ..request() }; + request.camera.set_view(crate::StandardView::Top); + request.raytrace = Some(RaytraceOptions { + lights: Some(Vec::new()), + environment: Some(crate::job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + dielectrics: vec![DielectricOptions { + body_index: 0, + body_name: "captured box".into(), + boundary: DielectricBoundary::ClosedBox, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + shadow_transmission: false, + subsurface: None, + }], + ..Default::default() + }); + (scene, request) + } + + #[test] + fn prepared_optics_debit_once_and_transfer_work_and_retained_leases_without_enqueuing_early() { + let host = host(MEMORY_LIMIT); + let (scene, request) = capture(); + let source = Arc::downgrade(&scene.meshes[0].mesh); + let retained = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); + let prepared = host.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).unwrap(); + assert_eq!(prepared.proof.len(), 1); + assert!(prepared.options.is_none()); + assert!(host.0.shared.queue.lock().unwrap().is_empty(), "preparation has no job identity or queued work"); + let expected = prepared.admission().estimated_total_bytes + retained; + assert_eq!(host.admitted_bytes(), expected); + assert_eq!(prepared.reservation.bytes, prepared.admission().estimated_total_bytes); + assert_eq!(prepared.request_reservation.as_ref().unwrap().bytes, retained); + let job = host.submit_prepared(id(801, 1), 99, prepared).unwrap(); + assert_eq!(host.admitted_bytes(), expected, "enqueue moves rather than reserves credit"); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert_eq!(work.proof.len(), 1); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(1).unwrap() { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.id(), id(801, 1)); + drop(running); + assert!(source.upgrade().is_none(), "certified source drops with actual work"); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(host.admitted_bytes(), retained + frame._reservation.bytes); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), retained, "captured option names/capacities outlive frame eviction"); + let clone = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), retained); + drop(clone); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn preparation_drop_cancel_wrong_host_and_exact_pool_boundary_release_all_captures() { + let original = host(MEMORY_LIMIT); + let (scene, request) = capture(); + let prepared = original.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).unwrap(); + let required = original.admitted_bytes(); + drop(prepared); + assert_eq!(original.admitted_bytes(), 0); + for limit in [required - 1, required] { + let host = host(limit); + let (scene, request) = capture(); + let source = Arc::downgrade(&scene.meshes[0].mesh); + let result = host.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()); + assert_eq!(result.is_ok(), limit == required); + drop(result); + assert_eq!(host.admitted_bytes(), 0); + assert!(source.upgrade().is_none()); + } + let cancel = CancelToken::default(); + let (scene, request) = capture(); + let prepared = original.prepare_submission(scene, request, JobOptions::default(), None, cancel.clone()).unwrap(); + cancel.cancel(); + assert_eq!(original.submit_prepared(id(802, 1), 0, prepared).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(original.admitted_bytes(), 0); + let (scene, request) = capture(); + let prepared = original.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).unwrap(); + let other = host(MEMORY_LIMIT); + assert_eq!(other.submit_prepared(id(802, 2), 0, prepared).err().unwrap().code, ErrorCode::WrongOwner); + assert_eq!((original.admitted_bytes(), other.admitted_bytes()), (0, 0)); + assert!(original.0.shared.queue.lock().unwrap().is_empty()); + } + + #[test] + fn strict_host_and_preparation_keep_precise_geometry_refusal_without_pool_or_queue_leaks() { + let host = host(MEMORY_LIMIT); + let (mut scene, request) = capture(); + Arc::make_mut(&mut scene.meshes[0].mesh).positions[0].z += 0.125; + for error in [ + host.admit(&scene, &request, JobOptions::default()).err().unwrap(), + host.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).err().unwrap(), + ] { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("box face is not axis aligned"), "{}", error.message); + } + assert_eq!(host.admitted_bytes(), 0); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + } + #[test] + fn borrowed_enqueue_keeps_failed_capsule_credit_and_source_until_worker_retirement() { + let host = host(MEMORY_LIMIT); + let (scene, request) = capture(); + let source = Arc::downgrade(&scene.meshes[0].mesh); + let cancel = CancelToken::default(); + let prepared = host.prepare_submission(scene, request, JobOptions::default(), None, cancel.clone()).unwrap(); + let mut slot = Some(prepared); + let own_bytes = host.admitted_bytes(); + let first = host.submit(id(803, 1), 0, empty(), super::request()).unwrap(); + let second = host.submit(id(803, 2), 0, empty(), super::request()).unwrap(); + let queued_bytes = host.admitted_bytes() - own_bytes; + let error = host.try_submit_prepared(id(804, 1), 0, &mut slot).err().unwrap(); + assert_eq!(error.code, ErrorCode::QueueFull); + assert!(slot.is_some() && source.upgrade().is_some()); + assert_eq!(host.admitted_bytes(), own_bytes + queued_bytes); + // A racing cancellation does not make UI completion destroy queued + // captures. Background draining will reclaim their work later. + first.cancel().unwrap(); + assert_eq!(host.try_submit_prepared(id(804, 1), 0, &mut slot).err().unwrap().code, ErrorCode::QueueFull); + assert_eq!(host.0.shared.queue.lock().unwrap().len(), 2); + cancel.cancel(); + assert_eq!(host.try_submit_prepared(id(804, 1), 0, &mut slot).err().unwrap().code, ErrorCode::Cancelled); + assert!(slot.is_some()); + let other = self::host(MEMORY_LIMIT); + assert_eq!(other.try_submit_prepared(id(804, 1), 0, &mut slot).err().unwrap().code, ErrorCode::WrongOwner); + assert_eq!(host.admitted_bytes(), own_bytes + queued_bytes); + let (retire, receiver) = std::sync::mpsc::sync_channel(1); + let (ack, released) = std::sync::mpsc::sync_channel(1); + let worker = std::thread::spawn(move || { + drop(receiver.recv().unwrap()); + ack.send(()).unwrap(); + }); + retire.send(slot.take().unwrap()).unwrap(); + released.recv().unwrap(); + worker.join().unwrap(); + assert!(slot.is_none() && source.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), queued_bytes, "retirement ack follows actual owner/lease disposal"); + second.cancel().unwrap(); + drop(host.0.shared.queue.lock().unwrap().drain(..).collect::>()); + drop((first, second)); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn absent_optics_preserves_admission_and_has_no_proof_or_options_backing() { + let host = host(MEMORY_LIMIT); + for integrator in [Integrator::Raster, Integrator::Raytrace] { + let request = ImageRequest { integrator, ..super::request() }; + let expected = super::admit(&empty(), &request).unwrap(); + let fixed = request.retained_resource_metadata_bytes(); + let prepared = host.prepare_submission(empty(), request, JobOptions::default(), None, CancelToken::default()).unwrap(); + assert_eq!(serde_json::to_value(prepared.admission()).unwrap(), serde_json::to_value(expected).unwrap()); + assert_eq!((prepared.proof.len(), prepared.proof.capacity()), (0, 0)); + assert!(prepared.options.is_none()); + assert_eq!( + prepared.request_reservation.as_ref().unwrap().bytes, + fixed, + "None source paths still retain the exact CPU9 fixed header independently of Work" + ); + assert_eq!(host.admitted_bytes(), expected.estimated_total_bytes + fixed); + drop(prepared); + assert_eq!(host.admitted_bytes(), 0); + } + } + + fn general_capture() -> (ProductScene, ImageRequest) { + let (mut scene, mut request) = capture(); + // A rotated closed mesh is outside the legacy axis-aligned box subset. + for p in &mut Arc::make_mut(&mut scene.meshes[0].mesh).positions { + *p = Vec3::new((p.x + p.z) * std::f64::consts::FRAC_1_SQRT_2, p.y, (p.z - p.x) * std::f64::consts::FRAC_1_SQRT_2); + } + scene.bounds = scene.meshes[0].mesh.bounds(); + let options = request.raytrace.as_mut().unwrap(); + options.path = Some(crate::job::CpuPathOptions { max_depth: 16 }); + options.progressive = Some(crate::job::CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }); + options.shadows = true; + options.dielectrics[0].boundary = DielectricBoundary::ClosedMesh; + (scene, request) + } + + #[test] + fn general_glass_strict_admission_and_preparation_refuse_the_same_boundary_before_enqueue() { + let host = host(MEMORY_LIMIT); + for inward in [false, true] { + let (mut scene, request) = general_capture(); + let mesh = Arc::make_mut(&mut scene.meshes[0].mesh); + let expected = if inward { + for t in &mut mesh.triangles { + t.swap(1, 2); + } + "outward" + } else { + mesh.triangles.pop(); + "two oppositely" + }; + let source = Arc::downgrade(&scene.meshes[0].mesh); + let original_triangles = scene.meshes[0].mesh.triangles.clone(); + let original_request = serde_json::to_value(&request).unwrap(); + for error in [ + crate::raytrace::image::admit(&scene, &request, request.raytrace.as_ref().unwrap()).err().unwrap(), + super::admit(&scene, &request).err().unwrap(), + host.admit(&scene, &request, JobOptions::default()).err().unwrap(), + ] { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains(expected) || (!inward && error.message.contains("closed edges")), "{error}"); + assert_eq!(host.admitted_bytes(), 0); + } + assert_eq!(scene.meshes[0].mesh.triangles, original_triangles); + assert_eq!(serde_json::to_value(&request).unwrap(), original_request); + let error = host.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains(expected) || (!inward && error.message.contains("closed edges")), "{error}"); + assert!(source.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(host.0.shared.queue.lock().unwrap().is_empty(), "failed Check never creates a render job"); + } + } + + #[test] + fn general_glass_prepared_proof_moves_with_exact_source_and_releases_work_before_retained_metadata() { + let host = host(MEMORY_LIMIT); + let (scene, request) = general_capture(); + let source = Arc::downgrade(&scene.meshes[0].mesh); + let exact_mesh = Arc::as_ptr(&scene.meshes[0].mesh); + let original_request = serde_json::to_value(&request).unwrap(); + let retained = retained_request_bytes(&request).unwrap() + request.retained_resource_metadata_bytes(); + let prepared = host.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).unwrap(); + assert_eq!((prepared.proof.len(), prepared.proof.capacity()), (1, 1)); + assert_eq!(Arc::as_ptr(&prepared.scene.meshes[0].mesh), exact_mesh); + assert_eq!(serde_json::to_value(prepared.request()).unwrap(), original_request); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + let required = prepared.admission().estimated_total_bytes + retained; + assert_eq!(host.admitted_bytes(), required); + let job = host.submit_prepared(id(805, 1), 7, prepared).unwrap(); + assert_eq!(host.admitted_bytes(), required, "publication only transfers existing credit"); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert_eq!(Arc::as_ptr(&work.scene.meshes[0].mesh), exact_mesh); + assert_eq!(work.proof.len(), 1); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(1).unwrap() { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + drop(running); + assert!(source.upgrade().is_none()); + assert!(job.work_released()); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(host.admitted_bytes(), retained + frame._reservation.bytes); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), retained, "general proof and every certificate buffer belong to Work"); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn general_glass_proof_exact_pool_cancel_and_wrong_host_never_release_credit_before_ownership() { + let original = host(MEMORY_LIMIT); + let (scene, request) = general_capture(); + let prepared = original.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()).unwrap(); + let required = original.admitted_bytes(); + drop(prepared); + assert_eq!(original.admitted_bytes(), 0); + for limit in [required - 1, required] { + let host = host(limit); + let (scene, request) = general_capture(); + let source = Arc::downgrade(&scene.meshes[0].mesh); + let result = host.prepare_submission(scene, request, JobOptions::default(), None, CancelToken::default()); + assert_eq!(result.is_ok(), limit == required); + drop(result); + assert!(source.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), 0); + } + let other = host(MEMORY_LIMIT); + for cancel_after_preparation in [false, true] { + let (scene, request) = general_capture(); + let source = Arc::downgrade(&scene.meshes[0].mesh); + let cancel = CancelToken::default(); + let prepared = original.prepare_submission(scene, request, JobOptions::default(), None, cancel.clone()).unwrap(); + let mut slot = Some(prepared); + if cancel_after_preparation { + cancel.cancel(); + } + let result = if cancel_after_preparation { + original.try_submit_prepared(id(806, 1), 0, &mut slot) + } else { + other.try_submit_prepared(id(806, 2), 0, &mut slot) + }; + assert_eq!(result.err().unwrap().code, if cancel_after_preparation { ErrorCode::Cancelled } else { ErrorCode::WrongOwner }); + assert!(slot.is_some() && source.upgrade().is_some()); + assert_eq!(original.admitted_bytes(), required, "failed borrowed enqueue retains the exact certificate owner"); + assert_eq!(other.admitted_bytes(), 0); + drop(slot); + assert!(source.upgrade().is_none()); + assert_eq!(original.admitted_bytes(), 0); + } + } +} + +#[test] +fn independently_retained_metadata_never_borrows_work_credit_and_rejects_a_different_host_pool() { + let host = CpuHost::cooperative(); + let first = host.prepare_submission(empty(), request(), JobOptions::default(), None, CancelToken::default()).unwrap(); + let work = host.admitted_bytes(); + let lease = first.reserve_retained_metadata(257).unwrap(); + assert_eq!(lease.bytes(), 257); + assert_eq!(host.admitted_bytes(), work + 257); + drop(first); + assert_eq!(host.admitted_bytes(), 257, "independent backing survives actual Work capsule release"); + let second = + host.prepare_submission_with_metadata(empty(), request(), JobOptions::default(), None, CancelToken::default(), Some(&lease)).unwrap(); + assert_eq!(host.admitted_bytes(), work + 257, "existing retained credit is counted but not reserved twice"); + let other = CpuHost::cooperative(); + assert_eq!( + other + .prepare_submission_with_metadata(empty(), request(), JobOptions::default(), None, CancelToken::default(), Some(&lease)) + .err() + .unwrap() + .code, + ErrorCode::WrongOwner + ); + assert_eq!(other.admitted_bytes(), 0); + drop(second); + assert_eq!(host.admitted_bytes(), 257); + drop(lease); + assert_eq!(host.admitted_bytes(), 0); +} + +mod capture_credit { + use super::*; + + struct MetadataExecutor(Arc); + impl ImageExecutor for MetadataExecutor { + fn descriptor(&self) -> Result { + let mut descriptor = CpuExecutor.descriptor()?; + // Deliberately noncanonical order: resolution sorts both lists. + // The full raw descriptor still must remain exactly pinned. + descriptor.profiles[0].features.push(crate::RenderFeature::Hdri); + descriptor.profiles[0].formats.insert(0, RenderFormat::Exr); + let state = self.0.load(Ordering::Acquire); + descriptor.id = ExecutorId::new(if state == 1 { "changed-capture-map" } else { "capture-map" }).unwrap(); + if state == 3 { + descriptor.scratch.sample_bytes_per_pixel += 1; + } + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _options: JobOptions) -> Result { + let mut clean = request.clone(); + clean.textures = None; + let mut result = admit(scene, &clean)?; + if let Some(maps) = &request.textures { + result.estimated_total_bytes += maps.working_bytes(); + } + // Deliberately change layout metadata after the first pre-submit + // check, without changing executor identity or profile. + if self.0.load(Ordering::Acquire) == 2 { + self.0.store(3, Ordering::Release); + } + Ok(result) + } + fn begin(&self, _scene: ProductScene, _request: ImageRequest, _options: JobOptions, _cancel: CancelToken) -> Result> { + Err(JobError::new(ErrorCode::InvalidRequest, "controlled capture factory failure")) + } + } + fn registered(limit: u64, changed: Arc) -> ImageHost { + ImageHost(Arc::new(Owner { + executor: Some(Arc::new(MetadataExecutor(changed))), + shared: ImageHost::shared(limit), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + #[test] + fn capture_registered_credit_has_actual_host_cap_and_pins_descriptor_token_and_retained_context() { + let changed = Arc::new(AtomicU64::new(0)); + let host = registered(MEMORY_LIMIT, changed.clone()); + let cancel = CancelToken::default(); + let bytes = super::super::super::image::MAX_JOB_BYTES + 1; + let lease = host.reserve_capture(bytes, CaptureProfile::Registered, &cancel, None).unwrap(); + assert_eq!(host.admitted_bytes(), bytes, "registered capture must not inherit Compact's smaller CPU cap"); + drop(lease); + assert_eq!(host.admitted_bytes(), 0); + assert!( + matches!(host.reserve_capture(1,CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact),&cancel,None),Err(e) if e.code==ErrorCode::WrongOwner) + ); + let retained = RetainedMetadata(host.0.shared.budget.reserve(123).unwrap()); + let mut lease = host.reserve_capture(100, CaptureProfile::Registered, &cancel, Some(&retained)).unwrap(); + assert_eq!(host.admitted_bytes(), 223); + lease.try_extend(70, &cancel).unwrap(); + assert_eq!(lease.bytes(), 170); + assert_eq!(host.admitted_bytes(), 293); + let foreign = registered(MEMORY_LIMIT, Arc::new(AtomicU64::new(0))); + let foreign_retained = RetainedMetadata(foreign.0.shared.budget.reserve(123).unwrap()); + assert!(matches!(host.reserve_capture(1,CaptureProfile::Registered,&cancel,Some(&foreign_retained)),Err(e) if e.code==ErrorCode::WrongOwner)); + let other = CancelToken::default(); + assert_eq!(lease.try_extend(1, &other).unwrap_err().code, ErrorCode::WrongOwner); + assert_eq!(host.admitted_bytes(), 293); + changed.store(1, Ordering::Release); + assert_eq!(lease.try_extend(1, &cancel).unwrap_err().code, ErrorCode::HostUnavailable); + assert_eq!(host.admitted_bytes(), 293); + changed.store(0, Ordering::Release); + cancel.cancel(); + assert_eq!(lease.try_extend(1, &cancel).unwrap_err().code, ErrorCode::Cancelled); + drop(lease); + assert_eq!(host.admitted_bytes(), 123); + drop(retained); + assert_eq!(host.admitted_bytes(), 0); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn cpu(limit: u64) -> ImageHost { + ImageHost(Arc::new(Owner { + executor: None, + shared: ImageHost::shared(limit), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + fn mapped() -> (ProductScene, ImageRequest, Weak>) { + use crate::{ + job::{ + CpuProgressiveOptions, DirectionalLightOptions, OutputOptions, RaytraceOptions, + textures::{BaseColorMode, PlanarFrame, RuntimeTextures, TextureBinding, TextureMap}, + }, + surface::OpaqueSurface, + texture_input::MapRole, + }; + use image::ImageEncoder; + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image(&[128, 64, 32, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap(); + let map = TextureMap::new(bytes, MapRole::BaseColor).unwrap(); + let weak = map.source().encoded_weak(); + let binding = TextureBinding { + body_index: 0, + body_name: "Mapped receiver".into(), + frame: PlanarFrame { origin: [0.; 3], u: [1., 0., 0.], v: [0., 1., 0.] }, + base_color: Some(map), + normal: None, + roughness: None, + metallic: None, + base_color_mode: BaseColorMode::Replace, + flip_v: false, + normal_strength: 1.0, + }; + let maps = Arc::new(RuntimeTextures::new(vec![binding]).unwrap()); + let mesh = Mesh { + positions: vec![ + solidcore_record::Vec3::new(-10., -10., 0.), + solidcore_record::Vec3::new(10., -10., 0.), + solidcore_record::Vec3::new(10., 10., 0.), + solidcore_record::Vec3::new(-10., 10., 0.), + ], + normals: vec![solidcore_record::Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + let source = ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "Mapped receiver".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(solidcore_record::Vec3::new(1., 1., 1.), 0., 0.5, 1.).unwrap()), + transmission: None, + faces: Vec::new(), + }], + }; + let mut image = request(); + image.width = 2; + image.height = 2; + image.camera.distance = 4.; + image.camera.set_view(crate::StandardView::Top); + image.integrator = Integrator::Raytrace; + image.textures = Some(maps); + image.raytrace = Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 2, seed: 17 }), + lights: Some(vec![DirectionalLightOptions { direction: [0., 0., 1.], color: [1.; 3], intensity: std::f64::consts::PI }]), + shadows: false, + output: Some(Box::new(OutputOptions { linear_exr: true, ..Default::default() })), + ..Default::default() + }); + (source, image, weak) + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn capture_cpu_exact_cap_transfer_keeps_real_map_png_raw_and_releases_only_work_backing() { + let render = |capture_excess: Option| { + let (scene, image, weak) = mapped(); + let probe = cpu(MEMORY_LIMIT); + let admission = probe.admit(&scene, &image, JobOptions::default()).unwrap(); + let retained = retained_request_bytes(&image).unwrap() + image.retained_resource_metadata_bytes(); + let total = admission.estimated_total_bytes + retained; + drop(probe); + let extra = capture_excess.unwrap_or(0); + let host = cpu(total + extra + 123); + let plan = RetainedMetadata(host.0.shared.budget.reserve(123).unwrap()); + let cancel = CancelToken::default(); + let prepared = if capture_excess.is_some() { + let bytes = if extra == 0 { image.textures.as_ref().unwrap().captured_bytes().unwrap() } else { total + extra }; + let mut credit = host + .reserve_capture(bytes / 2, CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), &cancel, Some(&plan)) + .unwrap(); + credit.try_extend(bytes - bytes / 2, &cancel).unwrap(); + assert_eq!(host.admitted_bytes(), bytes + 123); + host.prepare_submission_with_capture(scene, image, JobOptions::default(), None, cancel, Some(&plan), credit).unwrap() + } else { + host.prepare_submission_with_metadata(scene, image, JobOptions::default(), None, cancel, Some(&plan)).unwrap() + }; + assert_eq!(prepared.admission().estimated_total_bytes, admission.estimated_total_bytes + extra); + assert_eq!(prepared.admission().preparation_bytes, admission.preparation_bytes + extra); + assert_eq!(host.admitted_bytes(), total + extra + 123, "exact pool leaves no room for a second combined reserve"); + let job = host.submit_prepared(id(9510, if capture_excess.is_some() { 2 } else { 1 }), 1, prepared).unwrap(); + assert!(job.0.request.textures.is_none(), "Record owns summary only, never captured map backing"); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + assert!(weak.upgrade().is_some(), "the actual CPU factory received the full captured map source"); + for _ in 0..200000 { + if !running.guarded_step(16384) { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + let png = frame.png().to_vec(); + let raw = frame.linear_exr().unwrap().to_vec(); + let pixels = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (2, 2)); + assert!( + pixels.pixels().all(|p| p[0] > p[1] && p[1] > p[2] && p[2] > 0 && p[3] == 255), + "the actual PNG must show the red>green>blue map; the unmapped receiver and sole source are achromatic" + ); + assert!(weak.upgrade().is_none(), "the completed CPU producer releases encoded maps before publishing a final image"); + drop(running); + assert!(job.work_released()); + assert!(weak.upgrade().is_none(), "observed final handle/frame cannot pin encoded map backing"); + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + retained + 123); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), retained + 123); + drop(job); + assert_eq!(host.admitted_bytes(), 123); + drop(plan); + assert_eq!(host.admitted_bytes(), 0); + (png, raw) + }; + let original = render(None); + assert_eq!(original, render(Some(0)), "new transfer must preserve actual CPU mapped PNG/raw bytes and sample stream"); + assert_eq!(original, render(Some(4096)), "retired capture scratch must not alter the actual mapped image or retained lease split"); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn capture_errors_drop_typed_resources_before_outer_credit_and_reject_context_changes() { + let (scene, image, weak) = mapped(); + let host = cpu(MEMORY_LIMIT); + let cancel = CancelToken::default(); + let bytes = image.textures.as_ref().unwrap().captured_bytes().unwrap(); + let retained = RetainedMetadata(host.0.shared.budget.reserve(123).unwrap()); + let mut credit = + host.reserve_capture(bytes, CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), &cancel, Some(&retained)).unwrap(); + // Observe the exact inner refusal boundary used by the consuming public + // wrapper: parameters have died, but the enclosing credit is still alive. + let result = host.prepare_submission_inner(scene, image, JobOptions::default(), None, cancel.clone(), None, Some(&mut credit)); + assert!(matches!(result,Err(e) if e.code==ErrorCode::WrongOwner)); + assert!(weak.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), bytes + 123); + drop(credit); + assert_eq!(host.admitted_bytes(), 123); + drop(retained); + assert_eq!(host.admitted_bytes(), 0); + let (scene, image, weak) = mapped(); + let cancel = CancelToken::default(); + let bytes = image.textures.as_ref().unwrap().captured_bytes().unwrap(); + let original = RetainedMetadata(host.0.shared.budget.reserve(123).unwrap()); + let same_sized = RetainedMetadata(host.0.shared.budget.reserve(123).unwrap()); + let mut credit = + host.reserve_capture(bytes, CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), &cancel, Some(&original)).unwrap(); + let error = + host.prepare_submission_inner(scene, image, JobOptions::default(), None, cancel, Some(&same_sized), Some(&mut credit)).err().unwrap(); + assert_eq!(error.code, ErrorCode::WrongOwner, "equal byte count cannot substitute a different retained Plan owner"); + assert!(weak.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), bytes + 246); + drop(credit); + drop(original); + drop(same_sized); + assert_eq!(host.admitted_bytes(), 0); + for variant in 0..3 { + let (scene, mut image, weak) = mapped(); + let cancel = CancelToken::default(); + let bytes = image.textures.as_ref().unwrap().captured_bytes().unwrap(); + let credit = host + .reserve_capture( + if variant == 2 { bytes - 1 } else { bytes }, + CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), + &cancel, + None, + ) + .unwrap(); + let other = cpu(MEMORY_LIMIT); + if variant == 1 { + image.raytrace.as_mut().unwrap().budget = super::super::super::CpuBudget::Studio; + } + let owner = if variant == 0 { &other } else { &host }; + let error = owner.prepare_submission_with_capture(scene, image, JobOptions::default(), None, cancel, None, credit).err().unwrap(); + assert_eq!(error.code, if variant == 2 { ErrorCode::LimitExceeded } else { ErrorCode::WrongOwner }); + assert!(weak.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert_eq!(other.admitted_bytes(), 0); + } + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn capture_extension_counts_independent_retained_owner_at_exact_cpu_profile_boundary() { + let host = cpu(MEMORY_LIMIT); + let cancel = CancelToken::default(); + let plan = RetainedMetadata(host.0.shared.budget.reserve(123).unwrap()); + let maximum = super::super::super::CpuBudget::Compact.limits().max_job_bytes; + let mut credit = + host.reserve_capture(maximum - 123, CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), &cancel, Some(&plan)).unwrap(); + assert_eq!(host.admitted_bytes(), maximum); + assert_eq!(credit.try_extend(1, &cancel).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), maximum); + drop(credit); + assert_eq!(host.admitted_bytes(), 123); + drop(plan); + assert_eq!(host.admitted_bytes(), 0); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn capture_pool_failure_and_cancelled_prepared_keep_credit_until_owned_backing_drops() { + let (scene, image, weak) = mapped(); + let host = cpu(MEMORY_LIMIT); + let options = JobOptions::default(); + let admission = host.admit(&scene, &image, options).unwrap(); + let total = admission.estimated_total_bytes + retained_request_bytes(&image).unwrap() + image.retained_resource_metadata_bytes(); + let busy = host.0.shared.budget.reserve(MEMORY_LIMIT - total + 1).unwrap(); + let cancel = CancelToken::default(); + let bytes = image.textures.as_ref().unwrap().captured_bytes().unwrap(); + let mut credit = host.reserve_capture(bytes, CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), &cancel, None).unwrap(); + let error = host.prepare_submission_inner(scene, image, options, None, cancel, None, Some(&mut credit)).err().unwrap(); + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(weak.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), busy.bytes + bytes); + drop(credit); + assert_eq!(host.admitted_bytes(), busy.bytes); + drop(busy); + assert_eq!(host.admitted_bytes(), 0); + let (scene, image, weak) = mapped(); + let cancel = CancelToken::default(); + let admission = host.admit(&scene, &image, options).unwrap(); + let bytes = admission.estimated_total_bytes + retained_request_bytes(&image).unwrap() + image.retained_resource_metadata_bytes() + 4096; + let credit = host.reserve_capture(bytes, CaptureProfile::CpuRaytrace(super::super::super::CpuBudget::Compact), &cancel, None).unwrap(); + let mut slot = Some(host.prepare_submission_with_capture(scene, image, options, None, cancel.clone(), None, credit).unwrap()); + assert_eq!(slot.as_ref().unwrap().admission().estimated_total_bytes, admission.estimated_total_bytes + 4096); + let held = host.admitted_bytes(); + assert_eq!(held, bytes); + cancel.cancel(); + assert_eq!(host.try_submit_prepared(id(9511, 1), 1, &mut slot).err().unwrap().code, ErrorCode::Cancelled); + assert!(slot.is_some() && weak.upgrade().is_some()); + assert_eq!(host.admitted_bytes(), held, "failed publication retains the full funded capsule"); + drop(slot); + assert!(weak.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn capture_rechecks_actual_registered_layout_after_admission_before_merging_credit() { + let (scene, mut image, weak) = mapped(); + image.integrator = Integrator::Raster; + image.raytrace = None; + let changed = Arc::new(AtomicU64::new(2)); + let host = registered(MEMORY_LIMIT, changed.clone()); + let cancel = CancelToken::default(); + let bytes = image.textures.as_ref().unwrap().captured_bytes().unwrap(); + let credit = host.reserve_capture(bytes, CaptureProfile::Registered, &cancel, None).unwrap(); + let error = host.prepare_submission_with_capture(scene, image, JobOptions::default(), None, cancel, None, credit).err().unwrap(); + assert_eq!(changed.load(Ordering::Acquire), 3); + assert_eq!(error.code, ErrorCode::HostUnavailable); + assert_eq!(error.message, "resolved capture executor metadata changed"); + assert!(weak.upgrade().is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + } + #[test] + fn capture_registered_factory_failure_releases_source_credit_and_preserves_only_record_summary() { + let (scene, mut image, weak) = mapped(); + image.integrator = Integrator::Raster; + image.raytrace = None; + let host = registered(MEMORY_LIMIT, Arc::new(AtomicU64::new(0))); + let cancel = CancelToken::default(); + let retained = image.retained_resource_metadata_bytes(); + let bytes = image.textures.as_ref().unwrap().captured_bytes().unwrap(); + let credit = host.reserve_capture(bytes, CaptureProfile::Registered, &cancel, None).unwrap(); + let prepared = host.prepare_submission_with_capture(scene, image, JobOptions::default(), None, cancel, None, credit).unwrap(); + let job = host.submit_prepared(id(9512, 1), 1, prepared).unwrap(); + assert!(job.0.request.textures.is_none()); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert!(Running::begin(work).is_none()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.work_released()); + assert!(weak.upgrade().is_none()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), retained); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] #[test] diff --git a/crates/render/src/job/image.rs b/crates/render/src/job/image.rs index a6841a543..0dcd1bcc6 100644 --- a/crates/render/src/job/image.rs +++ b/crates/render/src/job/image.rs @@ -17,6 +17,10 @@ pub const MAX_TRIANGLES: u64 = 262_144; pub const MAX_GEOMETRY_BYTES: u64 = 128 * 1024 * 1024; pub const MAX_JOB_BYTES: u64 = 384 * 1024 * 1024; pub const MAX_PIXEL_TESTS: u64 = 128_000_000; +// Existing source/task/host fixed preparation allowance. Cursor backing is +// charged separately; this value is unchanged by prepared submission metadata. +pub(crate) const PREPARATION_METADATA_BYTES: u64 = 262_144; + const MAX_STEP: usize = 16_384; const SS: usize = 2; @@ -53,6 +57,18 @@ fn add_bytes(sum: &mut u64, count: usize, size: usize, maximum: u64) -> Result<( /// counted even when another owner already holds them. Allocator and codec internals are estimates. /// Includes the CPU raster work estimate and its 384 MiB per-job check. pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result { + admit_inner(scene, request, true) +} + +/// Internal byte/header estimate, never a successful public preflight. A host +/// must finish the strict certificate under its reserved envelope before use. +pub(crate) fn admit_layout(scene: &ProductScene, request: &ImageRequest) -> Result { + admit_inner(scene, request, false) +} + +fn admit_inner(scene: &ProductScene, request: &ImageRequest, certify: bool) -> Result { + #[cfg(not(feature = "raytrace-cpu"))] + let _ = certify; if request.environment.is_some() || (request.textures.is_some() && request.integrator != super::Integrator::Raytrace) { return Err(JobError::new(ErrorCode::InvalidRequest, "captured GPU environments and raster textures require a registered image executor")); } @@ -72,7 +88,11 @@ pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result let defaults = super::RaytraceOptions::default(); let options = request.raytrace.as_ref().unwrap_or(&defaults); options.validate()?; - crate::raytrace::image::admit(scene, request, options) + if certify { + crate::raytrace::image::admit(scene, request, options) + } else { + crate::raytrace::image::admit_layout(scene, request, options) + } } #[cfg(not(feature = "raytrace-cpu"))] { @@ -114,11 +134,15 @@ fn admit_source(scene: &ProductScene, request: &ImageRequest, max_triangles: u64 #[cfg(feature = "raytrace-cpu")] pub(crate) fn admit_raytrace_source(scene: &ProductScene, request: &ImageRequest, budget: super::CpuBudget) -> Result { budget.validate_execution()?; - budget.validate_image(request.width, request.height, request.raytrace.as_ref().and_then(|o| o.progressive))?; + budget.validate_image( + request.width, + request.height, + request.raytrace.as_ref().map(super::RaytraceOptions::camera_sampling).transpose()?.flatten(), + )?; let source = admit_source_with_budget(scene, request, budget.limits().max_triangles, budget)?; let mut a = source.admission; a.pixel_scratch_bytes = source.raster_scratch_bytes; - a.preparation_bytes = 262_144; + a.preparation_bytes = PREPARATION_METADATA_BYTES; a.estimated_total_bytes = a .geometry_bytes .checked_add(a.pixel_scratch_bytes) @@ -257,7 +281,7 @@ fn admit_raster(source: Source) -> Result { .triangles .checked_mul(48) .and_then(|n| a.face_appearances.checked_mul(160).and_then(|f| n.checked_add(f))) - .and_then(|n| n.checked_add(source.bodies * 128 + 262_144)) + .and_then(|n| n.checked_add(source.bodies * 128 + PREPARATION_METADATA_BYTES)) .ok_or_else(|| limit("work list size overflow"))?; let total = a .geometry_bytes diff --git a/crates/render/src/job/lens.rs b/crates/render/src/job/lens.rs index b76753c3b..10b32b4eb 100644 --- a/crates/render/src/job/lens.rs +++ b/crates/render/src/job/lens.rs @@ -11,6 +11,26 @@ pub struct ThinLens { } impl ThinLens { + /// The shared physical camera domain used by both native ray-traced methods. + /// A zero-radius lens preserves pinhole/orthographic behavior exactly. + pub fn validate_camera(self, camera: &crate::Camera) -> Result<()> { + self.validate()?; + if self.aperture_radius_mm > 0.0 + && (!camera.is_valid() + || !(0.0..std::f64::consts::PI).contains(&camera.fov) + || camera.fov == 0.0 + || !camera.half_height().is_finite() + || camera.half_height() > 1e12 + || !(1e-6..=1e9).contains(&camera.distance) + || !(1e-6..=1e6).contains(&(camera.half_height() / camera.distance))) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "thin-lens depth of field requires a bounded perspective camera (distance >= 0.000001 mm and tan(fov/2) in 0.000001..1000000)", + )); + } + Ok(()) + } pub fn validate(self) -> Result<()> { if !self.aperture_radius_mm.is_finite() || !(0.0..=1e7).contains(&self.aperture_radius_mm) @@ -40,4 +60,24 @@ mod tests { assert!(ThinLens { aperture_radius_mm: 0.0, focus_distance_mm: 1.0 }.validate().is_ok()); assert!(serde_json::from_str::(r#"{"aperture_radius_mm":1,"focus_distance_mm":10,"f_stop":2}"#).is_err()); } + #[test] + fn active_lens_camera_domain_is_explicit_and_zero_aperture_stays_compatible() { + let active = ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 10.0 }; + let zero = ThinLens { aperture_radius_mm: 0.0, ..active }; + let mut camera = crate::Camera::default(); + assert!(active.validate_camera(&camera).is_err()); + zero.validate_camera(&camera).unwrap(); + camera.fov = 0.7; + active.validate_camera(&camera).unwrap(); + for fov in [f64::NAN, f64::INFINITY, -0.7, std::f64::consts::PI, 1e-12] { + assert!(active.validate_camera(&crate::Camera { fov, ..camera }).is_err()); + } + for distance in [1e-7, 1e9 + 1.0] { + assert!(active.validate_camera(&crate::Camera { distance, ..camera }).is_err()); + } + let fixed = super::super::RaytraceOptions { lens: Some(active), ..Default::default() }; + assert!(fixed.validate().is_err()); + super::super::RaytraceOptions { lens: Some(zero), ..fixed.clone() }.validate().unwrap(); + super::super::RaytraceOptions { progressive: Some(Default::default()), ..fixed }.validate().unwrap(); + } } diff --git a/crates/render/src/job/light_union_tests.rs b/crates/render/src/job/light_union_tests.rs index fd74259bd..f45d6d3dc 100644 --- a/crates/render/src/job/light_union_tests.rs +++ b/crates/render/src/job/light_union_tests.rs @@ -123,7 +123,7 @@ fn source_kind_boundaries_remain_independent_with_presets_and_full_rectangle_bud match kind { "directional" => { let lights = options.lights.as_mut().unwrap(); - lights.push(lights[0].clone()); + lights.push(lights[0]); } "punctual" => { let lights = options.punctual_lights.as_mut().unwrap(); diff --git a/crates/render/src/job/lighting.rs b/crates/render/src/job/lighting.rs index 61ca559d1..0eafc5377 100644 --- a/crates/render/src/job/lighting.rs +++ b/crates/render/src/job/lighting.rs @@ -1,6 +1,6 @@ //! Runtime rectangular emitters and constant environment radiance. Coordinates are //! world-space millimetres; radiance is linear RGB. Saved setups reuse these bounds. -use super::{ErrorCode, JobError, Result}; +use super::{DirectionalLightOptions, ErrorCode, JobError, Result}; use serde::{Deserialize, Serialize}; use solidcore_record::Vec3; use solidcraft_geom::prelude::*; @@ -137,16 +137,91 @@ impl<'de> Deserialize<'de> for AreaLights { } } +pub const MAX_DIRECTIONAL_LIGHTS: usize = 8; + +/// Copyable hard directional sources. The optional finite Sun shares the same +/// eight-source family limit, but keeps its separate angular-radiance contract. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DirectionalLights { + entries: [DirectionalLightOptions; MAX_DIRECTIONAL_LIGHTS], + len: usize, +} +impl Default for DirectionalLights { + fn default() -> Self { + Self { entries: [DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [0.0; 3], intensity: 0.0 }; MAX_DIRECTIONAL_LIGHTS], len: 0 } + } +} +impl DirectionalLights { + pub fn new(lights: &[DirectionalLightOptions]) -> Result { + if lights.len() > MAX_DIRECTIONAL_LIGHTS { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights including the Sun")); + } + let mut result = Self::default(); + for (slot, light) in result.entries.iter_mut().zip(lights) { + light.validate()?; + *slot = *light; + } + result.len = lights.len(); + Ok(result) + } + pub fn iter(&self) -> impl Iterator { + self.entries.iter().take(self.len) + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} +impl Serialize for DirectionalLights { + fn serialize(&self, serializer: S) -> std::result::Result { + serializer.collect_seq(self.iter()) + } +} +impl<'de> Deserialize<'de> for DirectionalLights { + fn deserialize>(deserializer: D) -> std::result::Result { + struct Visitor; + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = DirectionalLights; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("an array of at most eight hard directional lights") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut result = DirectionalLights::default(); + while let Some(light) = seq.next_element::()? { + let slot = result.entries.get_mut(result.len).ok_or_else(|| serde::de::Error::custom("at most eight directional lights"))?; + light.validate().map_err(serde::de::Error::custom)?; + *slot = light; + result.len += 1; + } + Ok(result) + } + } + deserializer.deserialize_seq(Visitor) + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct StudioLighting { pub sun: Option, + #[serde(skip_serializing_if = "DirectionalLights::is_empty")] + pub directional_lights: DirectionalLights, + #[serde(skip_serializing_if = "super::PunctualLights::is_empty")] + pub punctual_lights: super::PunctualLights, pub environment: [f64; 3], pub area_lights: AreaLights, } impl StudioLighting { pub fn validate(self) -> Result<()> { + if self.directional_lights.iter().count() + usize::from(self.sun.is_some()) > MAX_DIRECTIONAL_LIGHTS { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights including the Sun")); + } + for light in self.directional_lights.iter() { + light.validate()?; + } + for light in self.punctual_lights.iter() { + light.validate_gpu()?; + } if let Some(sun) = self.sun { sun.validate()?; } @@ -232,4 +307,32 @@ mod tests { previous = value; } } + #[test] + fn hard_directional_list_is_bounded_copyable_and_preserves_authored_values() { + fn is_copy() {} + is_copy::(); + let light = DirectionalLightOptions { direction: [f64::MIN_POSITIVE, 0.0, 0.0], color: [0.25, 0.5, 1.0], intensity: 0.0 }; + let list = DirectionalLights::new(&[light; 8]).unwrap(); + assert_eq!(list.iter().count(), 8); + assert_eq!(serde_json::from_value::(serde_json::to_value(list).unwrap()).unwrap(), list); + assert!(DirectionalLights::new(&[light; 9]).is_err()); + assert!(serde_json::from_value::(serde_json::json!(vec![light; 9])).is_err()); + for bad in [ + DirectionalLightOptions { direction: [0.0; 3], ..light }, + DirectionalLightOptions { color: [-0.1, 0.0, 0.0], ..light }, + DirectionalLightOptions { intensity: 64.01, ..light }, + ] { + assert!(DirectionalLights::new(&[bad]).is_err()); + } + let sun = Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.02, radiance: [1.0; 3] }; + assert!(StudioLighting { sun: Some(sun), directional_lights: list, ..Default::default() }.validate().is_err()); + assert!( + StudioLighting { sun: Some(sun), directional_lights: DirectionalLights::new(&[light; 7]).unwrap(), ..Default::default() } + .validate() + .is_ok() + ); + let legacy: StudioLighting = serde_json::from_str(r#"{"sun":null,"environment":[0.1,0.2,0.3],"area_lights":[]}"#).unwrap(); + assert!(legacy.directional_lights.is_empty()); + assert!(serde_json::to_value(legacy).unwrap().get("directional_lights").is_none()); + } } diff --git a/crates/render/src/job/linear_exr.rs b/crates/render/src/job/linear_exr.rs index e77a310be..e12160578 100644 --- a/crates/render/src/job/linear_exr.rs +++ b/crates/render/src/job/linear_exr.rs @@ -32,6 +32,28 @@ fn attribute(out: &mut Vec, name: &[u8], kind: &[u8], value: &[u8]) -> Resul } pub(super) fn header(width: u32, height: u32) -> Result> { + header_for(width, height, b"SolidCraft native GPU path") +} +#[cfg(feature = "raytrace-cpu")] +pub(super) fn cpu_header(width: u32, height: u32) -> Result> { + header_for(width, height, b"SolidCraft native CPU raytrace") +} +/// Accept only this writer's exact native profiles, never external EXR metadata. +pub(super) fn native_header(bytes: &[u8], width: u32, height: u32) -> Result> { + let gpu = header(width, height)?; + if bytes.starts_with(&gpu) { + return Ok(gpu); + } + #[cfg(feature = "raytrace-cpu")] + { + let cpu = cpu_header(width, height)?; + if bytes.starts_with(&cpu) { + return Ok(cpu); + } + } + Err(invalid("master is not a retained native FLOAT32 linear-sRGB/D65 profile")) +} +fn header_for(width: u32, height: u32, software: &[u8]) -> Result> { let mut out = Vec::new(); out.try_reserve_exact(4096).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "EXR header allocation failed"))?; out.extend_from_slice(&20_000_630_u32.to_le_bytes()); @@ -65,7 +87,7 @@ pub(super) fn header(width: u32, height: u32) -> Result> { chromaticities.extend_from_slice(&value.to_le_bytes()); } attribute(&mut out, b"chromaticities", b"chromaticities", &chromaticities)?; - attribute(&mut out, b"software", b"string", b"SolidCraft native GPU path")?; + attribute(&mut out, b"software", b"string", software)?; attribute(&mut out,b"comments",b"string",b"Raw scene-linear sRGB/D65; RGB coverage-premultiplied; before exposure, denoising, finishing, backdrop and tone mapping. Relative radiance, not calibrated SI units.")?; out.push(0); Ok(out) @@ -83,12 +105,20 @@ pub struct ExrTask { } impl ExrTask { pub fn new(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken) -> Result { + encoded_limit(width, height)?; + Self::with_header(width, height, pixels, cancel, header(width, height)?) + } + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn new_cpu(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken) -> Result { + encoded_limit(width, height)?; + Self::with_header(width, height, pixels, cancel, cpu_header(width, height)?) + } + fn with_header(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken, mut bytes: Vec) -> Result { let limit = encoded_limit(width, height)?; if pixels.len() as u64 != u64::from(width) * u64::from(height) { return Err(invalid("EXR pixel count differs from dimensions")); } cancel.check()?; - let mut bytes = header(width, height)?; let row_bytes = u64::from(width) * 16; let first = bytes.len() as u64 + u64::from(height) * 8; let total = first + u64::from(height) * (row_bytes + 8); diff --git a/crates/render/src/job/linear_exr_decode.rs b/crates/render/src/job/linear_exr_decode.rs index 27e72e09d..bcb5b261c 100644 --- a/crates/render/src/job/linear_exr_decode.rs +++ b/crates/render/src/job/linear_exr_decode.rs @@ -18,8 +18,8 @@ impl Decoder { pub(super) fn new(bytes: &[u8], width: u32, height: u32, cancel: &CancelToken) -> Result { cancel.check()?; let limit = super::linear_exr::encoded_limit(width, height)?; - let expected = super::linear_exr::header(width, height)?; - if bytes.len() as u64 > limit || !bytes.starts_with(&expected) { + let expected = super::linear_exr::native_header(bytes, width, height)?; + if bytes.len() as u64 > limit { return Err(invalid("master is not the retained native FLOAT32 linear-sRGB/D65 profile")); } let first = expected.len() + height as usize * 8; @@ -117,4 +117,19 @@ mod tests { assert!(decoder.step(&bytes, &cancel).is_err()); assert_eq!(decoder.rows(), 0); } + #[cfg(feature = "raytrace-cpu")] + #[test] + fn cpu_native_master_roundtrips_without_accepting_arbitrary_software_headers() { + let pixels = vec![[8.0, 0.25, 0.5, 0.75], [0.0, 0.0, 0.0, 0.0]]; + let mut task = super::super::linear_exr::ExrTask::new_cpu(2, 1, pixels.clone(), CancelToken::default()).unwrap(); + assert!(task.step(1).unwrap()); + let (bytes, _) = task.finish().unwrap(); + let mut decoder = Decoder::new(&bytes, 2, 1, &CancelToken::default()).unwrap(); + assert!(decoder.step(&bytes, &CancelToken::default()).unwrap()); + assert_eq!(decoder.finish().unwrap(), pixels); + let mut foreign = bytes; + let at = foreign.windows(b"SolidCraft native CPU raytrace".len()).position(|w| w == b"SolidCraft native CPU raytrace").unwrap(); + foreign[at] ^= 1; + assert!(Decoder::new(&foreign, 2, 1, &CancelToken::default()).is_err()); + } } diff --git a/crates/render/src/job/mod.rs b/crates/render/src/job/mod.rs index 58fa1d842..158219dd4 100644 --- a/crates/render/src/job/mod.rs +++ b/crates/render/src/job/mod.rs @@ -16,6 +16,10 @@ pub mod adaptive; pub mod aging; pub mod bloom; mod cpu_budget; +mod cpu_path; +mod cpu_sky; +#[cfg(feature = "raytrace-cpu")] +pub(crate) mod denoise; pub(crate) mod encoding; pub mod finishing; mod host; @@ -28,6 +32,8 @@ mod lighting; pub mod linear_exr; mod linear_exr_decode; pub mod looks; +#[cfg(feature = "raytrace-cpu")] +pub(crate) mod output; pub mod photographic; mod png; pub mod presentation; @@ -39,18 +45,21 @@ pub mod textures; pub mod volume; pub use cpu_budget::{CpuBudget, CpuBudgetLimits, MAX_CPU_BODIES, MAX_CPU_SAMPLES_PER_PIXEL, MAX_CPU_TRIANGLES, MAX_CPU_WORK, NATIVE_CPU_POOL_BYTES}; +pub use cpu_path::CpuPathOptions; +pub use cpu_sky::CpuSky; #[cfg(feature = "raytrace-cpu")] pub(crate) use host::FRAME_METADATA_BYTES; pub(crate) use host::Reservation; pub use host::{ - CpuHost, HostKind, ImageHost, JobEnvironmentInfo, JobHandle, JobStatus, LinearAlphaConvention, LinearColourEncoding, LinearMasterInfo, - PreviewInfo, RenderFrame, RenderPreview, + CaptureLease, CaptureProfile, CpuHost, HostKind, ImageHost, JobEnvironmentInfo, JobHandle, JobStatus, LinearAlphaConvention, + LinearColourEncoding, LinearMasterInfo, PreparedSubmission, PreviewInfo, RenderFrame, RenderPreview, RetainedMetadata, }; pub use image::{Admission, ImageTask, TaskPoll, admit, admit_geometry, admit_geometry_with_limits}; pub use lens::ThinLens; -pub use lighting::{AreaLight, AreaLights, MAX_AREA_LIGHTS, StudioLighting, Sun, ToneMap}; +pub use lighting::{AreaLight, AreaLights, DirectionalLights, MAX_AREA_LIGHTS, MAX_DIRECTIONAL_LIGHTS, StudioLighting, Sun, ToneMap}; pub use png::PngTask; -pub use punctual::{PunctualDiagnostics, PunctualLightOptions, SpotConeOptions}; +pub use presentation::OutputOptions; +pub use punctual::{MAX_PUNCTUAL_LIGHTS, MIN_GPU_SPOT_COSINE_GAP, PunctualDiagnostics, PunctualLightOptions, PunctualLights, SpotConeOptions}; /// Native path-tracing ceilings, further restricted by the actual device. /// Kept in the device-independent layer so saved intent and UI agree with execution. @@ -115,6 +124,46 @@ impl Default for JobOptions { } impl JobOptions { + /// Equality alone equates -0 and +0. Captured native option bits must survive + /// work release, so the allocation-free sentinel also checks default-zero fields. + pub fn is_structural_default(&self) -> bool { + let photo = self.finishing.photographic; + *self == Self::default() + && [ + self.exposure_ev, + self.finishing.vignette, + photo.flare.strength, + photo.chromatic_pixels, + photo.radial_distortion, + photo.soft_focus, + photo.sharpening, + photo.grain, + ] + .iter() + .all(|value| value.to_bits() == 0) + } + + /// Fixed native options survive work release through job/status handles. + /// Only structural defaults use the allocation-free representation: authored + /// Some(identity) lighting/effects remain captured and independently prepaid. + pub fn retained_bytes(&self) -> Result { + self.validate()?; + if self.is_structural_default() { + return Ok(0); + } + // The type contains only bounded inline values. The caller adds this + // exact allocation to the existing retained-request/job/host pool caps. + Ok(std::mem::size_of::() as u64) + } + + /// Absolute complete-pass target, including independent pilots when adaptive. + /// This is not a claim that every adaptive production pixel takes every pass. + pub fn preview_target(self) -> Result { + self.validate()?; + self.samples + .checked_add(self.adaptive.map_or(0, |adaptive| adaptive.pilot_samples)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "sampling pass target overflow")) + } pub fn validate(&self) -> Result<()> { self.aging.validate()?; if let Some(volume) = self.volume { @@ -159,8 +208,27 @@ impl JobOptions { } } +/// Provisional PNG from a complete pass, moved to the host for bounded publication. +/// It never enters the final-image or linear-master slot. +pub struct ImageWorkPreview { + pub png: Vec, + /// Uniform SPP, or the absolute pilot+production iteration for adaptive work. + /// The host publishes phase metadata so display clients never label it uniform SPP. + pub samples_per_pixel: u32, +} + /// One bounded quantum of image work. Implementations check cancellation between quanta. pub trait ImageWork: Send { + /// Cumulative omissions seen through the most recent complete image pass. + /// Adaptive jobs include pilot paths and every production Fresnel stratum. + fn punctual_diagnostics(&self) -> Option { + None + } + + /// Called after each step. The host hashes and publishes this separately from final output. + fn take_preview(&mut self) -> Option { + None + } fn sampling_report(&self) -> Option { None } @@ -180,6 +248,14 @@ 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 { + /// 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 { + None + } + fn preview_unavailable_reason(&self, _options: JobOptions) -> Option<&'static str> { + None + } fn supports_aging(&self) -> bool { false } @@ -384,7 +460,7 @@ impl ReflectionOptions { } /// Linear-light runtime inputs. These are never design settings or GPU presets. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct DirectionalLightOptions { pub direction: [f64; 3], @@ -392,6 +468,22 @@ pub struct DirectionalLightOptions { pub intensity: f64, } +impl DirectionalLightOptions { + /// Direction points towards the source. Intensity is a relative incident-light + /// scale, as in the CPU direct-light contract; this is not a finite Sun disk. + pub fn validate(&self) -> Result<()> { + let direction_valid = self.direction.iter().all(|n| n.is_finite() && n.abs() <= 1e9) && self.direction.iter().any(|n| *n != 0.0); + if !direction_valid + || !self.color.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) + || !self.intensity.is_finite() + || !(0.0..=64.0).contains(&self.intensity) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded directional light")); + } + Ok(()) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum LightingPreset { @@ -556,11 +648,19 @@ fn bounded_emissions<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std:: pub enum DielectricBoundary { ThinSheet, ClosedBox, + /// Exact captured closed-mesh certification is available only in CPU Path. + ClosedMesh, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct DielectricOptions { + /// Homogeneous elastic scattering inside a certified closed Path medium. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subsurface: Option, + /// Straight thin-sheet light visibility. Closed refractive connections refuse. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub shadow_transmission: bool, pub body_index: usize, #[serde(deserialize_with = "bounded_dielectric_body_name")] pub body_name: String, @@ -656,16 +756,65 @@ impl CpuProgressiveOptions { budget.validate_image(width, height, Some(*self)) } - /// Nonfinal checkpoints whose PNG allocations may remain externally retained. + /// At most two immutable nonfinal snapshots are admitted, independent of SPP. #[cfg(feature = "raytrace-cpu")] - pub(crate) fn preview_count(&self) -> u32 { - if self.samples_per_pixel <= 1 { 0 } else { (self.samples_per_pixel - 1).ilog2() + 1 } + pub(crate) fn preview_slots(&self) -> u32 { + self.samples_per_pixel.saturating_sub(1).min(2) } } +/// One portable CPU camera envelope, shared by runtime, saved jobs and UI checks. +/// Pilots and maximum production both consume the existing profile sample caps. +pub fn cpu_camera_sampling( + progressive: Option, + adaptive: Option, + budget: CpuBudget, +) -> Result> { + let Some(adaptive) = adaptive else { return Ok(progressive) }; + let progressive = + progressive.ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "CPU adaptive sampling requires progressive camera sampling"))?; + adaptive.validate(progressive.samples_per_pixel)?; + let samples_per_pixel = progressive + .samples_per_pixel + .checked_add(adaptive.pilot_samples) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU adaptive pass target overflow"))?; + budget.validate_samples(samples_per_pixel)?; + Ok(Some(CpuProgressiveOptions { samples_per_pixel, ..progressive })) +} + +/// The CPU filter shares the bounded float4 presentation envelope; it never +/// enlarges a profile or implies that a linear EXR companion is requested. +pub fn validate_cpu_denoise_image(width: u32, height: u32) -> Result<()> { + linear_exr::encoded_limit(width, height) + .map(|_| ()) + .map_err(|_| JobError::new(ErrorCode::InvalidRequest, "CPU denoising requires 1..8192 sides and at most 16777216 pixels")) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct RaytraceOptions { + /// One bounded world-space participating medium, available with explicit Path. + #[serde(skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sun: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub sky: Option>, + /// Captured bounded aging parameters; saved stable targets are resolved by the engine. + #[serde(skip_serializing_if = "Option::is_none")] + pub aging: Option>, + /// Independent pilot allocation; the progressive sample count is the production cap. + #[serde(skip_serializing_if = "Option::is_none")] + pub adaptive: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// Optional CPU spatial output filtering; never changes the raw film or sampling. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub denoise: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub lens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub output: Option>, #[serde(skip_serializing_if = "CpuBudget::is_compact")] pub budget: CpuBudget, #[serde(skip_serializing_if = "Option::is_none")] @@ -701,6 +850,15 @@ pub struct RaytraceOptions { impl Default for RaytraceOptions { fn default() -> Self { Self { + volume: None, + sun: None, + sky: None, + aging: None, + adaptive: None, + denoise: false, + path: None, + lens: None, + output: None, budget: CpuBudget::Compact, progressive: None, punctual_lights: None, @@ -818,7 +976,52 @@ impl RaytraceOptions { } Ok(bytes) } + /// Complete camera-sample envelope: independent pilots plus production cap. + /// The ordinary path returns the original value without changing its limits. + pub fn camera_sampling(&self) -> Result> { + cpu_camera_sampling(self.progressive, self.adaptive.as_deref().copied(), self.budget) + } + pub fn preview_target(&self) -> Result { + Ok(self.camera_sampling()?.map_or(0, |options| options.samples_per_pixel)) + } + pub fn retained_adaptive_bytes(&self) -> Result { + if self.adaptive.is_some() { + self.camera_sampling()?; + Ok(std::mem::size_of::() as u64) + } else { + Ok(0) + } + } + /// One capacity calculation shared by host and engine preflight. + pub fn retained_aging_bytes(&self) -> Result { + if let Some(stack) = &self.aging { + stack.validate()?; + Ok(std::mem::size_of::() as u64) + } else { + Ok(0) + } + } + pub(crate) fn retained_volume_bytes(&self) -> Result { + if let Some(volume) = self.volume { + volume.validate()?; + } + // Inline intent has no extra heap owner, including authored zero. + // Every retained request pays its fixed field through metadata_bytes. + Ok(0) + } + pub(crate) fn retained_celestial_bytes(&self) -> Result { + if let Some(sun) = self.sun.as_deref() { + sun.validate()?; + } + if let Some(sky) = self.sky.as_deref() { + sky.validate()?; + } + let sun = if self.sun.is_some() { std::mem::size_of::() as u64 } else { 0 }; + let sky = if self.sky.is_some() { std::mem::size_of::() as u64 } else { 0 }; + Ok(sun + sky) + } + pub fn retained_bytes(&self) -> Result { self.validate()?; let limit = || JobError::new(ErrorCode::LimitExceeded, "raytrace request capacity overflow"); @@ -843,17 +1046,22 @@ impl RaytraceOptions { for target in self.anisotropic_faces.iter().flatten() { bytes = bytes.checked_add(target.body_name.capacity() as u64).ok_or_else(limit)?; } + bytes = bytes.checked_add(if self.output.is_some() { std::mem::size_of::() as u64 } else { 0 }).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_aging_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_adaptive_bytes()?).ok_or_else(limit)?; bytes = bytes.checked_add(self.retained_emission_bytes()?).ok_or_else(limit)?; bytes = bytes.checked_add(self.retained_surface_effect_bytes()?).ok_or_else(limit)?; bytes = bytes.checked_add(self.retained_dielectric_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_volume_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_celestial_bytes()?).ok_or_else(limit)?; Ok(bytes) } /// No environment NEE on selected reflectors; rough transport must be purely metallic. /// Rejecting every nonmetallic effective face prevents silently dropping its diffuse HDR. pub fn validate_environment_reflections(&self, scene: &crate::ProductScene) -> Result<()> { self.validate()?; - if self.environment.is_some() { - return Err(JobError::new(ErrorCode::InvalidRequest, "choose either the HDR input or constant secondary environment")); + if self.environment.is_some() || self.sky.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either the HDR input or constant/Sky environment")); } if let Some(reflections) = &self.reflections { for selector in &reflections.bodies { @@ -862,6 +1070,21 @@ impl RaytraceOptions { if bodies.next().is_some() { return Err(JobError::new(ErrorCode::InvalidRequest, "ambiguous environment reflection body")); } + if selector.mode == ReflectionMode::RoughSpecular + && self.aging.as_deref().is_some_and(|stack| { + stack.iter().any(|layer| { + layer.active() + && layer.target.is_none_or(|target| target.body_name.as_str() == body.name) + && layer.surface_class != aging::SurfaceClass::Dielectric + && layer.metallic != 1.0 + }) + }) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR rough reflection cannot discard the diffuse lobe introduced by CPU aging; keep metallic aging or use opaque path transport explicitly", + )); + } if selector.mode == ReflectionMode::RoughSpecular && (body.surface.is_none_or(|s| s.metallic() != 1.0) || body.faces.iter().any(|f| f.surface.is_none_or(|s| s.metallic() != 1.0))) { @@ -884,6 +1107,73 @@ impl RaytraceOptions { Ok(()) } pub fn validate(&self) -> Result<()> { + let _ = self.retained_volume_bytes()?; + 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")); + } + if self.denoise || !self.dielectrics.is_empty() { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU Atmosphere cannot combine with Glass, subsurface scattering or surface Denoise; turn off one explicitly", + )); + } + } + let _ = self.retained_celestial_bytes()?; + if (self.sun.is_some() || self.sky.is_some()) && self.path.is_none() { + return Err(JobError::new(ErrorCode::InvalidRequest, "finite Sun and gradient Sky require explicit CPU Indirect lighting")); + } + if self.sky.is_some() && self.environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either gradient Sky or constant CPU environment")); + } + if self.lights.as_ref().map_or(3, Vec::len) + usize::from(self.sun.is_some()) > MAX_DIRECTIONAL_LIGHTS { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight CPU directional lights including the finite Sun")); + } + if let Some(stack) = &self.aging { + stack.validate()?; + if stack.active() && self.anisotropic_faces.iter().any(Option::is_some) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU aging cannot replace the independently authored anisotropic roughness axes; preserve those values and choose an isotropic transport explicitly", + )); + } + } + + if self.adaptive.is_some() { + self.camera_sampling()?; + } + if let Some(path) = self.path { + path.validate()?; + cpu_path::validate_emitters(self.area_lights.as_deref().unwrap_or(&[]))?; + if self.progressive.is_none() || self.primary_samples != 1 { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU opaque path transport requires explicit progressive sampling with primary_samples: 1", + )); + } + if !self.shadows { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU opaque path transport requires traced shadows for matched light visibility", + )); + } + if self.reflections.is_some() || self.anisotropic_faces.iter().any(Option::is_some) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU path transport cannot combine selected reflection or certified anisotropy overrides; preserve them and choose the legacy transport explicitly", + )); + } + } + + if let Some(lens) = self.lens { + lens.validate()?; + if lens.aperture_radius_mm > 0.0 && self.progressive.is_none() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU depth of field requires progressive camera sampling")); + } + } + if let Some(output) = &self.output { + output.validate()?; + } if let Some(progressive) = self.progressive { self.budget.validate_samples(progressive.samples_per_pixel)?; if self.primary_samples != 1 || self.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty() && r.samples != 1) { @@ -892,15 +1182,6 @@ impl RaytraceOptions { "CPU progressive requires primary_samples: 1 and one reflection attempt per camera sample", )); } - if !self.dielectrics.is_empty() - || self.anisotropic_faces.iter().any(Option::is_some) - || self.area_lights.as_ref().is_some_and(|lights| !lights.is_empty()) - { - return Err(JobError::new( - ErrorCode::InvalidRequest, - "CPU progressive currently supports isotropic opaque surfaces and directional/point/spot lights; use fixed sampling for dielectric, anisotropic or area/LED inputs", - )); - } } if self.environment.is_some_and(|environment| { !environment.color.into_iter().all(|v| v.is_finite() && (0.0..=1.0).contains(&v)) @@ -913,6 +1194,33 @@ impl RaytraceOptions { return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight dielectric overrides")); } for (index, input) in self.dielectrics.iter().enumerate() { + 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 { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU subsurface scattering requires Indirect lighting and a certified closed medium", + )); + } + if scattering.active() && self.denoise { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU subsurface random walks have no surface-denoiser guides; disable denoising explicitly", + )); + } + } + if self.path.is_none() && (input.boundary == DielectricBoundary::ClosedMesh || input.shadow_transmission) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU general dielectric boundaries and thin transmitted shadows require explicit Indirect lighting", + )); + } + if input.boundary != DielectricBoundary::ThinSheet && input.shadow_transmission { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU closed dielectric light connections are unsupported; preserve the setting or explicitly turn off transmitted shadows", + )); + } if input.body_name.is_empty() || input.body_name.len() > 1024 || input.body_name.capacity() > 1024 @@ -921,7 +1229,7 @@ impl RaytraceOptions { || !input.absorption_per_mm.into_iter().all(|v| v.is_finite() && (0.0..=100.0).contains(&v)) || !input.thickness_mm.is_finite() || !(0.0..=10000.0).contains(&input.thickness_mm) - || (input.boundary == DielectricBoundary::ClosedBox && input.thickness_mm != 0.0) + || (input.boundary != DielectricBoundary::ThinSheet && input.thickness_mm != 0.0) || self.dielectrics.iter().take(index).any(|previous| previous.body_index == input.body_index) { return Err(JobError::new(ErrorCode::InvalidRequest, "invalid or duplicate dielectric override")); @@ -954,7 +1262,12 @@ impl RaytraceOptions { if self.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) { return Err(JobError::new(ErrorCode::InvalidRequest, "area_samples must be 1, 4, 16 or 64")); } - let directional_count = self.lights.as_ref().map_or_else(|| if self.preset == Some(LightingPreset::KeyRim) { 2 } else { 3 }, Vec::len); + let directional_count = self.lights.as_ref().map_or_else( + || { + if self.preset == Some(LightingPreset::KeyRim) { 2 } else { 3 } + }, + Vec::len, + ); if directional_count .checked_add(area_count) .and_then(|n| n.checked_add(self.punctual_lights.as_ref().map_or(0, Vec::len))) @@ -1036,14 +1349,7 @@ impl RaytraceOptions { return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights")); } for light in lights { - let direction_valid = light.direction.iter().all(|n| n.is_finite() && n.abs() <= 1e9) && light.direction.iter().any(|n| *n != 0.0); - if !direction_valid - || !light.color.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) - || !light.intensity.is_finite() - || !(0.0..=64.0).contains(&light.intensity) - { - return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded directional light")); - } + light.validate()?; } } Ok(()) @@ -1094,13 +1400,22 @@ impl ImageRequest { } } - /// Small GPU resource summaries survive work completion and keep their own host lease. + /// 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::>() + + std::mem::size_of::>>() + + std::mem::size_of::>>()) as u64 + } + /// Resource summaries and fixed CPU intent headers share one retained lease. pub fn retained_resource_metadata_bytes(&self) -> u64 { let environment = self .environment .as_ref() .map_or(0, |source| (std::mem::size_of::() + source.info().source_sha256.len()) as u64); - environment + if self.textures.is_some() { std::mem::size_of::() as u64 } else { 0 } + Self::fixed_cpu_metadata_bytes() + + environment + + if self.textures.is_some() { std::mem::size_of::() as u64 } else { 0 } } } @@ -1187,8 +1502,10 @@ mod runtime_request_roundtrip_tests { color: [1.0; 3], intensity: 1.0, }; - assert!(RaytraceOptions { progressive, area_lights: Some(vec![area]), ..Default::default() }.validate().is_err()); + RaytraceOptions { progressive, area_lights: Some(vec![area]), ..Default::default() }.validate().unwrap(); let dielectric = DielectricOptions { + shadow_transmission: false, + subsurface: None, body_index: 0, body_name: "Body".into(), boundary: DielectricBoundary::ThinSheet, @@ -1196,7 +1513,7 @@ mod runtime_request_roundtrip_tests { absorption_per_mm: [0.0; 3], thickness_mm: 1.0, }; - assert!(RaytraceOptions { progressive, dielectrics: vec![dielectric], ..Default::default() }.validate().is_err()); + RaytraceOptions { progressive, dielectrics: vec![dielectric], ..Default::default() }.validate().unwrap(); let face = AnisotropicFaceOptions { body_index: 0, body_name: "Body".into(), @@ -1206,7 +1523,7 @@ mod runtime_request_roundtrip_tests { roughness_x: 0.2, roughness_y: 0.6, }; - assert!(RaytraceOptions { progressive, anisotropic_faces: [Some(face), None], ..Default::default() }.validate().is_err()); + RaytraceOptions { progressive, anisotropic_faces: [Some(face), None], ..Default::default() }.validate().unwrap(); RaytraceOptions { progressive, area_lights: Some(Vec::new()), ..Default::default() }.validate().unwrap(); } } diff --git a/crates/render/src/job/output.rs b/crates/render/src/job/output.rs new file mode 100644 index 000000000..76e27b826 --- /dev/null +++ b/crates/render/src/job/output.rs @@ -0,0 +1,289 @@ +//! Bounded presentation of an owned scene-linear CPU pass. Transport and film remain separate. +//! The caller supplies the cumulative work debit; every mutating stage checks it first. +use super::denoise::{DenoiseTask, Guide}; +use super::{CancelToken, ErrorCode, JobError, Phase, Progress, Result, TaskPoll}; +use super::{bloom::BloomTask, encoding::PngEncoding, linear_exr::ExrTask, photographic::PhotographicTask, presentation::Presentation}; +use crate::film::adaptive::CountsPlane; + +fn invalid(message: &str) -> JobError { + JobError::new(ErrorCode::InvalidRequest, message) +} + +fn coverage_alpha(coverage: f32, samples: u16) -> Result { + if samples == 0 || !coverage.is_finite() || !(0.0..=1.0).contains(&coverage) { + return Err(invalid("invalid CPU display coverage count")); + } + // Every CPU pass has one known denominator. Even at u16::MAX, float32 + // quantisation is far below half a hit, so the original count is unique. + // Keep the raw FLOAT32 plane unchanged and round only the final byte from + // the integer ratio: 5/6 rounds to 213; float32 alpha alone gives 212. + let covered = (f64::from(coverage) * f64::from(samples)).round() as u32; + if covered > u32::from(samples) || (f64::from(covered) / f64::from(samples)) as f32 != coverage { + return Err(invalid("CPU display coverage disagrees with its sample count")); + } + let denominator = u32::from(samples); + u8::try_from((covered * 510 + denominator) / (denominator * 2)).map_err(|_| invalid("CPU display alpha exceeds one byte")) +} + +enum Stage { + Exr(ExrTask), + Denoise(DenoiseTask), + Bloom(BloomTask), + Display(usize), + Photographic(PhotographicTask), + Png, + Done, +} + +pub(crate) struct OutputTask { + width: u32, + height: u32, + encoded_limit: u64, + presentation: Presentation, + cancel: CancelToken, + stage: Option, + png: Option, + linear: Option>, + glow: Option>, + rgba: Vec, + preserve_display: bool, + denoise: bool, + coverage_samples: u16, + exr: Option>, +} +impl OutputTask { + #[allow(clippy::too_many_arguments)] + pub(crate) fn new( + width: u32, + height: u32, + encoded_limit: u64, + linear: Vec<[f32; 4]>, + rgba: Vec, + presentation: Presentation, + preserve_display: bool, + retain_exr: bool, + denoise: bool, + coverage_samples: u16, + cancel: CancelToken, + charge: &mut impl FnMut(u64) -> Result<()>, + ) -> Result { + presentation.validate()?; + cancel.check()?; + if denoise && preserve_display { + return Err(invalid("CPU denoising cannot preserve an unfiltered display buffer")); + } + if coverage_samples == 0 { + return Err(invalid("CPU output requires a complete coverage sample count")); + } + let count = u64::from(width) * u64::from(height); + super::linear_exr::encoded_limit(width, height)?; + if linear.len() as u64 != count || (preserve_display && rgba.len() as u64 != count * 4) || (!preserve_display && !rgba.is_empty()) { + return Err(invalid("CPU output storage does not match its complete pass")); + } + let mut task = Self { + width, + height, + encoded_limit, + presentation, + cancel, + stage: None, + png: None, + linear: None, + glow: None, + rgba, + preserve_display, + denoise, + coverage_samples, + exr: None, + }; + if retain_exr { + charge(u64::from(height))?; // bounded offset-table construction + task.stage = Some(Stage::Exr(ExrTask::new_cpu(width, height, linear, task.cancel.clone())?)); + } else { + task.prepare_display(linear, charge)?; + } + Ok(task) + } + fn pending(&self) -> TaskPoll { + TaskPoll::Pending(Progress { phase: Phase::Encoding, done: 0, total: u64::from(self.width) * u64::from(self.height) }) + } + fn start_png(&mut self, charge: &mut impl FnMut(u64) -> Result<()>) -> Result<()> { + self.cancel.check()?; + charge(1)?; + let size = usize::try_from(self.encoded_limit).map_err(|_| invalid("CPU PNG output exceeds address space"))?; + let mut output = Vec::new(); + output.try_reserve_exact(size).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "CPU presentation PNG allocation failed"))?; + if output.capacity() != size { + return Err(invalid("CPU presentation PNG capacity exceeds admission")); + } + self.png = Some(PngEncoding::with_output(self.width, self.height, self.encoded_limit, self.cancel.clone(), output)?); + self.stage = Some(Stage::Png); + Ok(()) + } + fn prepare_display(&mut self, linear: Vec<[f32; 4]>, charge: &mut impl FnMut(u64) -> Result<()>) -> Result<()> { + if self.denoise { + charge(1)?; // one fallible, prepaid colour scratch reservation + self.stage = Some(Stage::Denoise(DenoiseTask::new(self.width, self.height, linear)?)); + Ok(()) + } else { + self.prepare_finishing(linear, charge) + } + } + fn prepare_finishing(&mut self, linear: Vec<[f32; 4]>, charge: &mut impl FnMut(u64) -> Result<()>) -> Result<()> { + if self.preserve_display { + drop(linear); + return self.start_png(charge); + } + if let Some(bloom) = self.presentation.finishing.bloom.filter(|b| b.active()) { + charge(u64::from(self.width) * u64::from(self.height) * 2)?; + self.stage = Some(Stage::Bloom(BloomTask::new(self.width, self.height, linear, bloom, self.cancel.clone())?)); + } else { + self.linear = Some(linear); + self.stage = Some(Stage::Display(0)); + } + Ok(()) + } + /// One bounded row/column or at most 256 pixels. The CPU caller limits calls per quantum. + pub(crate) fn step( + &mut self, + guides: Option<&[Guide]>, + counts: Option<&CountsPlane>, + charge: &mut impl FnMut(u64) -> Result<()>, + ) -> Result { + self.cancel.check()?; + let stage = self.stage.take().ok_or_else(|| invalid("CPU output stage disappeared"))?; + match stage { + Stage::Exr(mut task) => { + charge(u64::from(self.width))?; + if task.step(1)? { + let (bytes, pixels) = task.finish()?; + charge(bytes.len() as u64)?; // host's later digest scan + self.exr = Some(bytes); + self.prepare_display(pixels, charge)?; + } else { + self.stage = Some(Stage::Exr(task)); + } + } + Stage::Denoise(mut task) => { + charge(task.next_pixels() as u64)?; + let guides = guides.ok_or_else(|| invalid("CPU output is missing its admitted geometry guides"))?; + if task.step(guides, &self.cancel)? { + self.prepare_finishing(task.finish()?, charge)?; + } else { + self.stage = Some(Stage::Denoise(task)); + } + } + Stage::Bloom(mut task) => { + charge(task.next_line_pixels())?; + if task.step(1)? { + let (pixels, glow) = task.finish()?; + self.linear = Some(pixels); + self.glow = Some(glow); + self.stage = Some(Stage::Display(0)); + } else { + self.stage = Some(Stage::Bloom(task)); + } + } + Stage::Display(at) => { + let count = self.width as usize * self.height as usize; + let end = at.saturating_add(256).min(count); + charge((end - at) as u64)?; + let length = count.checked_mul(4).ok_or_else(|| invalid("CPU display length overflow"))?; + if self.rgba.capacity() != length { + self.rgba + .try_reserve_exact(length.saturating_sub(self.rgba.len())) + .map_err(|_| JobError::new(ErrorCode::AllocationFailed, "CPU display allocation failed"))?; + if self.rgba.capacity() != length { + return Err(invalid("CPU display capacity exceeds admission")); + } + } + self.rgba.resize(end * 4, 0); + let input = self.linear.as_deref().and_then(|v| v.get(at..end)).ok_or_else(|| invalid("CPU linear display pixels disappeared"))?; + let output = self.rgba.get_mut(at * 4..end * 4).ok_or_else(|| invalid("CPU display pixels disappeared"))?; + let glow = self.glow.as_deref().and_then(|v| v.get(at..end)); + self.presentation.display(self.width, self.height)?.encode_bloom_at(input, output, &self.cancel, at, glow)?; + if self.presentation.transparent_background { + // Canonical fully clear pixels cannot carry lifted-black RGB into + // edge filtering. Raw linear coverage/radiance remains unchanged. + for (offset, (pixel, rgba)) in input.iter().zip(output.as_chunks_mut::<4>().0).enumerate() { + rgba[3] = match counts { + Some(counts) => { + let exact = counts.pixel(at + offset)?; + if exact.samples() == 0 || (f64::from(exact.covered()) / f64::from(exact.samples())) as f32 != pixel[3] { + return Err(invalid("CPU adaptive coverage disagrees with its complete count plane")); + } + exact.alpha8()? + } + None => coverage_alpha(pixel[3], self.coverage_samples)?, + }; + if rgba[3] == 0 { + *rgba = [0; 4]; + } + } + } + if end == count { + self.glow = None; + if self.presentation.finishing.photographic.active() { + let pixels = self.linear.take().ok_or_else(|| invalid("CPU photographic source disappeared"))?; + self.stage = Some(Stage::Photographic(PhotographicTask::new( + self.width, + self.height, + std::mem::take(&mut self.rgba), + pixels, + self.presentation.finishing.photographic, + self.cancel.clone(), + )?)); + } else { + self.linear = None; + self.start_png(charge)?; + } + } else { + self.stage = Some(Stage::Display(end)); + } + } + Stage::Photographic(mut task) => { + charge(task.next_step_pixels(256)?)?; + if task.step(256)? { + self.rgba = task.finish()?; + self.start_png(charge)?; + } else { + self.stage = Some(Stage::Photographic(task)); + } + } + Stage::Png => { + let task = self.png.as_mut().ok_or_else(|| invalid("CPU PNG encoder disappeared"))?; + charge(if task.row() < self.height as usize { u64::from(self.width) } else { 1 })?; + if let Some(png) = task.step(&self.rgba)? { + charge(png.len() as u64)?; // host's later digest scan + self.png = None; + self.stage = Some(Stage::Done); + return Ok(TaskPoll::Complete(png)); + } + self.stage = Some(Stage::Png); + } + Stage::Done => return Err(invalid("CPU output already completed")), + } + self.cancel.check()?; + Ok(self.pending()) + } + #[cfg(test)] + pub(crate) fn stage_name(&self) -> &'static str { + match &self.stage { + Some(Stage::Exr(_)) => "exr", + Some(Stage::Denoise(_)) => "denoise", + Some(Stage::Bloom(_)) => "bloom", + Some(Stage::Display(_)) => "display", + Some(Stage::Photographic(_)) => "photographic", + Some(Stage::Png) => "png", + Some(Stage::Done) => "done", + None => "empty", + } + } + pub(crate) fn finish(self) -> Result<(Vec, Option>)> { + self.cancel.check()?; + if !matches!(self.stage, Some(Stage::Done)) { + return Err(invalid("CPU output is incomplete")); + } + Ok((self.rgba, self.exr)) + } +} diff --git a/crates/render/src/job/photographic.rs b/crates/render/src/job/photographic.rs index 1309fe7b5..561b1d76e 100644 --- a/crates/render/src/job/photographic.rs +++ b/crates/render/src/job/photographic.rs @@ -128,6 +128,12 @@ impl PhotographicTask { pub fn step(&mut self, units: usize) -> Result { self.state.first_mut().ok_or_else(|| invalid("missing photographic state"))?.step(units) } + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn next_step_pixels(&self, units: usize) -> Result { + let state = self.state.first().ok_or_else(|| invalid("missing photographic state"))?; + let remaining = state.width * state.height - if state.ready { state.pixel } else { state.scanned }; + Ok(remaining.min(units.clamp(1, 16384)) as u64) + } pub fn progress(&self) -> (u64, u64) { self.state.first().map_or((0, 0), PhotographicState::progress) } diff --git a/crates/render/src/job/presentation.rs b/crates/render/src/job/presentation.rs index 67665bdc9..4b20e4fbb 100644 --- a/crates/render/src/job/presentation.rs +++ b/crates/render/src/job/presentation.rs @@ -4,6 +4,61 @@ use super::finishing::{Backdrop, Finishing}; use super::{CancelToken, ErrorCode, JobError, JobId, Result, ToneMap}; use serde::{Deserialize, Serialize}; +/// Portable output intent. Exposure and the background remain owned by the image request. +/// This contains presentation only; it never enables another transport integrator. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct OutputOptions { + pub tone_map: ToneMap, + pub finishing: Finishing, + pub backdrop: Option, + pub linear_exr: bool, +} +impl OutputOptions { + /// Identity display keeps the CPU producer's original f64 PNG calculation. + pub fn identity_display(&self) -> bool { + self.tone_map == ToneMap::Reinhard && self.finishing.is_identity() && self.backdrop.is_none() + } + pub fn validate(self) -> Result<()> { + self.finishing.validate()?; + if let Some(backdrop) = self.backdrop { + backdrop.validate()?; + } + Ok(()) + } + pub fn validate_image(self, width: u32, height: u32) -> Result<()> { + self.validate()?; + if !self.identity_display() || self.linear_exr { + super::linear_exr::encoded_limit(width, height)?; + } + Ok(()) + } + pub fn presentation(self, exposure_ev: f64, background: [u8; 3], transparent_background: bool) -> Presentation { + Presentation { exposure_ev, background, transparent_background, tone_map: self.tone_map, finishing: self.finishing, backdrop: self.backdrop } + } + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn required_bytes(self, width: u32, height: u32) -> Result { + self.validate_image(width, height)?; + if self.identity_display() && !self.linear_exr { + return Ok(0); + } + let count = + u64::from(width).checked_mul(u64::from(height)).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU output pixel overflow"))?; + // One owned float4 conversion, bloom ping/pong, photographic destination/state, + // and a final-only EXR companion. The existing producer covers RGBA and PNG output. + let bloom = self.finishing.bloom.map_or(Ok(0), |b| b.scratch_bytes(width, height))?; + let photographic = self.finishing.photographic.scratch_bytes(width, height)?; + let exr = if self.linear_exr { super::linear_exr::encoded_limit(width, height)? } else { 0 }; + count + .checked_mul(16) + .and_then(|n| n.checked_add(std::mem::size_of::() as u64)) + .and_then(|n| n.checked_add(bloom)) + .and_then(|n| n.checked_add(photographic)) + .and_then(|n| n.checked_add(exr)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU presentation storage overflow")) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Presentation { diff --git a/crates/render/src/job/punctual.rs b/crates/render/src/job/punctual.rs index 2f95a4e73..7c4b6dbd7 100644 --- a/crates/render/src/job/punctual.rs +++ b/crates/render/src/job/punctual.rs @@ -25,7 +25,98 @@ pub struct PunctualLightOptions { pub cone: Option, } +/// GPU spot feathers narrower than this cosine interval are explicitly refused. +/// This keeps f32 unit-vector/dot rounding small compared with the authored +/// feather instead of widening two distinct f64 bounds into the same f32 cone. +pub const MIN_GPU_SPOT_COSINE_GAP: f64 = 1.0 / 1024.0; +pub const MAX_PUNCTUAL_LIGHTS: usize = 8; + +/// Copyable bounded GPU source intent. CPU requests keep their existing DTO Vec. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PunctualLights { + entries: [PunctualLightOptions; MAX_PUNCTUAL_LIGHTS], + len: usize, +} +impl Default for PunctualLights { + fn default() -> Self { + Self { + entries: [PunctualLightOptions { + position_mm: [0.0; 3], + color: [0.0; 3], + intensity: 0.0, + reference_distance_mm: 1.0, + minimum_distance_mm: 0.001, + cone: None, + }; MAX_PUNCTUAL_LIGHTS], + len: 0, + } + } +} +impl PunctualLights { + pub fn new(lights: &[PunctualLightOptions]) -> Result { + if lights.len() > MAX_PUNCTUAL_LIGHTS { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight point and spot lights combined")); + } + let mut result = Self::default(); + for (slot, light) in result.entries.iter_mut().zip(lights) { + light.validate_gpu()?; + *slot = *light; + } + result.len = lights.len(); + Ok(result) + } + pub fn iter(&self) -> impl Iterator { + self.entries.iter().take(self.len) + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} +impl Serialize for PunctualLights { + fn serialize(&self, serializer: S) -> std::result::Result { + serializer.collect_seq(self.iter()) + } +} +impl<'de> Deserialize<'de> for PunctualLights { + fn deserialize>(deserializer: D) -> std::result::Result { + struct Lights; + impl<'de> serde::de::Visitor<'de> for Lights { + type Value = PunctualLights; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("at most eight GPU point and spot lights combined") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut lights = PunctualLights::default(); + while let Some(light) = seq.next_element::()? { + let slot = + lights.entries.get_mut(lights.len).ok_or_else(|| serde::de::Error::custom("at most eight GPU point and spot lights"))?; + light.validate_gpu().map_err(serde::de::Error::custom)?; + *slot = light; + lights.len += 1; + } + Ok(lights) + } + } + deserializer.deserialize_seq(Lights) + } +} + impl PunctualLightOptions { + /// GPU precision is a separate bounded domain; original CPU intent is never + /// clamped or rewritten when it cannot be represented by this consumer. + pub fn validate_gpu(&self) -> Result<()> { + self.validate()?; + if let Some(cone) = self.cone { + let gap = cone.inner_half_angle_radians.cos() - cone.outer_half_angle_radians.cos(); + if gap < MIN_GPU_SPOT_COSINE_GAP { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "GPU spot feather is too narrow for reliable precision; increase its angle range or use CPU", + )); + } + } + Ok(()) + } pub fn validate(&self) -> Result<()> { let invalid = || JobError::new(ErrorCode::InvalidRequest, "invalid bounded point/spot light"); if !self.position_mm.iter().all(|v| v.is_finite() && v.abs() <= 1e9) @@ -194,3 +285,51 @@ impl PunctualDiagnostics { self.near_source == 0 && self.radiance_limit == 0 && self.shadow_offset_crossed == 0 } } + +#[cfg(test)] +mod gpu_tests { + use super::*; + fn point() -> PunctualLightOptions { + PunctualLightOptions { + position_mm: [1e9, 0.0, 1.0], + color: [0.25, 0.5, 1.0], + intensity: 2.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + } + } + #[test] + fn gpu_punctual_copy_list_preserves_exact_authored_values_and_rejects_hostile_ninth() { + let mut spot = point(); + spot.cone = Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1e-200], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); + let list = PunctualLights::new(&[point(), spot, point(), spot, point(), spot, point(), spot]).unwrap(); + assert_eq!(list.iter().count(), 8); + assert_eq!(serde_json::from_value::(serde_json::to_value(list).unwrap()).unwrap(), list); + assert!(PunctualLights::new(&[point(); 9]).is_err()); + assert!(serde_json::from_value::(serde_json::json!(vec![point(); 9])).is_err()); + assert!(serde_json::to_value(super::super::StudioLighting::default()).unwrap().get("punctual_lights").is_none()); + for mut invalid in [point(); 3] { + invalid.minimum_distance_mm = 0.0; + assert!(PunctualLights::new(&[invalid]).is_err()); + } + } + #[test] + fn gpu_spot_precision_refusal_never_widens_or_rewrites_cpu_valid_cones() { + for (inner, outer) in [(0.2, 0.2000000001), (0.0, 0.0001), (1.0, 1.000000001)] { + let mut spot = point(); + spot.cone = Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: inner, outer_half_angle_radians: outer }); + let before = spot; + spot.validate().unwrap(); + assert!(spot.validate_gpu().unwrap_err().message.contains("precision")); + assert_eq!(spot, before); + } + let mut spot = point(); + spot.cone = Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); + assert!(spot.validate_gpu().is_ok()); + let cone = spot.cone.unwrap(); + let inner = cone.inner_half_angle_radians.cos() as f32; + let outer = cone.outer_half_angle_radians.cos() as f32; + assert!(inner > outer && f64::from(inner - outer) > MIN_GPU_SPOT_COSINE_GAP); + } +} diff --git a/crates/render/src/job/rt2_tests.rs b/crates/render/src/job/rt2_tests.rs index 3e46b3b0b..74395df04 100644 --- a/crates/render/src/job/rt2_tests.rs +++ b/crates/render/src/job/rt2_tests.rs @@ -76,41 +76,58 @@ fn rejected_raytrace_submission_leaves_existing_raster_reservation_intact() { assert_eq!(raster.cancel().unwrap().progress.phase, Phase::Cancelled); // Pump only to discard cancelled queued input; it must not produce a frame. assert!(!host.pump(1).unwrap()); - assert_eq!(host.admitted_bytes(), 0); + assert!(raster.work_released()); + assert_eq!(host.admitted_bytes(), ImageRequest::fixed_cpu_metadata_bytes(), "the live handle retains only its exact fixed request header"); assert!(raster.frame().unwrap().is_none()); + drop(raster); + assert_eq!(host.admitted_bytes(), 0, "the last handle releases that header without any frame"); } #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] #[test] fn native_integrators_share_one_host_and_retained_frame_budget() { - let mut host = CpuHost::for_platform().unwrap(); - let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; - let raster_id = JobId { session: 10, serial: 1, generation: 1 }; - let raytrace_id = JobId { session: 20, serial: 1, generation: 1 }; - let raster = host.submit(raster_id, 100, scene(), request(Integrator::Raster)).unwrap(); - let raytrace = host.submit(raytrace_id, 200, scene(), request(Integrator::Raytrace)).unwrap(); - // Deadlock watchdog only; there is no rendering-speed assertion. - for job in [&raster, &raytrace] { - assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + for frames_first in [false, true] { + let mut host = CpuHost::for_platform().unwrap(); + let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let raster_id = JobId { session: 10, serial: 1, generation: 1 }; + let raytrace_id = JobId { session: 20, serial: 1, generation: 1 }; + let raster = host.submit(raster_id, 100, scene(), request(Integrator::Raster)).unwrap(); + let raytrace = host.submit(raytrace_id, 200, scene(), request(Integrator::Raytrace)).unwrap(); + // Deadlock watchdog only; there is no rendering-speed assertion. + for job in [&raster, &raytrace] { + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + } + host.join_worker_for_test().unwrap(); + let raster_frame = raster.frame().unwrap().unwrap(); + let raytrace_frame = raytrace.frame().unwrap().unwrap(); + assert_eq!(raster_frame.info.job, raster_id); + assert_eq!(raytrace_frame.info.job, raytrace_id); + assert_eq!(raster_frame.info.scene_generation, 100); + assert_eq!(raytrace_frame.info.scene_generation, 200); + assert_eq!(raster_frame.info.executor.as_str(), "cpu-product"); + assert_eq!(raytrace_frame.info.executor.as_str(), "cpu-raytrace"); + let fixed = ImageRequest::fixed_cpu_metadata_bytes(); + let both = host.admitted_bytes(); + assert!(both > 2 * fixed); + if frames_first { + drop(raster_frame); + drop(raytrace_frame); + assert_eq!(host.admitted_bytes(), both, "held Records still own both final images and both fixed request headers"); + drop(raster); + assert!(host.admitted_bytes() > fixed && host.admitted_bytes() < both - fixed, "the remaining Record keeps its image and exact header"); + drop(raytrace); + } else { + drop(raster); + assert_eq!(host.admitted_bytes(), both - fixed); + drop(raytrace); + let frames = both - 2 * fixed; + assert_eq!(host.admitted_bytes(), frames, "external frames retain image leases, not the dropped Records' request headers"); + drop(raster_frame); + assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < frames); + drop(raytrace_frame); + } + assert_eq!(host.admitted_bytes(), 0); } - host.join_worker_for_test().unwrap(); - let raster_frame = raster.frame().unwrap().unwrap(); - let raytrace_frame = raytrace.frame().unwrap().unwrap(); - assert_eq!(raster_frame.info.job, raster_id); - assert_eq!(raytrace_frame.info.job, raytrace_id); - assert_eq!(raster_frame.info.scene_generation, 100); - assert_eq!(raytrace_frame.info.scene_generation, 200); - assert_eq!(raster_frame.info.executor.as_str(), "cpu-product"); - assert_eq!(raytrace_frame.info.executor.as_str(), "cpu-raytrace"); - let both = host.admitted_bytes(); - assert!(both > 0); - drop(raster); - drop(raytrace); - assert_eq!(host.admitted_bytes(), both, "external frames retain both leases"); - drop(raster_frame); - assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < both); - drop(raytrace_frame); - assert_eq!(host.admitted_bytes(), 0); } #[cfg(feature = "raytrace-cpu")] diff --git a/crates/render/src/job/textures.rs b/crates/render/src/job/textures.rs index e6187cb46..668c22772 100644 --- a/crates/render/src/job/textures.rs +++ b/crates/render/src/job/textures.rs @@ -3,6 +3,7 @@ pub(crate) mod cpu_cache; #[cfg(feature = "raytrace-cpu")] pub mod cpu_preparation; + use super::{CancelToken, ErrorCode, JobError, Result}; use crate::{ ProductScene, @@ -271,7 +272,8 @@ impl RuntimeTextures { pub fn summary(&self) -> TextureSummary { TextureSummary { bodies: self.bindings.len(), encoded_bytes: self.source_bytes, linear_pixel_bytes: self.pixel_bytes } } - /// Captured source and control capacities, retained by the same host lease. + /// Actual/conservative captured source, binding, name and control-header + /// backing. Available before a CPU or registered executor consumes maps. pub fn captured_bytes(&self) -> Result { let slots: usize = self .bindings @@ -284,6 +286,8 @@ impl RuntimeTextures { .checked_add(self.bindings.capacity() as u64 * size_of::() as u64) .and_then(|bytes| bytes.checked_add(self.bindings.iter().map(|b| b.body_name.capacity() as u64).sum::())) .and_then(|bytes| bytes.checked_add(self.source_bytes)) + // Shared encoded allocations are counted once in source_bytes. The + // small control-header allowance conservatively counts every role. .and_then(|bytes| bytes.checked_add(slots as u64 * (size_of::>() + 2 * size_of::()) as u64)) .ok_or_else(|| invalid("CPU texture source metadata overflow")) } @@ -319,17 +323,18 @@ impl RuntimeTextures { } } -/// CPU image maps use one mapped closure for every supported direct-light path. -/// Unsupported optical continuations refuse before source preparation. +/// Pure compatibility check before captured image-map bytes enter a CPU job. +/// Opaque direct and path lighting share the same cached mapped closure. Other +/// optical continuations are retained in the request and refused, never ignored. pub fn validate_cpu_options(options: &super::RaytraceOptions) -> Result<()> { options.validate()?; - if !options.dielectrics.is_empty() + if (!options.dielectrics.is_empty() && options.path.is_none()) || options.anisotropic_faces.iter().any(Option::is_some) || options.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty()) || options.surface_effects.as_ref().is_some_and(|effects| !effects.is_empty()) { return Err(invalid( - "CPU surface maps support opaque direct lighting; use GPU or explicitly remove incompatible Glass, selected reflections, anisotropy or procedural surface effects", + "CPU surface maps support opaque direct or indirect lighting; preserve the maps and use GPU, or explicitly remove incompatible Glass, selected reflections, anisotropy or procedural surface effects", )); } Ok(()) @@ -511,6 +516,7 @@ mod tests { assert_eq!(encoded, "replace"); assert!(serde_json::from_str::("\"unspecified\"").is_err()); } + // Independent source-structure cost: one header and each4096-byte CRC // block; EXIF adds its header, each IFD entry, and one final transition. #[cfg(feature = "raytrace-cpu")] diff --git a/crates/render/src/job/textures/cpu_cache.rs b/crates/render/src/job/textures/cpu_cache.rs index 6c8ecbdf1..417dadd2a 100644 --- a/crates/render/src/job/textures/cpu_cache.rs +++ b/crates/render/src/job/textures/cpu_cache.rs @@ -1,5 +1,5 @@ //! One work-owned cache for opaque CPU image maps. Every hit reuses one complete -//! mapped closure for directional, point, area and environment direct lighting. +//! mapped closure for direct/indirect BRDF, PDF and deterministic denoise guides. use super::cpu_preparation::{MapPoint, MapTask, PreparedMap}; use super::{RuntimeTextures, TextureBinding, TextureMap, validate_cpu_options}; use crate::{ diff --git a/crates/render/src/job/volume.rs b/crates/render/src/job/volume.rs index f8d2dae9d..b98a164f0 100644 --- a/crates/render/src/job/volume.rs +++ b/crates/render/src/job/volume.rs @@ -144,3 +144,46 @@ mod tests { assert!(serde_json::from_str::(r#"{"density_grid":"arbitrary"}"#).is_err()); } } + +#[cfg(test)] +mod cpu_contract_tests { + use super::*; + use crate::job::{CpuPathOptions, CpuProgressiveOptions, RaytraceOptions}; + #[test] + fn cpu_atmosphere_preserves_typed_bounds_zero_and_explicit_incompatible_intent() { + let v = HomogeneousVolume { + min_mm: [-2.0, -3.0, -4.0], + max_mm: [5.0, 6.0, 7.0], + extinction_per_mm: 0.2, + scattering_albedo: [0.1, 0.3, 0.7], + anisotropy: -0.4, + }; + let mut options = RaytraceOptions { + volume: Some(v), + path: Some(CpuPathOptions { max_depth: 4 }), + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }), + ..Default::default() + }; + options.validate().unwrap(); + let saved = serde_json::to_value(&options).unwrap(); + assert_eq!(serde_json::from_value::(saved.clone()).unwrap(), options); + options.denoise = true; + assert!(options.validate().unwrap_err().message.contains("Denoise")); + assert_eq!(options.volume, Some(v)); + options.denoise = false; + options.path = None; + assert!(options.validate().unwrap_err().message.contains("Indirect lighting")); + options.volume.as_mut().unwrap().extinction_per_mm = 0.0; + options.denoise = true; + options.validate().unwrap(); + assert_eq!(options.retained_volume_bytes().unwrap(), 0, "authored inactive intent owns no additional allocation"); + assert_eq!(saved["volume"]["anisotropy"], -0.4); + for key in ["min_mm", "max_mm", "scattering_albedo"] { + let mut bad = saved.clone(); + bad["volume"][key] = serde_json::json!([1, 2]); + assert!(serde_json::from_value::(bad).is_err()); + } + assert!(serde_json::from_value::(serde_json::json!({"volume":{"density_grid":"hidden"}})).is_err()); + assert!(serde_json::to_value(RaytraceOptions::default()).unwrap().get("volume").is_none()); + } +} diff --git a/crates/render/src/lighting/environment.rs b/crates/render/src/lighting/environment.rs index 099bb2401..3264f4224 100644 --- a/crates/render/src/lighting/environment.rs +++ b/crates/render/src/lighting/environment.rs @@ -39,7 +39,7 @@ impl SkyGradient { } Ok(()) } - fn evaluate(self, z: f64) -> [f32; 3] { + pub(crate) fn evaluate(self, z: f64) -> [f32; 3] { let endpoint = if z >= 0.0 { self.zenith } else { self.ground }; let blend = z.abs().sqrt() as f32; std::array::from_fn(|i| self.horizon[i] * (1.0 - blend) + endpoint[i] * blend) diff --git a/crates/render/src/raytrace/aging.rs b/crates/render/src/raytrace/aging.rs new file mode 100644 index 000000000..fe9919f69 --- /dev/null +++ b/crates/render/src/raytrace/aging.rs @@ -0,0 +1,199 @@ +//! Ordered world-space aging, evaluated once per hit before its shared closure. +//! This is optical authorship, not corrosion kinetics or geometric displacement. +use crate::{ + job::{ + self, + aging::{AgingKind, AgingLayer, AgingStack, SurfaceClass}, + }, + surface::{OpaqueSurface, srgb8_to_linear}, + surface_patterns::ShadingSurface, +}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; + +fn invalid(message: &'static str) -> job::JobError { + job::JobError::new(job::ErrorCode::InvalidRequest, message) +} +fn hash(cell: [i64; 3], seed: u32) -> f64 { + let [x, y, z] = cell.map(|n| (n as u64 & 4095) as u32); + let mut h = x.wrapping_mul(0x8da6_b343) ^ y.wrapping_mul(0xd816_3841) ^ z.wrapping_mul(0xcb1a_b31f) ^ seed.wrapping_mul(0x9e37_79b9); + h = (h ^ (h >> 16)).wrapping_mul(0x7feb_352d); + h = (h ^ (h >> 15)).wrapping_mul(0x846c_a68b); + h ^= h >> 16; + f64::from(h >> 8) / 16_777_216.0 +} +fn mix(a: f64, b: f64, t: f64) -> f64 { + if t == 0.0 { + a + } else if t == 1.0 { + b + } else { + a + (b - a) * t + } +} +fn smooth(a: f64, b: f64, value: f64) -> f64 { + let x = ((value - a) / (b - a)).clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} +fn noise(point: Vec3, seed: u32) -> f64 { + let base = [point.x.floor() as i64, point.y.floor() as i64, point.z.floor() as i64]; + let fraction = [point.x - point.x.floor(), point.y - point.y.floor(), point.z - point.z.floor()]; + let [x, y, z] = fraction.map(|v| v * v * (3.0 - 2.0 * v)); + let at = |dx, dy, dz| hash([base[0] + dx, base[1] + dy, base[2] + dz], seed); + let low = mix(mix(at(0, 0, 0), at(1, 0, 0), x), mix(at(0, 1, 0), at(1, 1, 0), x), y); + let high = mix(mix(at(0, 0, 1), at(1, 0, 1), x), mix(at(0, 1, 1), at(1, 1, 1), x), y); + mix(low, high, z) +} +fn mask(layer: &AgingLayer, position: Vec3, outward: Vec3) -> job::Result<(f64, f64)> { + // Subtract in f64 before scaling. Do not derive a world field from camera + // rebasing: Scratch's floor(0.8*q) does not share noise's4096-cell period. + let origin = Vec3::new(layer.origin_mm[0], layer.origin_mm[1], layer.origin_mm[2]); + let q = (position - origin) / layer.scale_mm; + if !q.is_finite() || q.x.abs().max(q.y.abs()).max(q.z.abs()) > 1.0e15 { + return Err(invalid("CPU aging coordinates exceed the finite field bound")); + } + let coarse = noise(q, layer.seed); + let fine = noise(q * 3.0 + Vec3::new(19.0, 7.0, 3.0), layer.seed + 1); + let field = coarse * 0.75 + fine * 0.25; + let threshold = 1.0 - layer.coverage; + let mut coverage = if layer.coverage >= 1.0 { 1.0 } else { smooth(threshold - 0.09, threshold + 0.09, field) }; + if layer.kind == AgingKind::Scratches { + let [x, y, z] = [outward.x.abs(), outward.y.abs(), outward.z.abs()]; + let [u, v] = if x > y && x > z { + [q.y, q.z] + } else if y > z { + [q.x, q.z] + } else { + [q.x, q.y] + }; + let band = (v * 0.8).floor() as i64; + let line = ((u * 24.0 + hash([band, 0, 0], layer.seed) * 0.7).rem_euclid(1.0) - 0.5).abs(); + coverage *= 1.0 - smooth(0.025, 0.09, line); + coverage *= smooth(0.18, 0.48, fine); + } + let slope = outward.z.max(0.0).powf(1.5); + coverage *= mix(1.0, slope, layer.upward_bias); + Ok(((coverage * layer.strength).clamp(0.0, 1.0), field)) +} +fn apply( + layer: &AgingLayer, + original_metallic: f64, + surface: OpaqueSurface, + position: Vec3, + outward: Vec3, + body: usize, +) -> job::Result { + if !layer.active() + || layer.target.is_some_and(|target| target.body_index as usize != body) + || (layer.surface_class == SurfaceClass::Metal && original_metallic < 0.5) + || (layer.surface_class == SurfaceClass::Dielectric && original_metallic >= 0.5) + { + return Ok(surface); + } + let (weight, field) = mask(layer, position, outward)?; + if weight == 0.0 { + return Ok(surface); + } + let [r, g, b] = layer.color_srgb.map(srgb8_to_linear); + let mut coat = Vec3::new(r, g, b); + if matches!(layer.kind, AgingKind::Rust | AgingKind::Patina | AgingKind::Grime) { + coat = coat * (0.45 + 0.7 * field); + } + if layer.kind == AgingKind::Fading { + coat = surface.base_color().lerp(coat, 0.5); + } + coat = Vec3::new(coat.x.clamp(0.0, 1.0), coat.y.clamp(0.0, 1.0), coat.z.clamp(0.0, 1.0)); + let mut result = surface + .with_authored_finish( + if weight == 1.0 { coat } else { surface.base_color().lerp(coat, weight) }, + mix(surface.metallic(), layer.metallic, weight), + mix(surface.roughness(), layer.roughness, weight), + ) + .map_err(|_| invalid("invalid CPU aged surface"))?; + if let Some(clear) = surface.clear_coat() { + let clear = crate::clear_coat::ClearCoat::new(clear.weight() * (1.0 - weight), clear.roughness(), clear.ior()) + .map_err(|_| invalid("invalid CPU aged clear coat"))?; + result = result.with_clear_coat(clear); + } + Ok(result) +} + +#[derive(Clone, Copy)] +struct Hit { + current: ShadingSurface, + original_metallic: f64, + position: Vec3, + outward: Vec3, + body: usize, +} +/// A single fallibly prepaid slot is reused by guides and then transport. Future +/// mapped surfaces enter begin() before aging; no map consumer is implied here. +#[derive(Default)] +pub(super) struct Task { + hit: Option, + cursor: usize, + ready: bool, +} +impl Task { + pub(super) fn required_bytes() -> u64 { + std::mem::size_of::() as u64 + } + pub(super) fn reset(&mut self) { + *self = Self::default(); + } + pub(super) fn started(&self) -> bool { + self.hit.is_some() + } + pub(super) fn ready(&self) -> bool { + self.ready + } + pub(super) fn begin(&mut self, input: ShadingSurface, position: Vec3, outward: Vec3, body: usize, eligible: bool) -> job::Result<()> { + if !position.is_finite() || !outward.is_finite() || (outward.len() - 1.0).abs() > 1e-8 { + return Err(invalid("CPU aging needs a finite hit and its original unit geometric normal")); + } + self.hit = Some(Hit { current: input, original_metallic: input.surface.metallic(), position, outward, body }); + self.cursor = 0; + self.ready = !eligible; + Ok(()) + } + /// The caller charges exactly one existing cumulative-work unit before this + /// one-layer continuation. No RNG, heap allocation or film mutation occurs. + pub(super) fn advance(&mut self, stack: &AgingStack) -> job::Result { + if self.ready { + return Err(invalid("CPU aging hit is already complete")); + } + let mut hit = self.hit.ok_or_else(|| invalid("CPU aging hit is not initialized"))?; + let layer = stack.get(self.cursor).ok_or_else(|| invalid("CPU aging layer cursor exceeds admission"))?; + hit.current.surface = apply(layer, hit.original_metallic, hit.current.surface, hit.position, hit.outward, hit.body)?; + self.hit = Some(hit); + self.cursor += 1; + self.ready = self.cursor == stack.len(); + Ok(self.ready) + } + pub(super) fn surface(&self) -> job::Result { + if !self.ready { + return Err(invalid("CPU aging hit is incomplete")); + } + self.hit.map(|hit| hit.current).ok_or_else(|| invalid("CPU aging hit is missing")) + } + #[cfg(test)] + pub(super) fn cursor(&self) -> usize { + self.cursor + } +} + +pub(super) fn eligible(options: &crate::job::RaytraceOptions, body: usize, name: &str) -> bool { + !name.starts_with("__render_stage__/") && !options.dielectrics.iter().any(|optics| optics.body_index == body) +} + +pub(super) fn validate_scene(scene: &crate::ProductScene, options: &crate::job::RaytraceOptions) -> job::Result<()> { + if let Some(stack) = &options.aging { + stack.validate_scene(scene)?; + for layer in stack.iter().filter(|layer| layer.active()) { + if layer.target.is_some_and(|target| options.dielectrics.iter().any(|optics| optics.body_index == target.body_index as usize)) { + return Err(invalid("CPU aging supports opaque surfaces only; explicit certified dielectric targets are refused")); + } + } + } + Ok(()) +} diff --git a/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs b/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs index edf5dc68b..9697f2f42 100644 --- a/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs +++ b/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs @@ -315,3 +315,97 @@ fn cancellation_after_last_shadow_is_seen_before_shading_or_sampling() { assert!(task.pixels.is_empty()); } } + +fn progressive_anisotropic_fixture(samples: u32, orientation: AnisotropicOrientation, equal_axes: Option) -> ImageTask { + let mut request = request(orientation, true); + request.camera.distance = 20.0; + request.width = 3; + request.height = 3; + let options = request.raytrace.as_mut().unwrap(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 93 }); + options.reflections.as_mut().unwrap().samples = 1; + if let Some(explicit) = equal_axes { + if explicit { + let target = options.anisotropic_faces[0].as_mut().unwrap(); + target.roughness_x = 0.4; + target.roughness_y = 0.4; + } else { + options.anisotropic_faces = [None, None]; + } + } + ImageTask::new(scene(), request.clone(), CancelToken::default(), request.raytrace.unwrap()).unwrap() +} + +fn progressive_anisotropic_complete(mut task: ImageTask, quantum: usize) -> (Vec<(u32, Vec)>, Vec, u64) { + let mut previews = Vec::new(); + let mut real_secondary = false; + for _ in 0..2_000_000 { + let used = task.work.used(); + let transport = task.progress().phase == Phase::Running; + let poll = task.step_with_previews(quantum).unwrap(); + if quantum == 1 && transport { + assert!(task.work.used() - used <= 4); + } + real_secondary |= task.pending.as_ref().is_some_and(|p| p.bounce > 0); + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => previews.push((samples_per_pixel, png)), + ImagePoll::Complete(png) => { + assert!(real_secondary, "actual anisotropic image transport must trace secondary rays"); + return (previews, png, task.work.used()); + } + } + } + panic!("bounded progressive anisotropic fixture did not finish"); +} + +#[test] +fn progressive_anisotropic_images_keep_real_reflections_prefixes_and_quanta() { + let a = progressive_anisotropic_complete(progressive_anisotropic_fixture(8, AnisotropicOrientation::Zero, None), 1); + assert_eq!(a.0.iter().map(|p| p.0).collect::>(), [1, 2, 3, 4, 5, 6, 7]); + assert_eq!(a, progressive_anisotropic_complete(progressive_anisotropic_fixture(8, AnisotropicOrientation::Zero, None), 16_384)); + for (samples, png) in &a.0 { + assert_eq!(*png, progressive_anisotropic_complete(progressive_anisotropic_fixture(*samples, AnisotropicOrientation::Zero, None), 3).1); + } + let b = progressive_anisotropic_complete(progressive_anisotropic_fixture(8, AnisotropicOrientation::QuarterTurn, None), 1); + assert_ne!(a.1, b.1, "rotating anisotropy must affect the actual reflected object"); + let image = ::image::load_from_memory(&a.1).unwrap().to_rgba8(); + assert!(image.pixels().any(|p| p[0] > p[1] && p[1] > p[2]), "off-axis orange geometry must contribute through reflection"); +} + +#[test] +fn progressive_equal_anisotropic_axes_keep_every_isotropic_image_byte() { + let isotropic = progressive_anisotropic_complete(progressive_anisotropic_fixture(8, AnisotropicOrientation::Zero, Some(false)), 1); + for orientation in [AnisotropicOrientation::Zero, AnisotropicOrientation::QuarterTurn] { + let explicit = progressive_anisotropic_complete(progressive_anisotropic_fixture(8, orientation, Some(true)), 1); + assert_eq!(isotropic.0, explicit.0); + assert_eq!(isotropic.1, explicit.1); + } +} + +#[test] +fn adaptive_planar_anisotropy_keeps_real_reflection_and_equal_axes_through_independent_production() { + use crate::job::adaptive::AdaptiveSampling; + let build = |orientation, equal_axes| { + let original = progressive_anisotropic_fixture(16, orientation, equal_axes); + let options = RaytraceOptions { + adaptive: Some(Box::new(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + let a = progressive_anisotropic_complete(build(AnisotropicOrientation::Zero, None), 1); + assert_eq!(a, progressive_anisotropic_complete(build(AnisotropicOrientation::Zero, None), 16384)); + assert_eq!(a.0.iter().map(|p| p.0).collect::>(), (1..32).collect::>()); + let ordinary = progressive_anisotropic_complete(progressive_anisotropic_fixture(16, AnisotropicOrientation::Zero, None), 1); + assert_eq!(a.1, ordinary.1, "the separate pilot stream cannot alter original production VNDF keys or PDFs"); + let rotated = progressive_anisotropic_complete(build(AnisotropicOrientation::QuarterTurn, None), 3); + assert_ne!(a.1, rotated.1, "the actual reflected geometry must respond to anisotropic orientation"); + let isotropic = progressive_anisotropic_complete(build(AnisotropicOrientation::Zero, Some(false)), 1); + for orientation in [AnisotropicOrientation::Zero, AnisotropicOrientation::QuarterTurn] { + let equal = progressive_anisotropic_complete(build(orientation, Some(true)), 3); + assert_eq!(equal.0, isotropic.0); + assert_eq!(equal.1, isotropic.1); + } +} diff --git a/crates/render/src/raytrace/box_certificate.rs b/crates/render/src/raytrace/box_certificate.rs new file mode 100644 index 000000000..5680de4ad --- /dev/null +++ b/crates/render/src/raytrace/box_certificate.rs @@ -0,0 +1,325 @@ +//! The tiled-box proof as bounded, cancellable continuations. Its geometry and +//! raw-bit edge policy match the independent synchronous dielectric certifier. +use super::{Bounds, Result, TraceError, Triangle, WorkBudget}; +use crate::job::CancelToken; +use solidcore_record::Vec3; +use solidcraft_geom::Mesh; +use solidcraft_geom::prelude::*; +use std::{cmp::Ordering, mem::size_of}; + +type Edge = ([u64; 3], [u64; 3]); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Stage { + Load, + Edges, + Sort, + Duplicates, + Reverse, + Area, + Done, +} + +fn reserve(count: usize) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| TraceError::AllocationFailed)?; + if values.capacity() != count { + return Err(TraceError::MemoryLimit); + } + Ok(values) +} + +/// No source references or certificate may escape independently: the owning +/// image/preparation supplies its same immutable mesh at each continuation. +pub(super) struct BoxTask { + triangles: Vec, + edges: Vec, + scratch: Vec, + count: usize, + stage: Stage, + lo: Vec3, + hi: Vec3, + area: f64, + i: usize, + width: usize, + begin: usize, + left: usize, + right: usize, + end: usize, + out: usize, + searching: bool, + search_lo: usize, + search_hi: usize, +} + +impl BoxTask { + pub(super) fn required_bytes(count: usize) -> Result { + if !(12..=super::dielectric::MAX_BOX_TRIANGLES).contains(&count) { + return Err(TraceError::InvalidInput("unsupported dielectric boundary tessellation")); + } + count + .checked_mul(size_of::() + 6 * size_of::()) + .and_then(|bytes| bytes.checked_add(size_of::())) + .and_then(|bytes| u64::try_from(bytes).ok()) + .ok_or(TraceError::MemoryLimit) + } + + /// Caller has admitted and, for a host preparation, reserved required_bytes + /// before this fallible allocation. No allocator growth occurs during step. + pub(super) fn new(count: usize) -> Result { + Self::required_bytes(count)?; + let edges = count.checked_mul(3).ok_or(TraceError::MemoryLimit)?; + Ok(Self { + triangles: reserve(count)?, + edges: reserve(edges)?, + scratch: reserve(edges)?, + count, + stage: Stage::Load, + lo: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), + hi: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), + area: 0.0, + i: 0, + width: 1, + begin: 0, + left: 0, + right: 0, + end: 0, + out: 0, + searching: false, + search_lo: 0, + search_hi: 0, + }) + } + + pub(super) fn result(&self) -> Result { + if self.stage != Stage::Done { + return Err(TraceError::BuildIncomplete); + } + Bounds::new(self.lo, self.hi) + } + + /// Reuse the prepaid largest-target buffers; clearing Copy elements does not + /// run an input-sized destructor loop or allocate another target's scratch. + pub(super) fn reset(&mut self, count: usize) -> Result<()> { + Self::required_bytes(count)?; + let edges = count.checked_mul(3).ok_or(TraceError::MemoryLimit)?; + if count > self.triangles.capacity() || edges > self.edges.capacity() || edges > self.scratch.capacity() { + return Err(TraceError::MemoryLimit); + } + self.triangles.clear(); + self.edges.clear(); + self.scratch.clear(); + self.count = count; + self.stage = Stage::Load; + self.lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); + self.hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + self.area = 0.0; + self.i = 0; + self.width = 1; + self.begin = 0; + self.left = 0; + self.right = 0; + self.end = 0; + self.out = 0; + self.searching = false; + self.search_lo = 0; + self.search_hi = 0; + Ok(()) + } + + /// One charged triangle, edge copy/comparison, or fixed-state transition. + /// Cancellation/exhaustion debit precedes every state or buffer mutation. + pub(super) fn step(&mut self, mesh: &Mesh, work: &mut WorkBudget, cancel: &CancelToken) -> Result { + if self.stage == Stage::Done { + return super::check_cancel(cancel).map(|()| true); + } + work.tick(cancel)?; + if mesh.triangles.len() != self.count { + return Err(TraceError::InvalidInput("dielectric captured mesh changed")); + } + match self.stage { + Stage::Load => { + if let Some(indices) = mesh.triangles.get(self.i) { + let triangle = super::dielectric::triangle(mesh, indices)?; + for p in triangle.vertices() { + self.lo = self.lo.min(p); + self.hi = self.hi.max(p); + } + if self.triangles.len() == self.triangles.capacity() { + return Err(TraceError::MemoryLimit); + } + self.triangles.push(triangle); + self.i += 1; + } else { + if self.lo.x >= self.hi.x || self.lo.y >= self.hi.y || self.lo.z >= self.hi.z { + return Err(TraceError::InvalidInput("closed box needs positive extents")); + } + Bounds::new(self.lo, self.hi)?; + self.i = 0; + self.stage = Stage::Edges; + } + } + Stage::Edges => { + if let Some(triangle) = self.triangles.get(self.i) { + let vertices = triangle.vertices(); + let normal = triangle.geometric_normal().ok_or(TraceError::InvalidInput("box normal"))?; + let axis = if normal.x.abs() == 1.0 { + 0 + } else if normal.y.abs() == 1.0 { + 1 + } else if normal.z.abs() == 1.0 { + 2 + } else { + return Err(TraceError::InvalidInput("box face is not axis aligned")); + }; + let positive = super::component(normal, axis) > 0.0; + let plane = super::component(if positive { self.hi } else { self.lo }, axis); + if vertices.iter().any(|p| super::component(*p, axis) != plane) { + return Err(TraceError::InvalidInput("box winding or face plane")); + } + let [a, b, c] = vertices; + self.area += (b - a).cross(c - a).len() * 0.5; + let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]; + if self.edges.capacity().saturating_sub(self.edges.len()) < 3 || self.scratch.capacity().saturating_sub(self.scratch.len()) < 3 { + return Err(TraceError::MemoryLimit); + } + self.edges.extend([(key(a), key(b)), (key(b), key(c)), (key(c), key(a))]); + self.scratch.extend([Edge::default(); 3]); + self.i += 1; + } else { + self.i = 0; + self.stage = Stage::Sort; + } + } + Stage::Sort => { + if self.width >= self.edges.len() { + self.i = 0; + self.stage = Stage::Duplicates; + return Ok(false); + } + if self.out == self.begin { + self.left = self.begin; + self.right = (self.begin + self.width).min(self.edges.len()); + self.end = (self.right + self.width).min(self.edges.len()); + } + let middle = (self.begin + self.width).min(self.edges.len()); + let take_left = self.left < middle && (self.right >= self.end || self.edges.get(self.left) <= self.edges.get(self.right)); + let at = if take_left { + let at = self.left; + self.left += 1; + at + } else { + let at = self.right; + self.right += 1; + at + }; + let value = *self.edges.get(at).ok_or(TraceError::Internal("box merge input"))?; + *self.scratch.get_mut(self.out).ok_or(TraceError::Internal("box merge output"))? = value; + self.out += 1; + if self.out == self.end { + self.begin = self.end; + if self.begin == self.edges.len() { + std::mem::swap(&mut self.edges, &mut self.scratch); + self.width = self.width.checked_mul(2).ok_or(TraceError::MemoryLimit)?; + self.begin = 0; + self.out = 0; + } + } + } + Stage::Duplicates => { + if let Some(next) = self.edges.get(self.i + 1) { + if self.edges.get(self.i) == Some(next) { + return Err(TraceError::InvalidInput("incomplete or ambiguous closed box face")); + } + self.i += 1; + } else { + self.i = 0; + self.stage = Stage::Reverse; + } + } + Stage::Reverse => { + let Some((a, b)) = self.edges.get(self.i) else { + self.stage = Stage::Area; + return Ok(false); + }; + if !self.searching { + self.search_lo = 0; + self.search_hi = self.edges.len(); + self.searching = true; + } else if self.search_lo < self.search_hi { + let mid = self.search_lo + (self.search_hi - self.search_lo) / 2; + match self.edges.get(mid).ok_or(TraceError::Internal("box reverse edge search"))?.cmp(&(*b, *a)) { + Ordering::Less => self.search_lo = mid + 1, + Ordering::Greater => self.search_hi = mid, + Ordering::Equal => { + self.searching = false; + self.i += 1; + } + } + } else { + return Err(TraceError::InvalidInput("incomplete or ambiguous closed box face")); + } + } + Stage::Area => { + let size = self.hi - self.lo; + let boundary = 2.0 * (size.x * size.y + size.y * size.z + size.z * size.x); + if self.area.partial_cmp(&(1.5 * boundary)) != Some(Ordering::Less) { + return Err(TraceError::InvalidInput("closed box boundary covered more than once")); + } + self.stage = Stage::Done; + } + Stage::Done => {} + } + Ok(self.stage == Stage::Done) + } + + #[cfg(test)] + pub(super) fn allocated_bytes(&self) -> u64 { + (size_of::() + + self.triangles.capacity() * size_of::() + + (self.edges.capacity() + self.scratch.capacity()) * size_of::()) as u64 + } + + #[cfg(test)] + pub(super) fn fingerprint(&self) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + ( + self.stage as u8, + self.count, + self.i, + self.width, + self.begin, + self.left, + self.right, + self.end, + self.out, + self.searching, + self.search_lo, + self.search_hi, + ) + .hash(&mut hash); + [self.lo.x, self.lo.y, self.lo.z, self.hi.x, self.hi.y, self.hi.z, self.area].map(f64::to_bits).hash(&mut hash); + for triangle in &self.triangles { + for p in triangle.vertices() { + [p.x, p.y, p.z].map(f64::to_bits).hash(&mut hash); + } + } + self.edges.hash(&mut hash); + self.scratch.hash(&mut hash); + hash.finish() + } + + #[cfg(test)] + pub(super) fn phase(&self) -> &'static str { + match self.stage { + Stage::Load => "load", + Stage::Edges => "edges", + Stage::Sort => "sort", + Stage::Duplicates => "duplicates", + Stage::Reverse => "reverse", + Stage::Area => "area", + Stage::Done => "done", + } + } +} diff --git a/crates/render/src/raytrace/bvh.rs b/crates/render/src/raytrace/bvh.rs index 3f2f7aabc..4ba9d6c9c 100644 --- a/crates/render/src/raytrace/bvh.rs +++ b/crates/render/src/raytrace/bvh.rs @@ -341,6 +341,7 @@ impl Bvh { /// The fixed stack is included in image admission; no per-ray heap allocation. pub(crate) struct TraceCursor { ray: Ray, + source_plane: Option<(std::ops::Range, [solidcore_record::Vec3; 3])>, any: bool, stack: [usize; STACK_SLOTS], length: usize, @@ -350,9 +351,27 @@ pub(crate) struct TraceCursor { } impl TraceCursor { pub(crate) fn new(ray: Ray, any: bool) -> Self { - Self { ray, any, stack: [0; STACK_SLOTS], length: 1, leaf: None, best: None, done: false } + Self { ray, source_plane: None, any, stack: [0; STACK_SLOTS], length: 1, leaf: None, best: None, done: false } + } + /// Only the opt-in general-glass route uses an exact on-surface origin. + /// Exclude its producing plane, not an epsilon slab or a parallel face. + pub(crate) fn from_plane(ray: Ray, range: std::ops::Range, plane: [solidcore_record::Vec3; 3]) -> Self { + let mut cursor = Self::new(ray, false); + cursor.source_plane = Some((range, plane)); + cursor } pub(crate) fn step(&mut self, bvh: &Bvh, work: &mut WorkBudget, cancel: &CancelToken) -> Result>> { + self.step_ordered(bvh, work, cancel, |new, old| new.primitive_index < old.primitive_index) + } + /// Opt-in transport can choose a material ordering at an exact distance tie; + /// ordinary visibility retains its original input-ordinal ordering. + pub(crate) fn step_ordered( + &mut self, + bvh: &Bvh, + work: &mut WorkBudget, + cancel: &CancelToken, + prefer: impl Fn(Hit, Hit) -> bool, + ) -> Result>> { work.tick(cancel)?; if self.done { return Err(TraceError::Internal("completed traversal cursor")); @@ -366,6 +385,13 @@ impl TraceCursor { self.leaf = Some((ordinal + 1, end)); let index = *bvh.order.get(ordinal).ok_or(TraceError::Internal("cursor ordinal"))?; let triangle = bvh.triangles.get(index).ok_or(TraceError::Internal("cursor primitive"))?; + if self + .source_plane + .as_ref() + .is_some_and(|(range, plane)| range.contains(&index) && super::glass_mesh::same_plane(*plane, triangle.vertices())) + { + return Ok(None); + } if let Some(geometry) = triangle.intersect(&self.ray) { let hit = Hit { primitive_index: index, geometry }; if self.any { @@ -373,7 +399,7 @@ impl TraceCursor { return Ok(Some(Some(hit))); } if self.best.is_none_or(|old| { - geometry.distance < old.geometry.distance || (geometry.distance == old.geometry.distance && index < old.primitive_index) + geometry.distance < old.geometry.distance || (geometry.distance == old.geometry.distance && prefer(hit, old)) }) { self.best = Some(hit); } @@ -403,3 +429,67 @@ impl TraceCursor { Ok(None) } } + +/// Cooperative candidate enumeration for exact origin predicates. Query boxes +/// are conservative (an axis ray or finite segment's box); no floating ray-depth +/// ordering, nearest-hit truncation or probability is used for the certificate. +pub(super) struct PrimitiveScan { + min: solidcore_record::Vec3, + max: solidcore_record::Vec3, + stack: [usize; STACK_SLOTS], + length: usize, + leaf: Option<(usize, usize)>, + done: bool, +} +pub(super) enum ScanPoll { + Pending, + Primitive(usize), + Done, +} +impl PrimitiveScan { + pub(super) fn new(min: solidcore_record::Vec3, max: solidcore_record::Vec3) -> Result { + if !min.is_finite() || !max.is_finite() || min.x > max.x || min.y > max.y || min.z > max.z { + return Err(TraceError::InvalidInput("CPU origin scan bounds")); + } + Ok(Self { min, max, stack: [0; STACK_SLOTS], length: 1, leaf: None, done: false }) + } + pub(super) fn step(&mut self, bvh: &Bvh, work: &mut WorkBudget, cancel: &CancelToken) -> Result { + work.tick(cancel)?; + if self.done { + return Err(TraceError::Internal("completed CPU origin scan")); + } + if bvh.nodes.is_empty() { + self.done = true; + return Ok(ScanPoll::Done); + } + if let Some((at, end)) = self.leaf { + if at < end { + self.leaf = Some((at + 1, end)); + let index = *bvh.order.get(at).ok_or(TraceError::Internal("CPU origin scan ordinal"))?; + return Ok(ScanPoll::Primitive(index)); + } + self.leaf = None; + } + if self.length == 0 { + self.done = true; + return Ok(ScanPoll::Done); + } + self.length -= 1; + let index = *self.stack.get(self.length).ok_or(TraceError::Internal("CPU origin scan stack"))?; + let node = bvh.nodes.get(index).ok_or(TraceError::Internal("CPU origin scan node"))?; + let lo = node.bounds.min(); + let hi = node.bounds.max(); + if !(hi.x < self.min.x || lo.x > self.max.x || hi.y < self.min.y || lo.y > self.max.y || hi.z < self.min.z || lo.z > self.max.z) { + match node.kind { + Kind::Leaf { start, end } => self.leaf = Some((start, end)), + Kind::Branch { left, right } => { + for child in [right, left] { + *self.stack.get_mut(self.length).ok_or(TraceError::Internal("CPU origin scan bounded stack"))? = child; + self.length += 1; + } + } + } + } + Ok(ScanPoll::Pending) + } +} diff --git a/crates/render/src/raytrace/celestial.rs b/crates/render/src/raytrace/celestial.rs new file mode 100644 index 000000000..3ab92e12b --- /dev/null +++ b/crates/render/src/raytrace/celestial.rs @@ -0,0 +1,37 @@ +//! Bounded finite-disk Sun proposals. Shared material evaluation/PDFs stay unchanged. +use super::{Result, TraceError}; +use crate::{job::Sun, surface::unit_direction}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use std::f64::consts::{PI, TAU}; + +pub(super) struct Sample { + pub direction: Vec3, + pub radiance: Vec3, + pub pdf: f64, +} +fn invalid() -> TraceError { + TraceError::InvalidInput("invalid CPU finite Sun sample") +} +pub(super) fn pdf(sun: Sun, direction: Vec3) -> Result { + sun.validate().map_err(|_| invalid())?; + let direction = unit_direction(direction).map_err(|_| invalid())?; + Ok(if direction.dot(sun.direction()) >= sun.angular_radius_rad.cos() { sun.solid_angle().recip() } else { 0.0 }) +} +pub(super) fn radiance(sun: Sun, direction: Vec3) -> Result { + Ok(if pdf(sun, direction)? > 0.0 { Vec3::new(sun.radiance[0], sun.radiance[1], sun.radiance[2]) } else { Vec3::ZERO }) +} +pub(super) fn sample(sun: Sun, u: [f64; 2]) -> Result { + sun.validate().map_err(|_| invalid())?; + if u.into_iter().any(|v| !v.is_finite() || !(0.0..1.0).contains(&v)) { + return Err(invalid()); + } + let n = sun.direction(); + let axis = if n.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z }; + let tangent = unit_direction(axis.cross(n)).map_err(|_| invalid())?; + let z = 1.0 - u[0] * sun.solid_angle() / (2.0 * PI); + let radius = ((1.0 - z) * (1.0 + z)).max(0.0).sqrt(); + let phi = TAU * u[1]; + let direction = unit_direction(tangent * (radius * phi.cos()) + n.cross(tangent) * (radius * phi.sin()) + n * z).map_err(|_| invalid())?; + Ok(Sample { direction, radiance: Vec3::new(sun.radiance[0], sun.radiance[1], sun.radiance[2]), pdf: sun.solid_angle().recip() }) +} diff --git a/crates/render/src/raytrace/denoise.rs b/crates/render/src/raytrace/denoise.rs new file mode 100644 index 000000000..e0411b4c0 --- /dev/null +++ b/crates/render/src/raytrace/denoise.rs @@ -0,0 +1,272 @@ +//! Deterministic first-hit CPU guides, generated once without touching the sampling stream. +use super::bvh::TraceCursor; +use super::image::{error, invalid, primary_ray}; +use super::prepared::PreparedScene; +use super::{Hit, Ray, WorkBudget}; +use crate::job::{CancelToken, ImageRequest, RaytraceOptions, Result, denoise::Guide}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; + +pub(super) struct Guides { + pixels: Vec, + count: usize, + cursor: Option, + ray: Option, + hit: Option, + emitter_cursor: usize, + analytic_emitter: bool, + effect_cursor: usize, + effect: Option, + pending: Option, +} +impl Guides { + pub(super) fn required_bytes(width: u32, height: u32) -> Result { + (u64::from(width) * u64::from(height)) + .checked_mul(crate::job::denoise::GUIDE_BYTES) + .and_then(|v| v.checked_add(std::mem::size_of::() as u64)) + .ok_or_else(|| invalid("CPU denoising guide size overflow")) + } + pub(super) fn new(width: u32, height: u32) -> Result { + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| invalid("CPU guide dimensions overflow"))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(count).map_err(|_| error(super::TraceError::AllocationFailed))?; + if count == 0 || pixels.capacity() != count { + return Err(invalid("CPU guide capacity exceeds admission")); + } + Ok(Self { + pixels, + count, + cursor: None, + ray: None, + hit: None, + emitter_cursor: 0, + analytic_emitter: false, + effect_cursor: 0, + effect: None, + pending: None, + }) + } + #[cfg(test)] + pub(super) fn ready_to_store(&self, options: &RaytraceOptions) -> bool { + let scanned_emitters = options.path.is_none() || self.emitter_cursor >= options.area_lights.as_ref().map_or(0, Vec::len); + self.pending.is_some() || (self.ray.is_some() && self.cursor.is_none() && scanned_emitters && (self.hit.is_none() || self.analytic_emitter)) + } + #[cfg(test)] + pub(super) fn emitter_scans(&self) -> usize { + self.emitter_cursor + } + pub(super) fn completed_pixels(&self) -> usize { + self.pixels.len() + } + pub(super) fn ready(&self) -> bool { + self.pixels.len() == self.count + } + pub(super) fn pixels(&self) -> Result<&[Guide]> { + if !self.ready() { + return Err(invalid("CPU denoising guides are incomplete")); + } + Ok(&self.pixels) + } + fn append(&mut self, guide: Guide, work: &mut WorkBudget, cancel: &CancelToken) -> Result<()> { + work.tick(cancel).map_err(error)?; + guide.validate()?; + if self.ready() { + return Err(invalid("CPU denoising guide cursor exceeds admission")); + } + self.pixels.push(guide); + self.ray = None; + self.cursor = None; + self.hit = None; + self.emitter_cursor = 0; + self.analytic_emitter = false; + self.effect_cursor = 0; + self.effect = None; + self.pending = None; + Ok(()) + } + /// A continuation creates one ray, visits one BVH node/triangle, scans one + /// bounded emitter/effect row, or resolves/stores one guide. The normal image budget is shared. + #[allow(clippy::too_many_arguments)] + pub(super) fn step( + &mut self, + scene: PreparedScene<'_>, + request: &ImageRequest, + options: &RaytraceOptions, + clip: (f64, f64), + effects: &[(usize, crate::surface_patterns::PreparedEffect)], + mut maps: Option<&mut crate::job::textures::cpu_cache::CpuTextureCache>, + mut aging: Option<&mut super::aging::Task>, + work: &mut WorkBudget, + cancel: &CancelToken, + ) -> Result<()> { + cancel.check()?; + if self.ready() { + return Err(invalid("CPU denoising guides are already complete")); + } + if let Some(guide) = self.pending { + return self.append(guide, work, cancel); + } + if self.ray.is_none() { + work.tick(cancel).map_err(error)?; + let pixel = self.pixels.len(); + let width = request.width as usize; + let ray = primary_ray(request, (pixel % width) as f64 + 0.5, (pixel / width) as f64 + 0.5, clip).map_err(error)?; + if let Some(maps) = &mut maps { + maps.reset_hit(); + } + if let Some(aging) = &mut aging { + aging.reset(); + } + self.ray = Some(ray); + self.cursor = Some(TraceCursor::new(ray, false)); + return Ok(()); + } + if let Some(cursor) = &mut self.cursor { + if let Some(hit) = cursor.step(scene.bvh, work, cancel).map_err(error)? { + self.cursor = None; + self.hit = hit; + } + return Ok(()); + } + let ray = self.ray.ok_or_else(|| invalid("CPU guide ray disappeared"))?; + if options.path.is_some() + && let Some(input) = options.area_lights.as_ref().and_then(|lights| lights.get(self.emitter_cursor)) + { + // The path producer makes analytic rectangles visible. A guide for the + // body behind a closer panel would incorrectly filter its emitted pixels. + // One source scan owns one debit; equal-depth geometry still wins. + work.tick(cancel).map_err(error)?; + let light = super::indirect::Rectangle::new(input).map_err(error)?; + if let Some((distance, _)) = light.intersect(ray).map_err(error)? + && self.hit.is_none_or(|hit| distance < hit.geometry.distance) + { + self.analytic_emitter = true; + } + self.emitter_cursor += 1; + return Ok(()); + } + if self.analytic_emitter { + return self.append(Guide::default(), work, cancel); + } + let Some(hit) = self.hit else { + return self.append(Guide::default(), work, cancel); + }; + work.tick(cancel).map_err(error)?; + let mut shared = scene.resolve_hit(ray, hit).map_err(error)?; + if let Some((body, _)) = effects.get(self.effect_cursor) { + if *body == shared.body_index { + self.effect = Some(self.effect_cursor); + self.effect_cursor = effects.len(); + } else { + self.effect_cursor += 1; + } + return Ok(()); + } + if let Some(index) = self.effect { + let (_, effect) = effects.get(index).ok_or_else(|| invalid("CPU guide effect disappeared"))?; + let changed = effect.apply(shared.surface, shared.shading_normal, shared.oriented_geometric_normal(), shared.position)?; + shared.surface = changed.surface; + shared.shading_normal = changed.shading_normal; + } + let has_aging = aging.is_some(); + if let Some(maps) = maps { + if !maps.hit_started() { + let has_face_override = scene.primitives.get(shared.primitive_index).is_none_or(|look| look.has_face_override); + let pixel = self.pixels.len(); + let width = request.width as usize; + let footprint = super::image::camera_footprint( + request, + (pixel % width) as f64 + 0.5, + (pixel / width) as f64 + 0.5, + 1.0, + clip, + shared.position, + shared.oriented_geometric_normal(), + )?; + maps.begin_hit( + crate::surface_patterns::ShadingSurface { surface: shared.surface, shading_normal: shared.shading_normal }, + (!has_face_override).then_some(shared.body_index), + crate::job::textures::cpu_preparation::MapPoint { + position: shared.position, + geometric_normal: shared.oriented_geometric_normal(), + view_direction: -ray.direction(), + }, + footprint, + )?; + } + if !maps.hit_ready() { + let ready = maps.advance_hit()?; + // One map-role transition owns this debit. Aging starts on a + // subsequent continuation, after the complete mapped closure. + if !ready || has_aging { + return Ok(()); + } + } + let mapped = maps.surface()?; + shared.surface = mapped.surface; + shared.shading_normal = mapped.shading_normal; + } + if let Some(aging) = aging { + if !aging.started() { + aging.begin( + crate::surface_patterns::ShadingSurface { surface: shared.surface, shading_normal: shared.shading_normal }, + shared.position, + shared.geometric_normal, + shared.body_index, + super::aging::eligible(options, shared.body_index, shared.body_name), + )?; + } + if !aging.ready() { + let stack = options.aging.as_deref().ok_or_else(|| invalid("CPU guide aging stack disappeared"))?; + if !aging.advance(stack)? { + return Ok(()); + } + } + let changed = aging.surface()?; + shared.surface = changed.surface; + shared.shading_normal = changed.shading_normal; + } + // Match the GPU's first-hit policy. The explicit CPU Mirror mode is the + // corresponding sharp-reflection override even on a dielectric base colour. + let glass = options.dielectrics.iter().any(|value| value.body_index == shared.body_index); + let mirror = options.reflections.as_ref().is_some_and(|settings| { + settings.bodies.iter().any(|value| value.body == shared.body_name && value.mode == crate::job::ReflectionMode::Mirror) + }); + let emitter = options + .emissions + .iter() + .flatten() + .any(|value| value.body_index == shared.body_index && value.strength > 0.0 && value.color.iter().any(|v| *v > 0.0)); + let smooth_metal = shared.surface.metallic() > 0.5 && shared.surface.roughness() < 0.25; + let sharp_coat = shared.surface.clear_coat().is_some_and(|coat| coat.weight() > 0.0 && coat.roughness() < 0.05); + if glass || mirror || emitter || smooth_metal || sharp_coat { + self.pending = Some(Guide::default()); + return Ok(()); + } + let geometric = shared.oriented_geometric_normal(); + let normal = if shared.shading_normal.dot(-ray.direction()) > 0.0 { shared.shading_normal } else { geometric }; + let camera = &request.camera; + let relative = shared.position - camera.eye(); + let depth = relative.dot(-camera.back()); + let mut footprint = 2.0 * camera.half_height() / f64::from(request.height); + if camera.fov != 0.0 { + footprint *= depth.max(0.0) / camera.distance; + } + let array = |v: Vec3| [v.x as f32, v.y as f32, v.z as f32]; + let body = u32::try_from(shared.body_index) + .ok() + .and_then(|body| body.checked_add(1)) + .ok_or_else(|| invalid("CPU denoising body identity overflow"))?; + let guide = Guide { + albedo: array(shared.surface.base_color()), + body, + normal: array(normal), + depth: depth as f32, + position: array(relative), + footprint: footprint.max(0.000001) as f32, + }; + guide.validate()?; + self.pending = Some(guide); + Ok(()) + } +} diff --git a/crates/render/src/raytrace/dielectric.rs b/crates/render/src/raytrace/dielectric.rs index b12116ccd..9dc1a93e4 100644 --- a/crates/render/src/raytrace/dielectric.rs +++ b/crates/render/src/raytrace/dielectric.rs @@ -22,6 +22,21 @@ pub fn interface(direction: Vec3, normal: Vec3, incident: f64, transmitted: f64) polarized_interface(direction, normal, incident, transmitted).map(|(optics, _)| optics) } +/// General Path follows the captured smooth optical normal only while both +/// delta directions cross the original geometric hemispheres correctly. Entry, +/// exit, medium identity and source-plane exclusion always use the original face. +pub(super) fn shaded_interface(direction: Vec3, geometric: Vec3, shading: Vec3, incident: f64, transmitted: f64) -> Result<(Interface, Vec3)> { + let geometric = unit(geometric).ok_or(TraceError::InvalidInput("CPU glass geometric normal"))?; + let direction = unit(direction).ok_or(TraceError::InvalidInput("CPU glass incident direction"))?; + let shading = unit(shading).filter(|n| n.dot(geometric) > 0.0 && n.dot(-direction) > 0.0).unwrap_or(geometric); + let candidate = interface(direction, shading, incident, transmitted)?; + if candidate.reflected.dot(geometric) <= 0.0 || candidate.transmitted.is_some_and(|d| d.dot(geometric) >= 0.0) { + Ok((interface(direction, geometric, incident, transmitted)?, geometric)) + } else { + Ok((candidate, shading)) + } +} + fn polarized_interface(direction: Vec3, normal: Vec3, incident: f64, transmitted: f64) -> Result<(Interface, [f64; 2])> { if ![incident, transmitted].into_iter().all(|n| n.is_finite() && (1.0..=3.0).contains(&n)) { return Err(TraceError::InvalidInput("dielectric IOR outside 1..3")); @@ -113,6 +128,13 @@ pub const MAX_BOX_TRIANGLES: usize = 1 << 16; /// coplanar triangles; a closed box is a mesh that is exactly the boundary of an axis-aligned /// box, in however many triangles ([`certify_box`]). pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result { + if input.boundary == crate::job::DielectricBoundary::ClosedMesh || input.shadow_transmission { + return Err(TraceError::InvalidInput("general glass requires explicit CPU Path transport")); + } + certify_shape(scene, input) +} +/// Geometry-only certificate reused for the same thin-sheet boundary in Path. +pub(super) fn certify_shape(scene: &ProductScene, input: &DielectricOptions) -> Result { let body = scene.meshes.get(input.body_index).ok_or(TraceError::InvalidInput("dielectric body ordinal"))?; if body.name != input.body_name { return Err(TraceError::InvalidInput("dielectric captured body identity mismatch")); @@ -126,6 +148,13 @@ pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result Result { + let unsupported = TraceError::InvalidInput("unsupported dielectric boundary tessellation"); if !(1..=2).contains(&mesh.triangles.len()) || mesh.positions.len() > 36 { return Err(unsupported); } @@ -173,7 +202,7 @@ pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result Result { +pub(super) fn triangle(mesh: &solidcraft_geom::Mesh, indices: &[u32; 3]) -> Result { let mut vertices = [Vec3::ZERO; 3]; for (v, index) in vertices.iter_mut().zip(indices) { *v = *mesh.positions.get(*index as usize).ok_or(TraceError::InvalidInput("dielectric vertex index"))?; diff --git a/crates/render/src/raytrace/dielectric_tests.rs b/crates/render/src/raytrace/dielectric_tests.rs index 3cfced34b..2a1ed3e86 100644 --- a/crates/render/src/raytrace/dielectric_tests.rs +++ b/crates/render/src/raytrace/dielectric_tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::{ ProductMesh, - job::{CancelToken, DielectricBoundary, ImageRequest, Integrator, RaytraceOptions, TaskPoll}, + job::{self, CancelToken, DielectricBoundary, ImageRequest, Integrator, RaytraceOptions, TaskPoll}, }; use solidcraft_geom::Mesh; use std::sync::Arc; @@ -28,6 +28,8 @@ pub(in crate::raytrace) fn scene(body: ProductMesh) -> ProductScene { } pub(in crate::raytrace) fn input(boundary: DielectricBoundary) -> DielectricOptions { DielectricOptions { + shadow_transmission: false, + subsurface: None, body_index: 0, body_name: "captured slab@occurrence-2".into(), boundary, @@ -266,7 +268,13 @@ fn thin_sheet_is_certified_separately_and_duplicate_faces_refuse() { let actual = render(scene(body.clone()), options); let closed = RaytraceOptions { environment: environment(), - dielectrics: vec![DielectricOptions { ior: 1.0, absorption_per_mm: [0.1, 0.0, 0.0], ..input(DielectricBoundary::ClosedBox) }], + dielectrics: vec![DielectricOptions { + shadow_transmission: false, + subsurface: None, + ior: 1.0, + absorption_per_mm: [0.1, 0.0, 0.0], + ..input(DielectricBoundary::ClosedBox) + }], lights: Some(Vec::new()), shadows: false, ..Default::default() @@ -375,7 +383,7 @@ fn actual_oblique_png_selects_the_snell_shifted_colour_target() { let mut results = Vec::new(); for ior in [1.5, 1.0] { let options = RaytraceOptions { - dielectrics: vec![DielectricOptions { ior, ..input(DielectricBoundary::ClosedBox) }], + dielectrics: vec![DielectricOptions { shadow_transmission: false, subsurface: None, ior, ..input(DielectricBoundary::ClosedBox) }], lights: Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 4.0 }]), shadows: false, ..Default::default() @@ -433,6 +441,8 @@ fn thin_sheet_normal_incidence_keeps_the_lossless_slab_limit() { #[test] fn thin_sheet_matched_indices_keep_beer_lambert_transmission() { let material = DielectricOptions { + shadow_transmission: false, + subsurface: None, ior: 1.0, thickness_mm: 2.0, absorption_per_mm: [2.0f64.ln() / 2.0, 4.0f64.ln() / 2.0, 0.0], @@ -448,7 +458,8 @@ fn thin_sheet_matched_indices_keep_beer_lambert_transmission() { fn thin_sheet_zero_thickness_index_matched_grazing_is_transparent() { // Equal indices remove the interface; zero thickness means exp(-sigma * 0) = 1. for absorption_per_mm in [[0.0; 3], [100.0, 0.25, 1.0]] { - let material = DielectricOptions { ior: 1.0, absorption_per_mm, ..input(DielectricBoundary::ThinSheet) }; + let material = + DielectricOptions { shadow_transmission: false, subsurface: None, ior: 1.0, absorption_per_mm, ..input(DielectricBoundary::ThinSheet) }; let (optics, reflected, transmitted) = thin_sheet(Vec3::X, Vec3::Z, &material).unwrap(); assert_eq!(optics.reflectance, 0.0); assert_eq!(optics.transmitted, Some(Vec3::X)); @@ -459,7 +470,8 @@ fn thin_sheet_zero_thickness_index_matched_grazing_is_transparent() { #[test] fn thin_sheet_positive_thickness_index_matched_grazing_refuses_without_tir() { - let material = DielectricOptions { ior: 1.0, thickness_mm: 1.0, ..input(DielectricBoundary::ThinSheet) }; + let material = + DielectricOptions { shadow_transmission: false, subsurface: None, ior: 1.0, thickness_mm: 1.0, ..input(DielectricBoundary::ThinSheet) }; let optics = interface(Vec3::X, Vec3::Z, 1.0, 1.0).unwrap(); assert_eq!(optics.transmitted, Some(Vec3::X)); assert_eq!(optics.reflectance, 0.0); @@ -469,7 +481,13 @@ fn thin_sheet_positive_thickness_index_matched_grazing_refuses_without_tir() { #[test] fn thin_sheet_zero_thickness_grazing_still_validates_absorption() { for sigma in [f64::NAN, f64::INFINITY, -1.0, 101.0] { - let material = DielectricOptions { ior: 1.0, absorption_per_mm: [sigma, 0.0, 0.0], ..input(DielectricBoundary::ThinSheet) }; + let material = DielectricOptions { + shadow_transmission: false, + subsurface: None, + ior: 1.0, + absorption_per_mm: [sigma, 0.0, 0.0], + ..input(DielectricBoundary::ThinSheet) + }; assert!(matches!(thin_sheet(Vec3::X, Vec3::Z, &material), Err(TraceError::InvalidInput("dielectric absorption or distance")))); } } @@ -478,6 +496,8 @@ fn thin_sheet_zero_thickness_grazing_still_validates_absorption() { fn thin_sheet_absorbing_brewster_keeps_separate_internal_returns() { let direction = Vec3::new(3.0, 0.0, -2.0) / 13.0f64.sqrt(); let material = DielectricOptions { + shadow_transmission: false, + subsurface: None, // cos(theta_t) = 3/sqrt(13), hence the one-pass distance is 1 mm. thickness_mm: 3.0 / 13.0f64.sqrt(), absorption_per_mm: [2.0f64.ln(), 2.0f64.ln(), 0.0], @@ -539,3 +559,513 @@ fn actual_png_brewster_thin_sheet_matches_reflected_energy() { // maps to 98, so this also detects a consumer still using the old series. assert_eq!(pixel.expect("Brewster sheet fixture must finish"), [95, 95, 95, 255]); } + +fn general_options() -> RaytraceOptions { + RaytraceOptions { + path: Some(crate::job::CpuPathOptions { max_depth: 16 }), + progressive: Some(crate::job::CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }), + dielectrics: vec![input(DielectricBoundary::ClosedMesh)], + ..Default::default() + } +} +fn general_certificate(scene: &ProductScene, options: &RaytraceOptions) -> crate::job::Result { + let mut certificate = super::super::glass_mesh::Task::new(scene, options)?; + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1_000_000).unwrap(); + for _ in 0..1_000_000 { + if certificate.ready() { + return Ok(certificate); + } + let before = work.used(); + certificate.step(scene, options, &mut work, &cancel)?; + assert_eq!(work.used() - before, 1, "every real certificate transition has one cumulative debit"); + } + panic!("bounded exact certificate did not finish") +} +#[test] +fn general_glass_exact_triangle_contacts_preserve_only_real_shared_simplexes() { + let a = [Vec3::ZERO, Vec3::X, Vec3::Y]; + let cross = [Vec3::new(0.25, 0.25, -1.0), Vec3::new(0.25, 0.25, 1.0), Vec3::new(1.0, 1.0, 1.0)]; + let overlap = [Vec3::new(0.25, 0.25, 0.0), Vec3::new(0.75, 0.25, 0.0), Vec3::new(0.25, 0.75, 0.0)]; + let adjacent = [Vec3::X, Vec3::ZERO, -Vec3::Y]; + let folded = [Vec3::X, Vec3::ZERO, Vec3::Z]; + let vertex = [Vec3::ZERO, -Vec3::X, -Vec3::Y]; + let apart = [Vec3::new(0.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(0.0, 1.0, 1.0)]; + for b in [cross, overlap, a] { + assert!(super::super::glass_mesh::forbidden_contact(a, b, true)); + } + for b in [adjacent, folded, vertex, apart] { + assert!(!super::super::glass_mesh::forbidden_contact(a, b, true)); + } + for b in [adjacent, folded, vertex] { + assert!(super::super::glass_mesh::forbidden_contact(a, b, false), "another body's contact is never a shared simplex"); + } + let almost = apart.map(|p| Vec3::new(p.x, p.y, f64::from_bits((1023 - 100) << 52))); + assert!(!super::super::glass_mesh::forbidden_contact(a, almost, false), "no epsilon turns a real gap into contact"); +} +#[test] +fn general_glass_certifies_rotated_closed_mesh_and_rejects_open_inward_and_crossed_shells() { + let mut body = box_body(2.0); + for p in &mut Arc::make_mut(&mut body.mesh).positions { + let (x, y) = (p.x, p.y); + p.x = (x - y) * std::f64::consts::FRAC_1_SQRT_2; + p.y = (x + y) * std::f64::consts::FRAC_1_SQRT_2; + } + assert!(certify(&scene(body.clone()), &input(DielectricBoundary::ClosedBox)).is_err()); + general_certificate(&scene(body.clone()), &general_options()).unwrap(); + let mut open = body.clone(); + Arc::make_mut(&mut open.mesh).triangles.pop(); + let error = general_certificate(&scene(open), &general_options()).err().unwrap(); + assert!(error.message.contains("closed edges") || error.message.contains("two oppositely"), "{error}"); + // Retain the actual independent winding and contact oracles, not only a broad failure. + let mut inward = body; + for t in &mut Arc::make_mut(&mut inward.mesh).triangles { + t.swap(1, 2); + } + assert!(general_certificate(&scene(inward), &general_options()).err().unwrap().message.contains("outward")); + let mut crossed = box_body(2.0); + Arc::make_mut(&mut crossed.mesh).positions[7] = Vec3::new(0.0, 0.0, -1.0); + assert!(general_certificate(&scene(crossed), &general_options()).err().unwrap().message.contains("intersect")); +} +#[test] +fn general_glass_vertex_link_refuses_a_pinch_even_with_two_faces_per_edge_and_one_shell() { + let mut body = box_body(2.0); + let mesh = Arc::make_mut(&mut body.mesh); + let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 4, 6, 2], [1, 3, 7, 5], [0, 1, 5, 4], [2, 6, 7, 3]]; + mesh.triangles.clear(); + for q in quads { + let center = q.map(|i| mesh.positions[i]).into_iter().fold(Vec3::ZERO, |s, p| s + p) * 0.25; + let n = mesh.positions.len() as u32; + mesh.positions.push(center); + for i in 0..4 { + mesh.triangles.push([n, q[i] as u32, q[(i + 1) % 4] as u32]); + } + } + // These opposite corners have disjoint edge neighbors in this triangulation. + // Coinciding them preserves edge2 and global connectivity but creates two links. + mesh.positions[7] = mesh.positions[0]; + let error = general_certificate(&scene(body), &general_options()).err().unwrap(); + assert!(error.message.contains("vertex link"), "the vertex certificate must catch the pinch before generic contact checks: {error}"); +} +#[test] +fn general_glass_nested_parents_are_certified_not_inferred_from_overlapping_bounds() { + let outer = box_body(4.0); + let mut inner = box_body(2.0); + inner.name = "inner".into(); + for p in &mut Arc::make_mut(&mut inner.mesh).positions { + p.x *= 0.5; + p.y *= 0.5; + p.z += 1.0; + } + let mut scene = scene(outer); + scene.meshes.push(inner); + let mut options = general_options(); + let mut input = options.dielectrics[0].clone(); + input.body_index = 1; + input.body_name = "inner".into(); + options.dielectrics.push(input); + let certificate = general_certificate(&scene, &options).unwrap(); + assert_eq!(certificate.region(0).unwrap().parent, None); + assert_eq!(certificate.region(1).unwrap().parent, Some(0)); + Arc::make_mut(&mut scene.meshes[1].mesh).positions.iter_mut().for_each(|p| p.z -= 1.0); + let error = general_certificate(&scene, &options).err().unwrap(); + assert!(error.message.contains("touch") || error.message.contains("intersect"), "{error}"); +} +#[test] +fn general_glass_certificate_cancel_and_exhaustion_never_publish_a_partial_proof() { + let scene = scene(box_body(2.0)); + let options = general_options(); + let cancel = CancelToken::default(); + let mut certificate = super::super::glass_mesh::Task::new(&scene, &options).unwrap(); + let mut work = super::super::WorkBudget::new(1).unwrap(); + certificate.step(&scene, &options, &mut work, &cancel).unwrap(); + assert!(!certificate.ready()); + assert_eq!(certificate.step(&scene, &options, &mut work, &cancel).unwrap_err().code, crate::job::ErrorCode::LimitExceeded); + assert!(!certificate.ready()); + cancel.cancel(); + assert_eq!(certificate.step(&scene, &options, &mut work, &cancel).unwrap_err().code, crate::job::ErrorCode::Cancelled); + assert!(!certificate.ready()); +} + +#[test] +fn general_glass_uses_smooth_optical_normals_only_with_correct_geometric_crossings() { + let geometric = Vec3::Z; + let direction = -Vec3::Z; + let smooth = unit(Vec3::new(0.2, 0.0, 0.96)).unwrap(); + let (actual, normal) = shaded_interface(direction, geometric, smooth, 1.0, 1.5).unwrap(); + assert!((normal - smooth).len() < 1e-14); + assert!((actual.transmitted.unwrap() - interface(direction, smooth, 1.0, 1.5).unwrap().transmitted.unwrap()).len() < 1e-14); + assert_ne!(actual.transmitted, interface(direction, geometric, 1.0, 1.5).unwrap().transmitted); + let folded = unit(Vec3::new(0.99, 0.0, 0.01)).unwrap(); + let (actual, normal) = shaded_interface(direction, geometric, folded, 1.0, 1.5).unwrap(); + assert_eq!(normal, geometric); + assert_eq!(actual.transmitted, Some(direction)); + for ni in [1.0, 1.5] { + for nt in [1.0, 1.5] { + let (i, _) = shaded_interface(direction, geometric, folded, ni, nt).unwrap(); + assert!(i.reflected.dot(geometric) > 0.0); + if let Some(t) = i.transmitted { + assert!(t.dot(geometric) < 0.0); + } + } + } +} + +#[test] +fn general_glass_exact_dyadic_volume_has_translation_and_winding_invariant_sign_at_cancellation_scales() { + for offset in [Vec3::ZERO, Vec3::new(1e12 - 1024.0, -1e12 + 1024.0, 1e12 - 1024.0)] { + let mut body = box_body(0.125); + let mesh = Arc::make_mut(&mut body.mesh); + for p in &mut mesh.positions { + *p += offset; + } + for reverse in [false, true] { + let mut signed = super::super::glass_volume::SignedVolume::default(); + for face in &mesh.triangles { + let mut p = face.map(|i| mesh.positions[i as usize]); + if reverse { + p.swap(1, 2); + } + for term in 0..6 { + signed.add_term(p, term).unwrap(); + } + } + assert_eq!(signed.positive(), !reverse, "a 0.125mm closed slab remains outward at large world coordinates"); + } + } + let mut exact = super::super::glass_volume::SignedVolume::default(); + let p = [Vec3::new(0.25, 0.5, 0.75), Vec3::new(1.0, 0.5, 0.75), Vec3::new(0.25, 1.0, 0.75)]; + for t in 0..6 { + exact.add_term(p, t).unwrap(); + } + let reversed = [p[0], p[2], p[1]]; + for t in 0..6 { + exact.add_term(reversed, t).unwrap(); + } + assert!(!exact.positive(), "exact opposite oriented terms cancel to zero, never a rounded positive shell"); +} + +#[test] +fn general_glass_absence_preserves_the_original_runtime_optics_wire_and_explicit_legacy_gate() { + let old = input(DielectricBoundary::ClosedBox); + assert_eq!( + serde_json::to_string(&old).unwrap(), + r#"{"body_index":0,"body_name":"captured slab@occurrence-2","boundary":"closed_box","ior":1.5,"absorption_per_mm":[0.0,0.0,0.0],"thickness_mm":0.0}"# + ); + let mut options = RaytraceOptions { dielectrics: vec![old.clone()], ..Default::default() }; + options.validate().unwrap(); + let before = options.clone(); + options.dielectrics[0].boundary = DielectricBoundary::ClosedMesh; + assert!(options.validate().unwrap_err().message.contains("Indirect lighting")); + options.dielectrics[0] = old; + assert_eq!(options, before); +} + +#[test] +fn general_glass_origin_winding_is_half_open_at_projected_edges_vertices_and_silhouettes() { + let body = box_body(2.0); + let crossing = |p: Vec3| { + body.mesh + .triangles + .iter() + .map(|indices| super::super::glass_mesh::origin_crossing(indices.map(|i| body.mesh.positions[i as usize]), p)) + .try_fold(0_i32, |sum, n| n.map(|n| sum + i32::from(n))) + }; + for p in [Vec3::new(0.0, 0.0, 1.0), Vec3::new(9.0, 9.0, 1.0), Vec3::new(-9.0, -9.0, 0.5)] { + assert_eq!(crossing(p).unwrap(), 1, "inside {p:?}"); + } + // Positive-X rays deliberately pass through an entire triangle diagonal, + // a shared vertex line or a silhouette. No jitter/retry is permitted. + for p in + [Vec3::new(-20.0, 0.0, 1.0), Vec3::new(20.0, 0.0, 1.0), Vec3::new(-20.0, 10.0, 2.0), Vec3::new(-20.0, 10.0, 1.0), Vec3::new(0.0, 0.0, 3.0)] + { + assert_eq!(crossing(p).unwrap(), 0, "outside half-open query {p:?}"); + } + for p in [Vec3::new(10.0, 0.0, 1.0), Vec3::new(10.0, 10.0, 1.0), Vec3::new(10.0, 10.0, 2.0)] { + assert!(crossing(p).unwrap_err().message.contains("exactly on"), "boundary {p:?} must never be guessed as air"); + } +} + +#[test] +fn general_glass_origin_segment_contact_includes_complete_crossings_touches_and_coplanar_motion() { + let triangle = [Vec3::new(0.0, -2.0, -2.0), Vec3::new(0.0, 2.0, -2.0), Vec3::new(0.0, 0.0, 2.0)]; + let contact = |a, b| super::super::glass_mesh::origin_segment_contact(triangle, a, b).unwrap(); + assert!(contact(Vec3::new(-1.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0)), "both endpoints can be outside while the near segment crosses a boundary"); + assert!(contact(Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO), "a boundary at the clipped endpoint is included"); + assert!(contact(Vec3::new(0.0, -4.0, 0.0), Vec3::new(0.0, 4.0, 0.0)), "coplanar motion can touch or cross a boundary"); + assert!(!contact(Vec3::new(-1.0, 4.0, 0.0), Vec3::new(1.0, 4.0, 0.0))); + assert!(!contact(Vec3::new(-2.0, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0))); +} + +#[test] +fn cpu_subsurface_runtime_intent_is_bounded_closed_path_only_and_inactive_values_stay_authored() { + use crate::transmission::subsurface::Subsurface; + let mut options = RaytraceOptions { + path: Some(job::CpuPathOptions { max_depth: 4 }), + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }), + dielectrics: vec![input(DielectricBoundary::ClosedMesh)], + ..Default::default() + }; + options.dielectrics[0].subsurface = Some(Subsurface { scattering_per_mm: 0.0, anisotropy: 0.95 }); + options.denoise = true; + options.validate().unwrap(); + let json = serde_json::to_value(&options).unwrap(); + assert_eq!(json["dielectrics"][0]["subsurface"]["scattering_per_mm"], 0.0); + assert_eq!(serde_json::from_value::(json.clone()).unwrap(), options); + options.dielectrics[0].subsurface.as_mut().unwrap().scattering_per_mm = 0.5; + assert!(options.validate().unwrap_err().message.contains("denois")); + options.denoise = false; + options.validate().unwrap(); + options.path = None; + assert!(options.validate().unwrap_err().message.contains("subsurface")); + options.path = Some(job::CpuPathOptions { max_depth: 4 }); + options.dielectrics[0].boundary = DielectricBoundary::ThinSheet; + assert!(options.validate().unwrap_err().message.contains("closed")); + options.dielectrics[0].boundary = DielectricBoundary::ClosedMesh; + for rate in [-1.0, f64::NAN, f64::INFINITY, 100.001] { + options.dielectrics[0].subsurface.as_mut().unwrap().scattering_per_mm = rate; + assert!(options.validate().is_err()); + } + assert_eq!(json["dielectrics"][0]["subsurface"]["anisotropy"], 0.95); +} + +/// A separate barycentric tiler. Constant coordinates stay exactly on their +/// analytic face; each replaced triangle is three non-overlapping triangles. +fn tiled_certificate_box(count: usize) -> ProductMesh { + assert!(count >= 12 && count.is_multiple_of(2)); + let mut body = box_body(2.0); + let mesh = Arc::make_mut(&mut body.mesh); + while mesh.triangles.len() < count { + let split = ((count - mesh.triangles.len()) / 2).min(mesh.triangles.len()); + let old = std::mem::take(&mut mesh.triangles); + for (index, t) in old.into_iter().enumerate() { + if index >= split { + mesh.triangles.push(t); + continue; + } + let [a, b, c] = t.map(|i| mesh.positions[i as usize]); + let centre = |a: f64, b: f64, c: f64| if a == b && b == c { a } else { (a + b + c) / 3.0 }; + let point = Vec3::new(centre(a.x, b.x, c.x), centre(a.y, b.y, c.y), centre(a.z, b.z, c.z)); + let at = mesh.positions.len() as u32; + mesh.positions.push(point); + mesh.triangles.extend([[t[0], t[1], at], [t[1], t[2], at], [t[2], t[0], at]]); + } + } + assert_eq!(mesh.triangles.len(), count); + body +} + +fn bounded_box_certificate(body: &ProductMesh) -> super::super::Result { + let mut task = super::super::box_certificate::BoxTask::new(body.mesh.triangles.len())?; + assert_eq!(task.allocated_bytes(), super::super::box_certificate::BoxTask::required_bytes(body.mesh.triangles.len())?); + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(super::super::MAX_WORK)?; + while task.result().is_err() { + let before = work.used(); + task.step(&body.mesh, &mut work, &cancel)?; + assert_eq!(work.used() - before, 1, "every real box continuation has one debit"); + } + let n = body.mesh.triangles.len() as u64; + let logarithm = u64::from((n * 3).next_power_of_two().ilog2()); + assert!(work.used() <= 6 * n * logarithm + 16 * n + 32, "bounded merge/search work cannot become an all-pairs proof"); + task.result() +} + +#[test] +fn bounded_box_certificate_matches_original_main_oracle_tilings_rejections_and_raw_signed_zero() { + let compare = |body: ProductMesh| { + let original = certify(&scene(body.clone()), &input(DielectricBoundary::ClosedBox)); + let actual = bounded_box_certificate(&body); + match (original, actual) { + (Ok(Certificate::ClosedBox(a)), Ok(b)) => { + for (a, b) in [a.min(), a.max()].into_iter().zip([b.min(), b.max()]) { + assert_eq!([a.x, a.y, a.z].map(f64::to_bits), [b.x, b.y, b.z].map(f64::to_bits)); + } + } + (Err(a), Err(b)) => assert_eq!(a, b, "same precise refusal, not a generic unsupported fallback"), + _ => panic!("bounded and original strict box decisions differ"), + } + }; + for count in [12, 14, 36, 108, 324] { + for offset in [Vec3::ZERO, Vec3::new(1e12 - 64.0, 1e12 - 64.0, 1e12 - 64.0), Vec3::new(-1e12 + 64.0, -1e12 + 64.0, -1e12 + 64.0)] { + let mut body = tiled_certificate_box(count); + Arc::make_mut(&mut body.mesh).positions.iter_mut().for_each(|p| *p += offset); + compare(body.clone()); + let mut open = body.clone(); + Arc::make_mut(&mut open.mesh).triangles.pop(); + compare(open); + let mut duplicate = body.clone(); + let mesh = Arc::make_mut(&mut duplicate.mesh); + mesh.triangles.push(mesh.triangles[0]); + compare(duplicate); + let mut inward = body.clone(); + Arc::make_mut(&mut inward.mesh).triangles[0].swap(1, 2); + compare(inward); + let mut warped = body; + Arc::make_mut(&mut warped.mesh).positions[0].z += 0.125; + compare(warped); + } + } + let mut negative = tiled_certificate_box(36); + for p in &mut Arc::make_mut(&mut negative.mesh).positions { + if p.z == 0.0 { + p.z = -0.0; + } + } + compare(negative.clone()); + let mesh = Arc::make_mut(&mut negative.mesh); + let original = mesh.triangles[0][0] as usize; + let mut changed = mesh.positions[original]; + changed.z = 0.0; + let at = mesh.positions.len() as u32; + mesh.positions.push(changed); + mesh.triangles[0][0] = at; + assert!(certify(&scene(negative.clone()), &input(DielectricBoundary::ClosedBox)).is_err(), "raw signed-zero seams are not silently welded"); + compare(negative); +} + +#[test] +fn bounded_box_certificate_keeps_the_full_65536_triangle_domain_and_exact_scratch() { + let body = tiled_certificate_box(MAX_BOX_TRIANGLES); + let expected = certify(&scene(body.clone()), &input(DielectricBoundary::ClosedBox)).unwrap(); + let actual = bounded_box_certificate(&body).unwrap(); + let Certificate::ClosedBox(expected) = expected else { panic!("box oracle") }; + assert_eq!((actual.min(), actual.max()), (expected.min(), expected.max())); + assert_eq!((actual.min(), actual.max()), (Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 2.0))); + assert!(super::super::box_certificate::BoxTask::required_bytes(MAX_BOX_TRIANGLES + 1).is_err()); +} + +#[test] +fn bounded_box_certificate_cancel_and_work_exhaustion_freeze_every_phase_without_a_partial_proof() { + let body = tiled_certificate_box(36); + for phase in ["load", "edges", "sort", "duplicates", "reverse", "area"] { + let mut task = super::super::box_certificate::BoxTask::new(36).unwrap(); + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(super::super::MAX_WORK).unwrap(); + while task.phase() != phase { + task.step(&body.mesh, &mut work, &cancel).unwrap(); + } + let before = (task.fingerprint(), task.allocated_bytes(), work.used()); + let mut exhausted = super::super::WorkBudget::new(1).unwrap(); + exhausted.charge(1, &cancel).unwrap(); + assert_eq!(task.step(&body.mesh, &mut exhausted, &cancel).unwrap_err(), super::super::TraceError::WorkLimit); + assert_eq!((task.fingerprint(), task.allocated_bytes(), work.used()), before); + assert!(task.result().is_err()); + cancel.cancel(); + assert_eq!(task.step(&body.mesh, &mut work, &cancel).unwrap_err(), super::super::TraceError::Cancelled); + assert_eq!((task.fingerprint(), task.allocated_bytes(), work.used()), before); + assert!(task.result().is_err()); + } +} + +#[test] +fn general_path_declared_tiled_box_reuses_complete_certificate_without_extra_triangle_scratch() { + let mut options = general_options(); + let body = tiled_certificate_box(108); + let mut captured = scene(body); + let mesh_bytes = super::super::glass_mesh::Task::required_bytes(&captured, &options).unwrap(); + let mesh_proof = general_certificate(&captured, &options).unwrap(); + options.dielectrics[0].boundary = DielectricBoundary::ClosedBox; + assert_eq!( + super::super::glass_mesh::Task::required_bytes(&captured, &options).unwrap(), + mesh_bytes, + "the existing exact manifold/contact certificate pays the same scratch for a declared box" + ); + let box_proof = general_certificate(&captured, &options).unwrap(); + assert_eq!(box_proof.region(0).unwrap().bounds.min(), mesh_proof.region(0).unwrap().bounds.min()); + assert_eq!(box_proof.region(0).unwrap().bounds.max(), mesh_proof.region(0).unwrap().bounds.max()); + // Captured ordinal+name is the identity. Another body carrying that same + // name is permitted by main's certifier and must not introduce a new policy. + let mut unrelated = box_body(2.0); + Arc::make_mut(&mut unrelated.mesh).positions.iter_mut().for_each(|p| p.x += 100.0); + captured.meshes.push(unrelated); + general_certificate(&captured, &options).unwrap(); + let mut malformed = captured.clone(); + Arc::make_mut(&mut malformed.meshes[0].mesh).positions[0].z += 0.125; + let error = general_certificate(&malformed, &options).err().unwrap(); + assert_eq!(error.message, "box face is not axis aligned"); +} + +#[test] +fn bounded_box_certificate_matches_main_for_unused_vertices_without_welding_raw_zero() { + let mut body = tiled_certificate_box(36); + // The certificate is a proof of referenced boundary triangles. Main does + // not extend the box, reject, or weld from unused source vertex records. + Arc::make_mut(&mut body.mesh).positions.extend([ + Vec3::new(1e13, -1e13, 1e13), + Vec3::new(f64::NAN, f64::INFINITY, f64::NEG_INFINITY), + Vec3::new(-0.0, 0.0, -0.0), + ]); + let original = certify(&scene(body.clone()), &input(DielectricBoundary::ClosedBox)).unwrap(); + let Certificate::ClosedBox(original) = original else { panic!("box oracle") }; + let actual = bounded_box_certificate(&body).unwrap(); + assert_eq!((actual.min(), actual.max()), (original.min(), original.max())); + assert_eq!((actual.min(), actual.max()), (Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 2.0))); + let mut options = general_options(); + options.dielectrics[0].boundary = DielectricBoundary::ClosedBox; + let captured = scene(body.clone()); + let complete = general_certificate(&captured, &options).unwrap(); + let padded_min = Vec3::new(actual.min().x.next_down(), actual.min().y.next_down(), actual.min().z.next_down()); + let padded_max = Vec3::new(actual.max().x.next_up(), actual.max().y.next_up(), actual.max().z.next_up()); + assert_eq!((complete.region(0).unwrap().bounds.min(), complete.region(0).unwrap().bounds.max()), (padded_min, padded_max)); + assert!(padded_min.x < actual.min().x && padded_min.y < actual.min().y && padded_min.z < actual.min().z); + assert!(padded_max.x > actual.max().x && padded_max.y > actual.max().y && padded_max.z > actual.max().z); + let mut closed_mesh = options.clone(); + closed_mesh.dielectrics[0].boundary = DielectricBoundary::ClosedMesh; + let prior_mesh_policy = general_certificate(&captured, &closed_mesh).unwrap(); + assert_eq!( + (complete.region(0).unwrap().bounds.min(), complete.region(0).unwrap().bounds.max()), + (prior_mesh_policy.region(0).unwrap().bounds.min(), prior_mesh_policy.region(0).unwrap().bounds.max()), + "declaring Box preserves the existing padded general-mesh region ABI" + ); + // Making an invalid previously-unused record part of the boundary must + // still produce the original strict refusal; it is never sanitised. + let mesh = Arc::make_mut(&mut body.mesh); + let invalid = (mesh.positions.len() - 2) as u32; + mesh.triangles[0][0] = invalid; + let expected = certify(&scene(body.clone()), &input(DielectricBoundary::ClosedBox)).unwrap_err(); + assert_eq!(bounded_box_certificate(&body).unwrap_err(), expected); +} + +#[test] +fn general_box_axis_planes_undo_only_single_ulp_padding_and_keep_raw_zero_endpoints() { + use super::super::Triangle; + // This tests Triangle's bounding arithmetic over finite IEEE values, not a + // broader glass predicate domain. Subnormal referenced coordinates remain + // outside GeneralPath's separate, unchanged exact-certificate domain. + let minimum = f64::from_bits(1); + for value in [-1e12, -1e-300, -minimum, -0.0, 0.0, minimum, 1e-300, 1e12] { + let points = [Vec3::new(-1.0, -1.0, value), Vec3::new(1.0, -1.0, value), Vec3::new(0.0, 1.0, value)]; + let triangle = Triangle::new(points).unwrap(); + let padded = triangle.bounds(); + assert_eq!(padded.min().z.to_bits(), value.next_down().to_bits()); + assert_eq!(padded.max().z.to_bits(), value.next_up().to_bits()); + let low = padded.min().z.next_up(); + let high = padded.max().z.next_down(); + assert_eq!(low, value); + assert_eq!(high, value); + if value != 0.0 { + assert_eq!(low.to_bits(), value.to_bits()); + assert_eq!(high.to_bits(), value.to_bits()); + } + assert!(triangle.vertices().iter().all(|point| point.z.to_bits() == value.to_bits()), "bounds never rewrite signed endpoint bits"); + } + for negative in [false, true] { + let mut body = tiled_certificate_box(36); + for point in &mut Arc::make_mut(&mut body.mesh).positions { + if point.z == 0.0 { + point.z = if negative { -0.0 } else { 0.0 }; + } + } + let captured = scene(body); + let raw = certify(&captured, &input(DielectricBoundary::ClosedBox)).unwrap(); + let mut options = general_options(); + options.dielectrics[0].boundary = DielectricBoundary::ClosedBox; + let complete = general_certificate(&captured, &options).unwrap(); + let Certificate::ClosedBox(raw) = raw else { panic!("raw box oracle") }; + assert_eq!(complete.region(0).unwrap().bounds.min().z, raw.min().z.next_down()); + assert_eq!(complete.region(0).unwrap().bounds.max().z, raw.max().z.next_up()); + let bits = if negative { (-0.0_f64).to_bits() } else { 0.0_f64.to_bits() }; + assert!(captured.meshes[0].mesh.positions.iter().filter(|point| point.z == 0.0).all(|point| point.z.to_bits() == bits)); + } +} diff --git a/crates/render/src/raytrace/environment_image_tests.rs b/crates/render/src/raytrace/environment_image_tests.rs index ba23acf3f..de52a6c8b 100644 --- a/crates/render/src/raytrace/environment_image_tests.rs +++ b/crates/render/src/raytrace/environment_image_tests.rs @@ -129,7 +129,8 @@ fn centre(png: &[u8]) -> [u8; 4] { #[test] fn progressive_hdr_and_rough_reflections_keep_the_same_absolute_prefix_at_every_quantum() { - for (target, checkpoints) in [(3, vec![1, 2]), (7, vec![1, 2, 4])] { + for target in [3, 7] { + let checkpoints: Vec<_> = (1..target).collect(); let result = progressive_hdr_png(target, 82, 1, Some(input())); assert_eq!(result.previews.iter().map(|(n, _)| *n).collect::>(), checkpoints); let other = progressive_hdr_png(target, 82, 16384, Some(input())); diff --git a/crates/render/src/raytrace/glass_mesh.rs b/crates/render/src/raytrace/glass_mesh.rs new file mode 100644 index 000000000..941fc55f3 --- /dev/null +++ b/crates/render/src/raytrace/glass_mesh.rs @@ -0,0 +1,859 @@ +//! 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 +//! permitted only along the same body's actual shared topological simplex. +use super::{Bounds, Triangle, WorkBudget}; +use crate::{ + ProductScene, + job::{self, CancelToken, DielectricBoundary, RaytraceOptions}, +}; +use robust::{Coord, Coord3D, orient2d, orient3d}; +use solidcore_record::Vec3; +use std::mem::size_of; + +fn invalid(message: &str) -> job::JobError { + job::JobError::new(job::ErrorCode::InvalidScene, message) +} +fn memory() -> job::JobError { + job::JobError::new(job::ErrorCode::LimitExceeded, "CPU glass certification memory exceeds admission") +} +fn reserved(n: usize) -> job::Result> { + let mut values = Vec::new(); + values.try_reserve_exact(n).map_err(|_| job::JobError::new(job::ErrorCode::AllocationFailed, "CPU glass certification allocation failed"))?; + if values.capacity() != n { + return Err(memory()); + } + Ok(values) +} +// Keep adaptive determinant expansions away from IEEE underflow. This is a +// conservative certificate domain, not a snap tolerance or a changed ray bound. +// With coordinates in [2^-128, 1e12] (or exactly zero), each nonzero f64 +// difference is at least 2^-180 and the degree-three expansion products remain +// normal. Original legacy optics have no new coordinate restriction. +fn predicate_domain(points: &[Vec3]) -> job::Result<()> { + let minimum = f64::from_bits((1023 - 128) << 52); + if points.iter().flat_map(|p| [p.x, p.y, p.z]).any(|v| !v.is_finite() || v.abs() > super::MAX_COORDINATE_MM || (v != 0.0 && v.abs() < minimum)) { + return Err(invalid("CPU exact glass certificate requires zero or coordinate magnitudes at least 2^-128 mm within the existing world bound")); + } + Ok(()) +} +fn point(p: Vec3) -> Coord3D { + Coord3D { x: p.x, y: p.y, z: p.z } +} +fn side(t: [Vec3; 3], p: Vec3) -> f64 { + orient3d(point(t[0]), point(t[1]), point(t[2]), point(p)) +} +fn key(p: Vec3) -> [u64; 3] { + [p.x, p.y, p.z].map(|v| if v == 0.0 { 0 } else { v.to_bits() }) +} +fn target_key(p: Vec3, medium: usize, options: &RaytraceOptions) -> job::Result<[u64; 3]> { + let input = options.dielectrics.get(medium).ok_or_else(|| invalid("CPU glass coordinate target"))?; + Ok(if input.boundary == DielectricBoundary::ClosedBox { [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()] } else { key(p) }) +} +fn same(a: Vec3, b: Vec3) -> bool { + key(a) == key(b) +} +fn projection(t: [Vec3; 3]) -> usize { + for drop in 0..3 { + let q = t.map(|p| project(p, drop)); + if orient2d(q[0], q[1], q[2]) != 0.0 { + return drop; + } + } + 2 +} +fn project(p: Vec3, drop: usize) -> Coord { + match drop { + 0 => Coord { x: p.y, y: p.z }, + 1 => Coord { x: p.z, y: p.x }, + _ => Coord { x: p.x, y: p.y }, + } +} +fn in_triangle(t: [Vec3; 3], p: Vec3, drop: usize) -> bool { + let q = t.map(|p| project(p, drop)); + let p = project(p, drop); + let s = [orient2d(q[0], q[1], p), orient2d(q[1], q[2], p), orient2d(q[2], q[0], p)]; + !s.iter().any(|v| *v < 0.0) || !s.iter().any(|v| *v > 0.0) +} +fn on_segment(a: Coord, b: Coord, p: Coord) -> bool { + orient2d(a, b, p) == 0.0 && p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y) +} +fn opposite(a: f64, b: f64) -> bool { + (a < 0.0 && b > 0.0) || (a > 0.0 && b < 0.0) +} +fn shared_vertex(p: Vec3, a: [Vec3; 3], b: [Vec3; 3]) -> bool { + a.into_iter().any(|x| same(x, p)) && b.into_iter().any(|x| same(x, p)) +} +fn coplanar_edge_bad(edges: [[Vec3; 2]; 2], triangles: [[Vec3; 3]; 2], allow_shared: bool, drop: usize) -> bool { + let [[a, b], [c, d]] = edges; + let [ta, tb] = triangles; + let [pa, pb, pc, pd] = [a, b, c, d].map(|p| project(p, drop)); + let s = [orient2d(pa, pb, pc), orient2d(pa, pb, pd), orient2d(pc, pd, pa), orient2d(pc, pd, pb)]; + if opposite(s[0], s[1]) && opposite(s[2], s[3]) { + return true; + } + for (p, q, r) in [(a, pc, pd), (b, pc, pd), (c, pa, pb), (d, pa, pb)] { + if on_segment(q, r, project(p, drop)) && (!allow_shared || !shared_vertex(p, ta, tb)) { + return true; + } + } + // If collinear overlap has positive length, it is legal only for the exact + // shared topological edge, not two incident edges extending the same way. + if s.into_iter().all(|v| v == 0.0) { + let axis_x = (pa.x - pb.x).abs() >= (pa.y - pb.y).abs(); + let value = |p: Coord| if axis_x { p.x } else { p.y }; + let lo = value(pa).min(value(pb)).max(value(pc).min(value(pd))); + let hi = value(pa).max(value(pb)).min(value(pc).max(value(pd))); + if lo < hi && !(allow_shared && ((same(a, c) && same(b, d)) || (same(a, d) && same(b, c)))) { + return true; + } + } + false +} +/// True if the two exact triangles meet beyond their permitted shared simplex. +/// This uses signs of adaptive exact predicates; no distance/angle tolerance. +pub(super) fn forbidden_contact(a: [Vec3; 3], b: [Vec3; 3], allow_shared: bool) -> bool { + let sa = a.map(|p| side(b, p)); + let sb = b.map(|p| side(a, p)); + if sa.iter().all(|v| *v > 0.0) || sa.iter().all(|v| *v < 0.0) || sb.iter().all(|v| *v > 0.0) || sb.iter().all(|v| *v < 0.0) { + return false; + } + let common = a.iter().filter(|p| b.iter().any(|q| same(**p, *q))).count(); + if common == 3 { + return true; + } + for (t, u, s) in [(a, b, sa), (b, a, sb)] { + let drop = projection(u); + for (p, sign) in t.into_iter().zip(s) { + if sign == 0.0 && in_triangle(u, p, drop) && (!allow_shared || !shared_vertex(p, a, b)) { + return true; + } + } + for (i, j) in [(0, 1), (1, 2), (2, 0)] { + let p = t[i]; + let q = t[j]; + if opposite(s[i], s[j]) { + let w = [side([p, q, u[0]], u[1]), side([p, q, u[1]], u[2]), side([p, q, u[2]], u[0])]; + if !w.iter().any(|v| *v < 0.0) || !w.iter().any(|v| *v > 0.0) { + return true; + } + } else if s[i] == 0.0 && s[j] == 0.0 { + for (k, l) in [(0, 1), (1, 2), (2, 0)] { + if coplanar_edge_bad([[p, q], [u[k], u[l]]], [a, b], allow_shared, drop) { + return true; + } + } + } + } + } + false +} +#[derive(Clone, Copy)] +struct Face { + p: [Vec3; 3], + medium: usize, +} +#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] +struct Edge { + medium: usize, + a: [u64; 3], + b: [u64; 3], + face: usize, + forward: bool, +} +#[derive(Clone, Copy)] +pub(super) struct Region { + pub bounds: Bounds, + pub parent: Option, + begin: usize, + end: usize, + pub primitive_begin: usize, + pub primitive_end: usize, +} +impl Default for Region { + fn default() -> Self { + Self { bounds: Bounds::empty(), parent: None, begin: 0, end: 0, primitive_begin: 0, primitive_end: 0 } + } +} +#[derive(Clone, Copy)] +enum Stage { + Index, + Load, + BoxAxes, + Edges, + Sort, + Pairs, + Connected, + CornerInit, + CornerEdges, + CornerRecords, + VertexLinks, + Contact, + Sources, + Volume, + Parents, + Convex, + Inside, + Done, +} +/// All vectors reserve their admitted exact capacity before preparation begins. +/// Sorting is an iterative merge: a continuation copies at most one edge. +pub(super) struct Task { + faces: Vec, + edges: Vec, + scratch: Vec, + parents: Vec, + ranks: Vec, + regions: [Region; 8], + count: usize, + stage: Stage, + vertex_sort: bool, + medium: usize, + triangle: usize, + i: usize, + j: usize, + width: usize, + begin: usize, + left: usize, + right: usize, + end: usize, + out: usize, + pair: (usize, usize), + vertex: usize, + outer: usize, + inner: usize, + volume: super::glass_volume::SignedVolume, +} +fn selected_count(scene: &ProductScene, options: &RaytraceOptions) -> job::Result { + 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)?; + } + } + if count as u64 > options.budget.limits().max_triangles { + return Err(memory()); + } + Ok(count) +} +impl Task { + pub(super) fn required_bytes(scene: &ProductScene, options: &RaytraceOptions) -> job::Result { + let n = selected_count(scene, options)?; + n.checked_mul(size_of::() + 6 * size_of::() + 3 * size_of::() + 3 * size_of::()) + .and_then(|n| n.checked_add(size_of::())) + .and_then(|n| u64::try_from(n).ok()) + .ok_or_else(memory) + } + pub(super) fn new(scene: &ProductScene, options: &RaytraceOptions) -> job::Result { + options.validate()?; + let n = selected_count(scene, options)?; + let edges = n.checked_mul(3).ok_or_else(memory)?; + Ok(Self { + faces: reserved(n)?, + edges: reserved(edges)?, + scratch: reserved(edges)?, + parents: reserved(edges)?, + ranks: reserved(edges)?, + regions: [Region::default(); 8], + count: options.dielectrics.len(), + stage: Stage::Index, + vertex_sort: false, + medium: 0, + triangle: 0, + i: 0, + j: 1, + width: 1, + begin: 0, + left: 0, + right: 0, + end: 0, + out: 0, + pair: (0, 1), + vertex: 0, + outer: 0, + inner: 0, + volume: Default::default(), + }) + } + pub(super) fn ready(&self) -> bool { + matches!(self.stage, Stage::Done) + } + pub(super) fn region(&self, index: usize) -> job::Result { + self.regions.get(index).copied().filter(|_| self.ready()).ok_or_else(|| invalid("CPU glass certificate missing")) + } + fn root(&self, mut n: usize) -> job::Result { + // Union by rank bounds the tree by log2(number of corners). The explicit bound also protects + // malformed private state; every parent chase is finite and cancellable + // at the surrounding per-edge continuation. + for _ in 0..64 { + let p = *self.parents.get(n).ok_or_else(|| invalid("CPU glass component index"))?; + if p == n { + return Ok(n); + } + n = p; + } + Err(invalid("CPU glass component chain exceeds its bounded certificate")) + } + fn join(&mut self, ra: usize, rb: usize) -> job::Result<()> { + if ra != rb { + let ar = *self.ranks.get(ra).ok_or_else(|| invalid("CPU glass union rank"))?; + let br = *self.ranks.get(rb).ok_or_else(|| invalid("CPU glass union rank"))?; + let (keep, merge) = if ar < br { (rb, ra) } else { (ra, rb) }; + *self.parents.get_mut(merge).ok_or_else(|| invalid("CPU glass union index"))? = keep; + if ar == br { + let r = self.ranks.get_mut(keep).ok_or_else(|| invalid("CPU glass union rank"))?; + *r = r.checked_add(1).ok_or_else(|| invalid("CPU glass union rank overflow"))?; + } + } + Ok(()) + } + fn next_pair(&mut self) { + self.pair.1 += 1; + if self.pair.1 >= self.faces.len() { + self.pair.0 += 1; + self.pair.1 = self.pair.0 + 1; + } + } + pub(super) fn step(&mut self, scene: &ProductScene, options: &RaytraceOptions, work: &mut WorkBudget, cancel: &CancelToken) -> job::Result<()> { + work.tick(cancel).map_err(super::image::error)?; + match self.stage { + Stage::Index => { + if let Some(body) = scene.meshes.get(self.medium) { + for (index, input) in options.dielectrics.iter().enumerate() { + if input.body_index == self.medium { + let region = self.regions.get_mut(index).ok_or_else(|| invalid("CPU glass primitive range"))?; + 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)?; + } + DielectricBoundary::ClosedBox => { + if !(12..=super::dielectric::MAX_BOX_TRIANGLES).contains(&body.mesh.triangles.len()) { + return Err(invalid("unsupported dielectric boundary tessellation")); + } + } + DielectricBoundary::ClosedMesh => {} + } + } + } + self.i = self.i.checked_add(body.mesh.triangles.len()).ok_or_else(memory)?; + self.medium += 1; + } else { + self.i = 0; + self.medium = 0; + self.stage = Stage::Load; + } + } + Stage::Load => { + let Some(input) = options.dielectrics.get(self.medium) else { + self.i = 0; + self.stage = if options.dielectrics.iter().any(|input| input.boundary == DielectricBoundary::ClosedBox) { + Stage::BoxAxes + } else { + Stage::Edges + }; + return Ok(()); + }; + let body = + scene.meshes.get(input.body_index).filter(|b| b.name == input.body_name).ok_or_else(|| invalid("CPU glass target changed"))?; + let region = self.regions.get_mut(self.medium).ok_or_else(|| invalid("CPU glass region index"))?; + if self.triangle == 0 { + region.begin = self.faces.len(); + } + 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")); + } + self.medium += 1; + self.triangle = 0; + return Ok(()); + }; + let mut p = [Vec3::ZERO; 3]; + for (v, index) in p.iter_mut().zip(indices) { + *v = *body.mesh.positions.get(*index as usize).ok_or_else(|| invalid("CPU glass vertex index"))?; + } + predicate_domain(&p)?; + if Triangle::new(p).map_err(super::image::error)?.geometric_normal().is_none() { + 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()); + } + self.parents.push(self.faces.len()); + self.ranks.push(0); + self.faces.push(Face { p, medium: self.medium }); + } + self.triangle += 1; + } + Stage::BoxAxes => { + if let Some(face) = self.faces.get(self.i) { + let input = options.dielectrics.get(face.medium).ok_or_else(|| invalid("CPU box plane target"))?; + if input.boundary == DielectricBoundary::ClosedBox { + let normal = Triangle::new(face.p).map_err(super::image::error)?.geometric_normal().ok_or_else(|| invalid("box normal"))?; + let axis = if normal.x.abs() == 1.0 { + 0 + } else if normal.y.abs() == 1.0 { + 1 + } else if normal.z.abs() == 1.0 { + 2 + } else { + return Err(invalid("box face is not axis aligned")); + }; + let bounds = self.regions.get(face.medium).ok_or_else(|| invalid("CPU box plane bounds"))?.bounds; + let positive = super::component(normal, axis) > 0.0; + // Region bounds union Triangle::bounds, whose finite extrema + // each take exactly one outward representable step. Undo + // only that padding for the raw face-plane comparison; + // keep the stored bounds and raw endpoint edge keys intact. + // The inverse is value-exact, including subnormals. ±0 + // compare equally here; signed-zero topology still uses + // the original referenced coordinates' unchanged bits. + let padded = super::component(if positive { bounds.max() } else { bounds.min() }, axis); + let plane = if positive { padded.next_down() } else { padded.next_up() }; + if face.p.iter().any(|p| super::component(*p, axis) != plane) { + return Err(invalid("box winding or face plane")); + } + self.i += 1; + } else { + self.i = self.regions.get(face.medium).ok_or_else(|| invalid("CPU box skip region"))?.end; + } + } else { + self.i = 0; + self.stage = Stage::Edges; + } + } + Stage::Edges => { + if let Some(face) = self.faces.get(self.i) { + for (a, b) in [(0, 1), (1, 2), (2, 0)] { + let a = target_key(face.p[a], face.medium, options)?; + let b = target_key(face.p[b], face.medium, options)?; + if a == b { + return Err(invalid("CPU glass collapsed edge")); + } + self.edges.push(Edge { medium: face.medium, a: a.min(b), b: a.max(b), face: self.i, forward: a < b }); + self.scratch.push(Edge::default()); + } + self.i += 1; + } else { + self.stage = Stage::Sort; + self.begin = 0; + self.out = 0; + } + } + Stage::Sort => { + if self.width >= self.edges.len() { + self.stage = if self.vertex_sort { Stage::VertexLinks } else { Stage::Pairs }; + self.i = 0; + return Ok(()); + } + if self.out == self.begin { + self.left = self.begin; + self.right = (self.begin + self.width).min(self.edges.len()); + self.end = (self.right + self.width).min(self.edges.len()); + } + let middle = (self.begin + self.width).min(self.edges.len()); + let take_left = self.left < middle && (self.right >= self.end || self.edges.get(self.left) <= self.edges.get(self.right)); + let at = if take_left { + let n = self.left; + self.left += 1; + n + } else { + let n = self.right; + self.right += 1; + n + }; + let value = *self.edges.get(at).ok_or_else(|| invalid("CPU glass merge input"))?; + *self.scratch.get_mut(self.out).ok_or_else(|| invalid("CPU glass merge output"))? = value; + self.out += 1; + if self.out == self.end { + self.begin = self.end; + if self.begin == self.edges.len() { + std::mem::swap(&mut self.edges, &mut self.scratch); + self.width = self.width.checked_mul(2).ok_or_else(memory)?; + self.begin = 0; + self.out = 0; + } + } + } + Stage::Pairs => { + let Some(a) = self.edges.get(self.i).copied() else { + self.stage = Stage::Connected; + 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 ra = self.root(a.face)?; + let rb = self.root(b.face)?; + self.join(ra, rb)?; + self.i += 2; + } + Stage::Connected => { + 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")); + } + self.i += 1; + } else { + self.stage = Stage::CornerInit; + self.i = 0; + } + } + Stage::CornerInit => { + let count = self.faces.len().checked_mul(3).ok_or_else(memory)?; + if self.i == count { + self.stage = Stage::CornerEdges; + self.i = 0; + self.vertex = 0; + return Ok(()); + } + if let Some(parent) = self.parents.get_mut(self.i) { + *parent = self.i; + } else { + self.parents.push(self.i); + } + if let Some(rank) = self.ranks.get_mut(self.i) { + *rank = 0; + } else { + self.ranks.push(0); + } + self.i += 1; + } + Stage::CornerEdges => { + let Some(a) = self.edges.get(self.i).copied() else { + self.stage = Stage::CornerRecords; + self.i = 0; + return Ok(()); + }; + let b = *self.edges.get(self.i + 1).ok_or_else(|| invalid("CPU glass corner edge pair"))?; + let coordinate = if self.vertex == 0 { a.a } else { a.b }; + let corner = |edge: Edge| -> job::Result { + let face = self.faces.get(edge.face).ok_or_else(|| invalid("CPU glass corner face"))?; + let mut local = None; + for (index, p) in face.p.into_iter().enumerate() { + if target_key(p, face.medium, options)? == coordinate { + local = Some(index); + break; + } + } + let local = local.ok_or_else(|| invalid("CPU glass corner endpoint"))?; + edge.face.checked_mul(3).and_then(|n| n.checked_add(local)).ok_or_else(memory) + }; + let ra = self.root(corner(a)?)?; + let rb = self.root(corner(b)?)?; + self.join(ra, rb)?; + self.vertex += 1; + if self.vertex == 2 { + self.vertex = 0; + self.i += 2; + } + } + Stage::CornerRecords => { + let Some(face) = self.faces.get(self.i / 3).copied() else { + self.vertex_sort = true; + self.width = 1; + self.begin = 0; + self.out = 0; + self.stage = Stage::Sort; + return Ok(()); + }; + let coordinate = target_key(*face.p.get(self.i % 3).ok_or_else(|| invalid("CPU glass corner position"))?, face.medium, options)?; + *self.edges.get_mut(self.i).ok_or_else(|| invalid("CPU glass corner record"))? = + Edge { medium: face.medium, a: coordinate, b: [0; 3], face: self.i, forward: false }; + self.i += 1; + } + Stage::VertexLinks => { + let Some(a) = self.edges.get(self.i).copied() else { + self.stage = Stage::Contact; + self.pair = (0, 1); + return Ok(()); + }; + if let Some(b) = self.i.checked_sub(1).and_then(|i| self.edges.get(i)).copied() + && (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")); + } + self.i += 1; + } + Stage::Contact => { + let Some(a) = self.faces.get(self.pair.0).copied() else { + self.stage = Stage::Sources; + self.medium = 0; + self.triangle = 0; + self.vertex = 0; + return Ok(()); + }; + let Some(b) = self.faces.get(self.pair.1).copied() else { + self.next_pair(); + return Ok(()); + }; + let ba = Triangle::new(a.p).map_err(super::image::error)?.bounds(); + let bb = Triangle::new(b.p).map_err(super::image::error)?.bounds(); + if !disjoint(ba, bb) && forbidden_contact(a.p, b.p, a.medium == b.medium) { + return Err(invalid("CPU glass boundaries intersect, touch, overlap or self-intersect")); + } + self.next_pair(); + } + Stage::Sources => { + let Some(input) = options.dielectrics.get(self.medium) else { + self.stage = Stage::Volume; + self.medium = 0; + self.vertex = 0; + return Ok(()); + }; + let body = scene.meshes.get(input.body_index).ok_or_else(|| invalid("CPU glass source-contact body"))?; + let Some(indices) = body.mesh.triangles.get(self.triangle) else { + self.medium += 1; + self.triangle = 0; + self.vertex = 0; + return Ok(()); + }; + let mut p = [Vec3::ZERO; 3]; + for (p, index) in p.iter_mut().zip(indices) { + *p = *body.mesh.positions.get(*index as usize).ok_or_else(|| invalid("CPU glass source-contact vertex"))?; + } + let areas = options.area_lights.as_ref().map_or(0, Vec::len); + if let Some(light) = options.area_lights.as_ref().and_then(|lights| lights.get(self.vertex)) { + let vector = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + let c = vector(light.center_mm); + let u = vector(light.edge_u_mm) * 0.5; + let v = vector(light.edge_v_mm) * 0.5; + let q = [c - u - v, c + u - v, c + u + v, c - u + v]; + predicate_domain(&q)?; + if forbidden_contact(p, [q[0], q[1], q[2]], false) || forbidden_contact(p, [q[0], q[2], q[3]], false) { + return Err(invalid("CPU glass cannot touch an analytic area emitter")); + } + self.vertex += 1; + } else if let Some(light) = + self.vertex.checked_sub(areas).and_then(|at| options.punctual_lights.as_ref().and_then(|lights| lights.get(at))) + { + let q = Vec3::new(light.position_mm[0], light.position_mm[1], light.position_mm[2]); + predicate_domain(&[q])?; + if side(p, q) == 0.0 && in_triangle(p, q, projection(p)) { + return Err(invalid("CPU point or spot source lies on a glass boundary")); + } + self.vertex += 1; + } else { + self.triangle += 1; + self.vertex = 0; + } + } + Stage::Volume => { + let Some(input) = options.dielectrics.get(self.medium) else { + self.stage = Stage::Parents; + self.outer = 0; + self.inner = 1; + return Ok(()); + }; + let region = *self.regions.get(self.medium).ok_or_else(|| invalid("CPU exact glass volume region"))?; + if input.boundary == DielectricBoundary::ThinSheet { + self.medium += 1; + return Ok(()); + } + if self.vertex == 0 { + self.i = region.begin; + self.volume = Default::default(); + self.vertex = 1; + } + if self.i == region.end { + if !self.volume.positive() { + return Err(invalid("CPU glass must enclose positive exact outward-oriented volume")); + } + self.medium += 1; + self.vertex = 0; + return Ok(()); + } + let p = self.faces.get(self.i).ok_or_else(|| invalid("CPU exact glass volume face"))?.p; + self.volume.add_term(p, self.vertex - 1)?; + self.vertex += 1; + if self.vertex == 7 { + self.vertex = 1; + self.i += 1; + } + } + Stage::Parents => { + if self.outer >= self.count { + self.finish(); + return Ok(()); + } + if self.inner >= self.count { + self.outer += 1; + self.inner = self.outer + 1; + return Ok(()); + } + let a = self.regions[self.outer]; + let b = self.regions[self.inner]; + if disjoint(a.bounds, b.bounds) { + self.inner += 1; + return Ok(()); + } + let oa = options.dielectrics.get(self.outer).ok_or_else(|| invalid("CPU glass outer options"))?; + let ob = options.dielectrics.get(self.inner).ok_or_else(|| invalid("CPU glass inner options"))?; + if oa.boundary == DielectricBoundary::ThinSheet || ob.boundary == DielectricBoundary::ThinSheet { + return Err(invalid("CPU thin sheets may not touch or overlap a closed medium's bounds")); + } + let (parent, child) = if contains(a.bounds, b.bounds) { + (self.outer, self.inner) + } else if contains(b.bounds, a.bounds) { + (self.inner, self.outer) + } else { + return Err(invalid("CPU glass overlapping bounds have no conservative nesting certificate")); + }; + self.pair = (parent, child); + self.i = self.regions[parent].begin; + self.j = self.regions[parent].begin; + self.vertex = 0; + self.stage = Stage::Convex; + } + Stage::Convex | Stage::Inside => { + let (parent, child) = self.pair; + let pr = self.regions[parent]; + let cr = self.regions[child]; + let inside = matches!(self.stage, Stage::Inside); + let points = if inside { cr } else { pr }; + if self.i >= pr.end { + if !inside { + self.stage = Stage::Inside; + self.i = pr.begin; + self.j = cr.begin; + self.vertex = 0; + return Ok(()); + } + let old = self.regions[child].parent; + if old.is_none_or(|old| contains(self.regions[old].bounds, pr.bounds)) { + self.regions[child].parent = Some(parent); + } + self.inner += 1; + self.stage = Stage::Parents; + return Ok(()); + } + let face = self.faces.get(self.i).ok_or_else(|| invalid("CPU glass nesting face"))?; + let p = self.faces.get(self.j).and_then(|f| f.p.get(self.vertex)).copied().ok_or_else(|| invalid("CPU glass nesting point"))?; + let sign = side(face.p, p); + if (inside && sign <= 0.0) || (!inside && sign < 0.0) { + return Err(invalid("CPU nested glass requires a convex outward parent and strictly contained child")); + } + self.vertex += 1; + if self.vertex == 3 { + self.vertex = 0; + self.j += 1; + } + if self.j >= points.end { + self.i += 1; + self.j = points.begin; + } + } + Stage::Done => return Err(invalid("CPU glass certification already complete")), + } + Ok(()) + } + fn finish(&mut self) { + self.stage = Stage::Done; + self.faces = Vec::new(); + self.edges = Vec::new(); + self.scratch = Vec::new(); + self.parents = Vec::new(); + self.ranks = Vec::new(); + } +} +fn disjoint(a: Bounds, b: Bounds) -> bool { + let a0 = a.min(); + let a1 = a.max(); + let b0 = b.min(); + let b1 = b.max(); + a1.x < b0.x || b1.x < a0.x || a1.y < b0.y || b1.y < a0.y || a1.z < b0.z || b1.z < a0.z +} +fn contains(a: Bounds, b: Bounds) -> bool { + let a0 = a.min(); + let a1 = a.max(); + let b0 = b.min(); + let b1 = b.max(); + a0.x <= b0.x && a0.y <= b0.y && a0.z <= b0.z && a1.x >= b1.x && a1.y >= b1.y && a1.z >= b1.z +} + +/// Source-plane exclusion is limited to the producing body and the exact f64 +/// plane, so a parallel opposite interface or another body's occluder remains. +pub(super) fn same_plane(a: [Vec3; 3], b: [Vec3; 3]) -> bool { + b.into_iter().all(|p| side(a, p) == 0.0) +} + +/// Exact positive-X oriented crossing with half-open projected edge ownership. +/// Shared projected edges with equal normal signs contribute once; silhouettes +/// contribute opposite signs (or neither). Thus a closed oriented manifold has +/// winding0 outside and1 inside, including rays through edges/vertices. A point +/// actually on the surface is refused instead of assigned to an arbitrary side. +pub(super) fn origin_crossing(t: [Vec3; 3], origin: Vec3) -> job::Result { + predicate_domain(&[origin])?; + let sign = side(t, origin); + if sign == 0.0 && in_triangle(t, origin, projection(t)) { + return Err(invalid("CPU camera or pupil origin lies exactly on a Glass boundary")); + } + let mut q = t.map(|p| project(p, 0)); + let p = project(origin, 0); + let area = orient2d(q[0], q[1], q[2]); + if area == 0.0 || sign == 0.0 || opposite(sign, area) { + return Ok(0); + } + let contribution = if area > 0.0 { 1 } else { -1 }; + if area < 0.0 { + q.swap(1, 2); + } + for (a, b) in [(0, 1), (1, 2), (2, 0)] { + let a = q[a]; + let b = q[b]; + let edge = orient2d(a, b, p); + let owns = b.y > a.y || (b.y == a.y && b.x < a.x); + if edge < 0.0 || (edge == 0.0 && !owns) { + return Ok(0); + } + } + Ok(contribution) +} + +/// Exact contact between a finite pre-clip segment and one optical triangle. +/// Touches, endpoints and coplanar stretches count: none is silently classified +/// as a constant medium. The existing camera's clipped projection is not changed. +pub(super) fn origin_segment_contact(t: [Vec3; 3], a: Vec3, b: Vec3) -> job::Result { + predicate_domain(&[a, b])?; + let sa = side(t, a); + let sb = side(t, b); + if (sa > 0.0 && sb > 0.0) || (sa < 0.0 && sb < 0.0) { + return Ok(false); + } + let drop = projection(t); + if (sa == 0.0 && in_triangle(t, a, drop)) || (sb == 0.0 && in_triangle(t, b, drop)) { + return Ok(true); + } + if opposite(sa, sb) { + let signs = [side([a, b, t[0]], t[1]), side([a, b, t[1]], t[2]), side([a, b, t[2]], t[0])]; + return Ok(!signs.iter().any(|s| *s < 0.0) || !signs.iter().any(|s| *s > 0.0)); + } + if sa == 0.0 && sb == 0.0 { + for (i, j) in [(0, 1), (1, 2), (2, 0)] { + if coplanar_edge_bad([[a, b], [t[i], t[j]]], [t, t], false, drop) { + return Ok(true); + } + } + } + Ok(false) +} + +/// A scattered origin must not round back onto its producing/endpoint plane. +/// This conservative precision check uses the same exact predicate domain as +/// the certificate; it never nudges a point to manufacture an interior sample. +pub(super) fn origin_on_plane(triangle: [Vec3; 3], point: Vec3) -> job::Result { + predicate_domain(&triangle)?; + predicate_domain(&[point])?; + Ok(side(triangle, point) == 0.0) +} diff --git a/crates/render/src/raytrace/glass_volume.rs b/crates/render/src/raytrace/glass_volume.rs new file mode 100644 index 000000000..56bfb8f9e --- /dev/null +++ b/crates/render/src/raytrace/glass_volume.rs @@ -0,0 +1,100 @@ +//! Exact dyadic sign of six times the captured closed mesh volume. +//! Certificate coordinates are zero or normal f64 values with magnitude2^-128..1e12. +//! A coordinate is an integer mantissa times2^e with -180<=e<=-13. +//! Triple products share2^-540; their magnitudes occupy at most660 bits. Even +//! six terms for usize::MAX faces need fewer than728 bits, so12 limbs suffice. +//! This fixed continuation state has no heap, tolerance or floating accumulation. +use crate::job::{self, ErrorCode, JobError}; +use solidcore_record::Vec3; +fn invalid() -> JobError { + JobError::new(ErrorCode::InvalidScene, "CPU exact glass volume exceeds its dyadic certificate domain") +} +#[derive(Default)] +pub(super) struct SignedVolume { + limbs: [u64; 12], + negative: bool, +} +fn magnitude_compare(a: &[u64; 12], b: &[u64; 12]) -> std::cmp::Ordering { + a.iter().rev().cmp(b.iter().rev()) +} +fn subtract(a: &mut [u64; 12], b: &[u64; 12]) -> job::Result<()> { + let mut borrow = false; + for (a, b) in a.iter_mut().zip(b) { + let (value, first) = a.overflowing_sub(*b); + let (value, second) = value.overflowing_sub(u64::from(borrow)); + *a = value; + borrow = first || second; + } + if borrow { + return Err(invalid()); + } + Ok(()) +} +fn parts(value: f64) -> job::Result> { + if value == 0.0 { + return Ok(None); + } + let bits = value.to_bits(); + let exponent = ((bits >> 52) & 2047) as i32; + if !value.is_finite() || value.abs() < f64::from_bits((1023 - 128) << 52) || value.abs() > super::MAX_COORDINATE_MM { + return Err(invalid()); + } + Ok(Some(((bits & ((1_u64 << 52) - 1)) | (1_u64 << 52), exponent - 1023 - 52, bits >> 63 != 0))) +} +impl SignedVolume { + pub(super) fn positive(&self) -> bool { + !self.negative && self.limbs.iter().any(|v| *v != 0) + } + /// Exactly one of the six determinant products per charged caller transition. + pub(super) fn add_term(&mut self, p: [Vec3; 3], term: usize) -> job::Result<()> { + let [a, b, c] = p; + let (x, y, z, minus) = match term { + 0 => (a.x, b.y, c.z, false), + 1 => (a.y, b.z, c.x, false), + 2 => (a.z, b.x, c.y, false), + 3 => (a.x, b.z, c.y, true), + 4 => (a.y, b.x, c.z, true), + 5 => (a.z, b.y, c.x, true), + _ => return Err(invalid()), + }; + let [Some((x, ex, sx)), Some((y, ey, sy)), Some((z, ez, sz))] = [parts(x)?, parts(y)?, parts(z)?] else { + return Ok(()); + }; + let xy = u128::from(x) * u128::from(y); + let low = u128::from(xy as u64) * u128::from(z); + let high = (xy >> 64) * u128::from(z) + (low >> 64); + let product = [low as u64, high as u64, (high >> 64) as u64]; + let shift = usize::try_from(ex + ey + ez + 540).map_err(|_| invalid())?; + let mut value = [0_u64; 12]; + let bit = shift % 64; + for (i, word) in product.into_iter().enumerate() { + let at = shift / 64 + i; + *value.get_mut(at).ok_or_else(invalid)? |= word << bit; + if bit != 0 { + *value.get_mut(at + 1).ok_or_else(invalid)? |= word >> (64 - bit); + } + } + let negative = sx ^ sy ^ sz ^ minus; + if self.negative == negative { + let mut carry = 0_u128; + for (a, b) in self.limbs.iter_mut().zip(value) { + let sum = u128::from(*a) + u128::from(b) + carry; + *a = sum as u64; + carry = sum >> 64; + } + if carry != 0 { + return Err(invalid()); + } + } else if magnitude_compare(&self.limbs, &value).is_lt() { + subtract(&mut value, &self.limbs)?; + self.limbs = value; + self.negative = negative; + } else { + subtract(&mut self.limbs, &value)?; + } + if self.limbs.iter().all(|v| *v == 0) { + self.negative = false; + } + Ok(()) + } +} diff --git a/crates/render/src/raytrace/image.rs b/crates/render/src/raytrace/image.rs index ceadd458a..b70998dbc 100644 --- a/crates/render/src/raytrace/image.rs +++ b/crates/render/src/raytrace/image.rs @@ -4,13 +4,14 @@ use super::bvh::TraceCursor; use super::dielectric::{self, Certificate, MAX_BOUNDARIES, MAX_OVERRIDES, MAX_PATHS}; use super::lighting::{DirectionalLight, Lighting, StudioPreset, map_to_display}; use super::prepared::{PreparedPrimitive, PreparedScene, SharedHit}; -use super::progressive::{self, Progressive}; +#[cfg(test)] +use super::progressive; +use super::progressive::{CameraFilm, Progressive}; use super::reflection; use super::{BuildLimits, Bvh, BvhBuilder, Ray, TraceError, Triangle, WorkBudget}; use crate::job::{self, Admission, CancelToken, ErrorCode, ImageRequest, JobError, Phase, Progress, RaytraceOptions, TaskPoll}; use crate::{ ProductScene, - film::primary::PrimaryFilm, surface::{OpaqueSurface, srgb8_to_linear}, }; use solidcore_record::Vec3; @@ -29,7 +30,7 @@ mod environment_reflection_tests; #[path = "anisotropic_reflection_image_tests.rs"] mod anisotropic_reflection_tests; -fn error(e: TraceError) -> JobError { +pub(crate) fn error(e: TraceError) -> JobError { let code = match e { TraceError::Cancelled => ErrorCode::Cancelled, TraceError::MemoryLimit | TraceError::WorkLimit => ErrorCode::LimitExceeded, @@ -39,7 +40,7 @@ fn error(e: TraceError) -> JobError { }; JobError::new(code, e.to_string()) } -fn invalid(message: &'static str) -> JobError { +pub(super) fn invalid(message: &'static str) -> JobError { JobError::new(ErrorCode::InvalidScene, message) } fn limits(budget: job::CpuBudget) -> BuildLimits { @@ -82,42 +83,98 @@ fn lighting(options: &RaytraceOptions) -> job::Result { } type Look = PreparedPrimitive; -fn certificates(scene: &ProductScene, options: &RaytraceOptions) -> job::Result<[Option; MAX_OVERRIDES]> { - let mut result = [None; MAX_OVERRIDES]; - for (slot, input) in result.iter_mut().zip(&options.dielectrics) { - *slot = Some(dielectric::certify(scene, input).map_err(error)?); +/// Sealed optical result transferred only with its owning captured scene/request. +/// The general cursor retains its exact certified f64 boundary and allocations; +/// moving it into ImageTask does not certify the same geometry a second time. +pub(crate) struct CertifiedOptics { + legacy: Option<[Option; MAX_OVERRIDES]>, + general: Vec, + work_used: u64, +} +impl CertifiedOptics { + pub(super) fn work_used(&self) -> u64 { + self.work_used } - for (i, left) in result.iter().enumerate() { - if let Some(Certificate::ClosedBox(a)) = left { - for right in result.iter().skip(i + 1) { - if let Some(Certificate::ClosedBox(b)) = right - && dielectric::overlaps(*a, *b) - { - return Err(invalid("nested, touching or overlapping dielectric volumes are unsupported")); - } - } + pub(super) fn legacy(values: [Option; MAX_OVERRIDES], work_used: u64) -> Self { + Self { legacy: Some(values), general: Vec::new(), work_used } + } + fn into_legacy(self) -> job::Result<[Option; MAX_OVERRIDES]> { + if !self.general.is_empty() { + return Err(invalid("unexpected general optical proof")); } + self.legacy.ok_or_else(|| invalid("missing legacy optical proof")) } - // Sheets within volumes are unsupported. Conservatively use the admitted - // tiny sheet's bounds, rather than pretending to resolve medium nesting. - for (i, certificate) in result.iter().enumerate() { - if let Some(Certificate::ClosedBox(a)) = certificate { - for (j, other) in result.iter().enumerate() { - if i != j && matches!(other, Some(Certificate::ThinSheet)) { - let input = options.dielectrics.get(j).ok_or_else(|| invalid("sheet override index"))?; - let body = scene.meshes.get(input.body_index).ok_or_else(|| invalid("sheet body index"))?; - let bounds = body.mesh.bounds(); - if dielectric::overlaps(*a, super::Bounds::new(bounds.min, bounds.max).map_err(error)?) { - return Err(invalid("thin sheets touching or inside dielectric volumes are unsupported")); - } - } - } - } - } - Ok(result) } +pub(crate) fn certification_bytes(scene: &ProductScene, options: &RaytraceOptions) -> job::Result { + if options.dielectrics.is_empty() { + return Ok(0); + } + let bytes = if options.path.is_some() { + super::glass_mesh::Task::required_bytes(scene, options)? + } else { + super::legacy_certificates::Task::required_bytes(scene, options).map_err(error)? + }; + bytes.checked_add(std::mem::size_of::() as u64).ok_or_else(|| error(TraceError::MemoryLimit)) +} + +fn legacy_error(cause: TraceError) -> JobError { + match cause { + TraceError::InvalidInput( + message @ ("nested, touching or overlapping dielectric volumes are unsupported" + | "thin sheets touching or inside dielectric volumes are unsupported" + | "thin-lens aperture sphere touches or enters a certified dielectric volume"), + ) => invalid(message), + other => error(other), + } +} + +pub(crate) fn certify_for_request( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + cancel: &CancelToken, +) -> job::Result> { + if options.dielectrics.is_empty() { + cancel.check()?; + return Ok(None); + } + cancel.check()?; + if options.path.is_some() { + let mut general = Vec::new(); + general.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if general.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + let mut task = super::glass_mesh::Task::new(scene, options)?; + let mut work = WorkBudget::new(options.budget.limits().max_work_units).map_err(error)?; + while !task.ready() { + task.step(scene, options, &mut work, cancel)?; + } + general.push(task); + return Ok(Some(CertifiedOptics { legacy: None, general, work_used: work.used() })); + } + let mut task = super::legacy_certificates::Task::new(scene, request, options).map_err(error)?; + let mut work = WorkBudget::new(options.budget.limits().max_work_units).map_err(error)?; + while !task.ready() { + task.step(scene, options, &mut work, cancel).map_err(legacy_error)?; + } + // The ordinary image continuation charges the same final proof store. + work.tick(cancel).map_err(error)?; + task.into_proof(work.used()).map(Some).map_err(error) +} + +/// Strict blocking admission for standalone callers. Native UI preparation must +/// run it beside the window; a header check is never reported as full preflight. pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> job::Result { + let admission = admit_layout(scene, request, options)?; + if !options.dielectrics.is_empty() { + certify_for_request(scene, request, options, &CancelToken::default())?; + } + Ok(admission) +} + +pub(crate) fn admit_layout(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> job::Result { options.validate()?; if let Some(original) = &request.raytrace { original.validate()?; @@ -128,15 +185,46 @@ pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOpt if request.integrator != job::Integrator::Raytrace { return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace task requires raytrace integrator")); } - if request.transparent_background { - return Err(invalid("raytrace supports opaque backgrounds only")); + if options.path.is_some() && scene.has_transmission() { + return Err(invalid(if options.volume.as_ref().is_some_and(|v| v.active()) { + "CPU Atmosphere cannot combine with captured Glass or subsurface scattering" + } else { + "CPU opaque path transport cannot discard authored transmission; choose its existing optical transport" + })); } - if let Some(progressive) = options.progressive { - progressive.validate_image_with_budget(request.width, request.height, options.budget)?; + if let Some(output) = &options.output { + output.presentation(options.exposure_ev, request.background, request.transparent_background).validate()?; } + options.budget.validate_image(request.width, request.height, options.camera_sampling()?)?; + if let Some(lens) = options.lens { + lens.validate_camera(&request.camera)?; + } + if options.denoise { + job::validate_cpu_denoise_image(request.width, request.height)?; + } + super::aging::validate_scene(scene, options)?; let map_bytes = request.textures.as_ref().map_or(Ok(0), |maps| job::textures::cpu_cache::CpuTextureCache::required_bytes(maps, scene, options))?; let mut a = job::image::admit_raytrace_source(scene, request, options.budget)?; + if let Some(lens) = options.lens.filter(|lens| lens.aperture_radius_mm > 0.0) { + // Bound every possible pupil/pixel ray against the same captured clip + // interval used by ImageTask, before allocating or starting transport. + let camera = &request.camera; + let radius = if scene.meshes.is_empty() { 10.0 } else { scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target) }; + let clip = camera.clip(radius); + let slope = (camera.half_height() / camera.distance) * (f64::from(request.width) / f64::from(request.height)).hypot(1.0) + + lens.aperture_radius_mm / lens.focus_distance_mm; + let scale = slope.hypot(1.0); + let eye = camera.eye(); + let origin_bound = eye.x.abs().max(eye.y.abs()).max(eye.z.abs()) + lens.aperture_radius_mm + clip.0.abs() * scale; + if !scale.is_finite() + || !origin_bound.is_finite() + || origin_bound > super::MAX_COORDINATE_MM + || (clip.1 - clip.0) * scale > super::MAX_DISTANCE_MM + { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU thin-lens pupil exceeds the bounded ray coordinate or interval envelope")); + } + } let r = options.reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples); u64::from(request.width) .checked_mul(u64::from(request.height)) @@ -165,7 +253,6 @@ pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOpt } } anisotropic_faces::prepare(scene, options, || Ok(()))?; - certificates(scene, options)?; for input in &options.dielectrics { if options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|v| v.body == input.body_name)) || options.anisotropic_faces.iter().flatten().any(|v| v.body_index == input.body_index) @@ -221,29 +308,82 @@ pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOpt ) }) .ok_or_else(|| error(TraceError::MemoryLimit))?; + let legacy_bytes = if options.dielectrics.is_empty() || options.path.is_some() { + 0 + } else { + certification_bytes(scene, options)?.checked_add(std::mem::size_of::() as u64).ok_or_else(|| error(TraceError::MemoryLimit))? + }; let optical_bytes = options .retained_dielectric_bytes()? .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_dielectric_bytes)?) - .and_then(|v| v.checked_add(if options.dielectrics.is_empty() { 0 } else { std::mem::size_of::() as u64 })) + .and_then(|bytes| bytes.checked_add(legacy_bytes)) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let aging_bytes = options + .retained_aging_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_aging_bytes)?) + .and_then(|v| { + v.checked_add(if options.aging.as_deref().is_some_and(job::aging::AgingStack::active) { super::aging::Task::required_bytes() } else { 0 }) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let adaptive_bytes = options + .retained_adaptive_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_adaptive_bytes)?) + .and_then(|v| v.checked_add(if options.adaptive.is_some() { std::mem::size_of::() as u64 } else { 0 })) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let celestial_bytes = options + .retained_celestial_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_celestial_bytes)?) .ok_or_else(|| error(TraceError::MemoryLimit))?; let n = usize::try_from(a.triangles).map_err(|_| error(TraceError::MemoryLimit))?; let film_bytes = if let Some(progressive) = options.progressive { let checkpoint = a.encoded_limit.checked_add(job::FRAME_METADATA_BYTES).ok_or_else(|| error(TraceError::MemoryLimit))?; - PrimaryFilm::required_bytes(request.width, request.height, progressive, options.budget)? - .checked_add(u64::from(progressive.preview_count()).checked_mul(checkpoint).ok_or_else(|| error(TraceError::MemoryLimit))?) + CameraFilm::required_bytes(request.width, request.height, progressive, options.adaptive.as_deref(), options.budget)? + .checked_add(u64::from(progressive.preview_slots()).checked_mul(checkpoint).ok_or_else(|| error(TraceError::MemoryLimit))?) + .and_then(|v| v.checked_add(if progressive.preview_slots() == 0 { 0 } else { job::FRAME_METADATA_BYTES })) .and_then(|v| v.checked_add(std::mem::size_of::() as u64)) .ok_or_else(|| error(TraceError::MemoryLimit))? } else { 0 }; + let output_bytes = options.output.as_deref().map_or(Ok(0), |output| { + output + .required_bytes(request.width, request.height)? + .checked_add(2 * std::mem::size_of::() as u64) + .ok_or_else(|| error(TraceError::MemoryLimit)) + })?; + // Guides remain job-owned across all checkpoints. Two colour vectors are + // required even with identity presentation; the normal output estimate already + // pays for one when presentation or EXR is enabled. + let denoise_bytes = if options.denoise { + let pixels = u64::from(request.width) * u64::from(request.height); + let output_already_paid = options.output.as_deref().is_some_and(|output| !output.identity_display() || output.linear_exr); + super::denoise::Guides::required_bytes(request.width, request.height)? + .checked_add(pixels.checked_mul(if output_already_paid { 16 } else { 32 }).ok_or_else(|| error(TraceError::MemoryLimit))?) + .and_then(|v| v.checked_add(if output_already_paid { 0 } else { std::mem::size_of::() as u64 })) + .ok_or_else(|| error(TraceError::MemoryLimit))? + } else { + 0 + }; + let general_glass_bytes = if options.path.is_some() && !options.dielectrics.is_empty() { + certification_bytes(scene, options)?.checked_add(super::origin::Task::required_bytes()).ok_or_else(|| error(TraceError::MemoryLimit))? + } else { + 0 + }; let extra = BvhBuilder::required_bytes(n, n, limits(options.budget)) .map_err(error)? .checked_add(a.triangles.checked_mul(std::mem::size_of::() as u64).ok_or_else(|| error(TraceError::MemoryLimit))?) .and_then(|v| v.checked_add(emission_bytes)) .and_then(|v| v.checked_add(effect_bytes)) .and_then(|v| v.checked_add(map_bytes)) + .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(if options.path.is_some() { std::mem::size_of::() as u64 } else { 0 })) .and_then(|v| v.checked_add(film_bytes)) + .and_then(|v| v.checked_add(adaptive_bytes)) + .and_then(|v| v.checked_add(celestial_bytes)) + .and_then(|v| v.checked_add(output_bytes)) + .and_then(|v| v.checked_add(denoise_bytes)) // The resumable pixel owns two traversal cursors. Its fallible, fixed // heap slot is additional to the unchanged host/task-state allowance. .and_then(|v| v.checked_add(PendingPixelSlot::required_bytes())) @@ -382,6 +522,7 @@ struct DielectricPixel { struct OpticalTask { certificates: [Option; MAX_OVERRIDES], pending: Option, + preparation: Vec, } impl DielectricPixel { @@ -456,11 +597,19 @@ fn resume_optical_path(pending: &mut PendingPixel, path: OpticalPath) { pending.environment_value = Vec3::ZERO; } +#[path = "image_indirect.rs"] +mod indirect_image; + pub struct ImageTask { maps: Vec, + aging: Vec, + path: Vec, punctual_diagnostics: job::PunctualDiagnostics, progressive: Option, + sampling: Vec, + denoise: Vec, optical: Vec, + glass: Vec, anisotropic_targets: [Option; 2], environment: Option, scene: ProductScene, @@ -473,6 +622,7 @@ pub struct ImageTask { effects: Vec<(usize, crate::surface_patterns::PreparedEffect)>, work: WorkBudget, clip: (f64, f64), + pupil_sample: Option<[f64; 2]>, triangles: Vec, looks: Vec, body: usize, @@ -485,6 +635,9 @@ pub struct ImageTask { bvh: Option, build_used: u64, pixels: Vec, + linear: Vec<[f32; 4]>, + output: Vec, + linear_exr: Option>, pixel: usize, sample: u8, spatial: u8, @@ -509,6 +662,9 @@ pub enum ImagePoll { } impl ImageTask { + pub fn sampling_report(&self) -> Option { + self.sampling.first().cloned() + } pub fn punctual_diagnostics(&self) -> Option { (!self.punctual_diagnostics.is_empty()).then_some(self.punctual_diagnostics) } @@ -522,17 +678,63 @@ impl ImageTask { cancel: CancelToken, options: RaytraceOptions, input: Option, + ) -> job::Result { + Self::new_prepared(scene, request, cancel, options, input, None) + } + pub(crate) fn new_prepared( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + proof: Option, ) -> job::Result { cancel.check()?; - let mut admission = admit(&scene, &request, &options)?; + let mut admission = admit_layout(&scene, &request, &options)?; + if options.dielectrics.is_empty() && proof.is_some() { + return Err(invalid("unexpected optical proof without selected boundaries")); + } + let certified_work = proof.as_ref().map_or(0, CertifiedOptics::work_used); + let (legacy_proof, mut glass) = if let Some(proof) = proof { + if options.path.is_some() { + if proof.legacy.is_some() || proof.general.len() != 1 || !proof.general.first().is_some_and(|task| task.ready()) { + return Err(invalid("unexpected or incomplete general optical proof")); + } + (None, proof.general) + } else { + (Some(proof.into_legacy()?), Vec::new()) + } + } else { + (None, Vec::new()) + }; let mut optical = Vec::new(); - if !options.dielectrics.is_empty() { - let certificates = certificates(&scene, &options)?; + if !options.dielectrics.is_empty() && options.path.is_none() { + let mut preparation = Vec::new(); + let certificates = if let Some(values) = legacy_proof { + values + } else { + preparation.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if preparation.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + cancel.check()?; + preparation.push(super::legacy_certificates::Task::new(&scene, &request, &options).map_err(error)?); + [None; MAX_OVERRIDES] + }; optical.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; if optical.capacity() != 1 { return Err(error(TraceError::MemoryLimit)); } - optical.push(OpticalTask { certificates, pending: None }); + optical.push(OpticalTask { certificates, pending: None, preparation }); + } else if legacy_proof.is_some() { + return Err(invalid("unexpected legacy optical proof")); + } + if options.path.is_some() && !options.dielectrics.is_empty() && glass.is_empty() { + glass.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if glass.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + glass.push(super::glass_mesh::Task::new(&scene, &options)?); } if input.is_some() { options.validate_environment_reflections(&scene)?; @@ -547,6 +749,7 @@ impl ImageTask { let environment = input.map(|e| e.begin()).transpose().map_err(environment_error)?; let lights = lighting(&options)?; let mut work = WorkBudget::new(options.budget.limits().max_work_units).map_err(error)?; + work.charge(certified_work, &cancel).map_err(error)?; let anisotropic_targets = anisotropic_faces::prepare(&scene, &options, || work.tick(&cancel).map_err(error))?; let mut effects = Vec::new(); if let Some(values) = &options.surface_effects { @@ -602,6 +805,30 @@ impl ImageTask { { return Err(error(TraceError::MemoryLimit)); } + let mut output = Vec::new(); + if options.denoise || options.output.as_deref().is_some_and(|settings| !settings.identity_display() || settings.linear_exr) { + output.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if output.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + } + let mut path = Vec::new(); + if options.path.is_some() { + cancel.check()?; + path.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if path.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + path.push(indirect_image::State::default()); + } + let mut denoise = Vec::new(); + if options.denoise { + denoise.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if denoise.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + denoise.push(super::denoise::Guides::new(request.width, request.height)?); + } let mut maps = Vec::new(); if let Some(resources) = &request.textures { maps.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; @@ -610,21 +837,45 @@ impl ImageTask { } maps.push(job::textures::cpu_cache::CpuTextureCache::new(resources.clone(), &cancel)?); } + let mut aging = Vec::new(); + if options.aging.as_deref().is_some_and(job::aging::AgingStack::active) { + cancel.check()?; + aging.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if aging.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + aging.push(super::aging::Task::default()); + } let pending = PendingPixelSlot::new(&cancel)?; let budget = options.budget; + let mut sampling = Vec::new(); + if options.adaptive.is_some() { + cancel.check()?; + sampling.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if sampling.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + } + let adaptive = options.adaptive.as_deref(); + let target = options.preview_target()?; let progressive = options .progressive .map(|options| -> job::Result { - let bytes = PrimaryFilm::required_bytes(request.width, request.height, options, budget)?; - let film = PrimaryFilm::new(request.width, request.height, options, bytes, &cancel, budget)?; - Ok(Progressive { film, options, resolving: false, resolve_pixel: 0 }) + let bytes = CameraFilm::required_bytes(request.width, request.height, options, adaptive, budget)?; + let film = CameraFilm::new(request.width, request.height, options, adaptive, budget, bytes, &cancel)?; + Ok(Progressive { film, options, target, resolving: false, resolve_pixel: 0 }) }) .transpose()?; Ok(Self { maps, + aging, + path, punctual_diagnostics: Default::default(), progressive, + sampling, + denoise, optical, + glass, anisotropic_targets, environment, scene, @@ -636,6 +887,7 @@ impl ImageTask { emissions, effects, clip, + pupil_sample: None, work, triangles, looks, @@ -647,6 +899,9 @@ impl ImageTask { bvh: None, build_used: 0, pixels, + linear: Vec::new(), + output, + linear_exr: None, pixel: 0, sample: 0, spatial: 0, @@ -661,22 +916,36 @@ impl ImageTask { }) } pub fn progress(&self) -> Progress { - let (phase, done, total) = if self.done { + let (phase, done, total) = if self.optical.first().is_some_and(|optical| !optical.preparation.is_empty()) { + (Phase::Preparing, 0, 1) + } else if self.done { (Phase::Completed, 1, 1) + } else if !self.output.is_empty() { + (Phase::Encoding, 0, u64::from(self.request.width) * u64::from(self.request.height)) } else if let Some(e) = &self.encoder { (Phase::Encoding, e.row() as u64, self.request.height as u64) } else if let Some(maps) = self.maps.first().filter(|maps| !maps.ready()) { let (done, total) = maps.preparation_rows(); (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.denoise.first().is_some_and(|guides| !guides.ready()) { + ( + Phase::Preparing, + self.denoise.first().map_or(0, |guides| guides.completed_pixels() as u64), + u64::from(self.request.width) * u64::from(self.request.height), + ) } else if let Some(progressive) = &self.progressive { let count = u64::from(self.request.width) * u64::from(self.request.height); if !progressive.film.ready() { (Phase::Preparing, progressive.film.initialized() as u64, count) + } else if progressive.film.resetting() { + (Phase::Preparing, progressive.film.reset_progress() as u64, count) } else if progressive.resolving { (Phase::Encoding, progressive.resolve_pixel as u64, count) } else if self.bvh.is_some() { let partial = if self.pixel as u64 == count { 0 } else { self.pixel as u64 }; - (Phase::Running, u64::from(progressive.film.samples()) * count + partial, u64::from(progressive.options.samples_per_pixel) * count) + (Phase::Running, u64::from(progressive.film.samples()) * count + partial, u64::from(progressive.target) * count) } else { (Phase::Preparing, self.triangles.len() as u64, self.admission.triangles) } @@ -743,6 +1012,105 @@ impl ImageTask { self.triangle += 1; Ok(()) } + /// Move the final native raw companion once. Provisional passes never populate it. + pub fn take_linear_exr(&mut self) -> Option> { + self.linear_exr.take() + } + fn preserves_display(&self) -> bool { + !self.options.denoise && self.options.output.as_deref().is_none_or(|o| o.identity_display()) + } + fn needs_linear_pass(&self) -> bool { + self.options.denoise + || self + .options + .output + .as_deref() + .is_some_and(|o| !o.identity_display() || (o.linear_exr && self.progressive.as_ref().is_none_or(|p| p.film.samples() == p.target))) + } + fn append_linear(&mut self, radiance: Vec3, covered: u16, samples: u16) -> job::Result<()> { + if !self.needs_linear_pass() { + return Ok(()); + } + if samples == 0 || covered > samples || !bounded_radiance(radiance) || (covered == 0 && radiance != Vec3::ZERO) { + return Err(invalid("invalid raw CPU radiance or coverage")); + } + self.work.tick(&self.cancel).map_err(error)?; + let count = self.request.width as usize * self.request.height as usize; + if self.linear.capacity() == 0 { + self.linear.try_reserve_exact(count).map_err(|_| error(TraceError::AllocationFailed))?; + } + if self.linear.capacity() != count || self.linear.len() >= count { + return Err(error(TraceError::MemoryLimit)); + } + let pixel = [radiance.x as f32, radiance.y as f32, radiance.z as f32, (f64::from(covered) / f64::from(samples)) as f32]; + if pixel.iter().any(|v| !v.is_finite() || *v < 0.0) || pixel[3] > 1.0 { + return Err(invalid("raw CPU float conversion exceeds finite bounds")); + } + self.cancel.check()?; + self.linear.push(pixel); + Ok(()) + } + fn start_output(&mut self) -> job::Result<()> { + if self.output.capacity() != 1 || !self.output.is_empty() { + return Err(invalid("CPU output slot is not admitted or available")); + } + let settings = match self.options.output.as_deref() { + Some(settings) => *settings, + None if self.options.denoise => Default::default(), + None => return Err(invalid("missing CPU output settings")), + }; + let final_pass = self.progressive.as_ref().is_none_or(|p| p.film.samples() == p.target); + let coverage_samples = match &self.progressive { + Some(progressive) => u16::try_from(progressive.film.samples()).map_err(|_| invalid("CPU coverage sample count overflow"))?, + None if self.options.primary_samples == 1 => 1, + None => u16::from(self.options.primary_samples) + .checked_mul(u16::from(self.sample_count())) + .ok_or_else(|| invalid("CPU spatial coverage sample count overflow"))?, + }; + let presentation = settings.presentation(self.options.exposure_ev, self.request.background, self.request.transparent_background); + let task = job::output::OutputTask::new( + self.request.width, + self.request.height, + self.admission.encoded_limit, + std::mem::take(&mut self.linear), + std::mem::take(&mut self.pixels), + presentation, + self.preserves_display(), + final_pass && settings.linear_exr, + self.options.denoise, + coverage_samples, + self.cancel.clone(), + &mut |units| self.work.charge(units, &self.cancel).map_err(error), + )?; + self.output.push(task); + Ok(()) + } + fn complete_png(&mut self, png: Vec, charged: bool) -> job::Result { + self.cancel.check()?; + if let Some(progressive) = &mut self.progressive { + if !charged { + self.work.charge(png.len() as u64, &self.cancel).map_err(error)?; + } + let samples_per_pixel = progressive.film.samples(); + if samples_per_pixel < progressive.target { + progressive.resolving = false; + progressive.resolve_pixel = 0; + self.encoder = None; + self.pixels.clear(); + self.pixel = 0; + return Ok(ImagePoll::Preview { png, samples_per_pixel }); + } + } + if let Some(report) = self.progressive.as_ref().map(|p| p.film.report()).transpose()?.flatten() { + if self.sampling.capacity() != 1 || !self.sampling.is_empty() { + return Err(invalid("CPU adaptive report slot is not admitted or available")); + } + self.cancel.check()?; + self.sampling.push(report); + } + self.release_completed_work()?; + Ok(ImagePoll::Complete(png)) + } fn sample_count(&self) -> u8 { self.options.reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples) } @@ -783,8 +1151,12 @@ impl ImageTask { } self.pending.clear(); if self.sample == self.sample_count() { - let display = map_to_display(self.pixel_radiance / self.sample as f64, self.options.exposure_ev).map_err(error)?; - self.pixels.extend_from_slice(&[encode8(display.x), encode8(display.y), encode8(display.z), 255]); + let radiance = self.pixel_radiance / self.sample as f64; + self.append_linear(radiance, 1, 1)?; + if self.preserves_display() { + let display = map_to_display(radiance, self.options.exposure_ev).map_err(error)?; + self.pixels.extend_from_slice(&[encode8(display.x), encode8(display.y), encode8(display.z), 255]); + } self.pixel += 1; self.sample = 0; self.pixel_radiance = Vec3::ZERO; @@ -833,9 +1205,19 @@ impl ImageTask { .checked_mul(u16::from(self.sample_count())) .filter(|n| *n <= 1024) .ok_or_else(|| invalid("spatial coverage bound"))?; - let rgba = composite_spatial(self.spatial_radiance, self.primary_coverage, attempts, self.request.background, self.options.exposure_ev)?; - self.cancel.check()?; - self.pixels.extend_from_slice(&rgba); + self.append_linear(self.spatial_radiance, self.primary_coverage, attempts)?; + if self.preserves_display() { + let rgba = composite_spatial_alpha( + self.spatial_radiance, + self.primary_coverage, + attempts, + self.request.background, + self.options.exposure_ev, + self.request.transparent_background, + )?; + self.cancel.check()?; + self.pixels.extend_from_slice(&rgba); + } self.pixel += 1; self.spatial = 0; self.primary_coverage = 0; @@ -884,6 +1266,7 @@ impl ImageTask { pending, &self.effects, self.maps.first(), + self.aging.first(), )?; if self.optical.first().is_some_and(|o| o.pending.is_some()) || self.options.dielectrics.iter().any(|input| input.body_index == shared.body_index) @@ -902,13 +1285,27 @@ impl ImageTask { } let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing image BVH"))?; if self.pending.is_none() { + if self.options.lens.is_some_and(|lens| lens.aperture_radius_mm > 0.0) && self.pupil_sample.is_none() { + self.work.tick(&self.cancel).map_err(error)?; + let progressive = self.progressive.as_ref().ok_or_else(|| invalid("physical pupil requires progressive camera sampling"))?; + self.pupil_sample = Some(progressive.variates(self.pixel, 0x4c454e53)?); + return Ok(()); + } self.work.tick(&self.cancel).map_err(error)?; let width = self.request.width as usize; // This proof belongs to the generator for a fixed (pixel, spatial), // not the camera/request globally. Future per-R jitter must revoke it. let (ray, repeatable_primary) = if let Some(progressive) = &self.progressive { - let [dx, dy] = progressive::variates(progressive.options.seed, self.pixel as u64, progressive.film.samples(), 0); - (primary_ray(&self.request, (self.pixel % width) as f64 + dx, (self.pixel / width) as f64 + dy, self.clip).map_err(error)?, false) + let [dx, dy] = progressive.variates(self.pixel, 0)?; + let x = (self.pixel % width) as f64 + dx; + let y = (self.pixel / width) as f64 + dy; + let ray = if let Some(lens) = self.options.lens.filter(|lens| lens.aperture_radius_mm > 0.0) { + let pupil = self.pupil_sample.take().ok_or_else(|| invalid("missing physical pupil sample"))?; + lens_primary_ray(&self.request, x, y, self.clip, lens, pupil).map_err(error)? + } else { + primary_ray(&self.request, x, y, self.clip).map_err(error)? + }; + (ray, false) } else if self.options.primary_samples == 1 { // Preserve the exact legacy centre path, including its reuse proof. (primary_ray(&self.request, (self.pixel % width) as f64 + 0.5, (self.pixel / width) as f64 + 0.5, self.clip).map_err(error)?, true) @@ -989,8 +1386,16 @@ impl ImageTask { // A miss is one of S*R attempts, never the completed pixel. return self.finish_sample(Vec3::ZERO); } - let [r, g, b] = self.request.background; - self.pixels.extend_from_slice(&[r, g, b, 255]); + self.append_linear(Vec3::ZERO, 0, 1)?; + if self.preserves_display() { + let rgba = if self.request.transparent_background { + [0; 4] + } else { + let [r, g, b] = self.request.background; + [r, g, b, 255] + }; + self.pixels.extend_from_slice(&rgba); + } self.pixel += 1; self.sample = 0; self.pixel_radiance = Vec3::ZERO; @@ -1022,6 +1427,9 @@ impl ImageTask { if let Some(maps) = self.maps.first_mut() { maps.reset_hit(); } + if let Some(aging) = self.aging.first_mut() { + aging.reset(); + } pending.light = 0; let shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; let mode = @@ -1035,7 +1443,7 @@ impl ImageTask { // Traversal consumed this continuation; selector work begins next call. return Ok(()); } - pending.surface_ready = self.effects.is_empty() && self.maps.is_empty(); + pending.surface_ready = self.effects.is_empty() && self.maps.is_empty() && self.aging.is_empty(); if !pending.surface_ready { // Traversal already consumed this continuation's unit. Scan one // effect per following call, before beginning any lighting stage. @@ -1091,12 +1499,33 @@ impl ImageTask { footprint, )?; } - if !maps.hit_ready() && !maps.advance_hit()? { - return Ok(()); + if !maps.hit_ready() { + let ready = maps.advance_hit()?; + if !ready || !self.aging.is_empty() { + return Ok(()); + } + } + } + if let Some(aging) = self.aging.first_mut() { + if !aging.started() { + let shared = unaged_surface_hit(&scene, pending, &self.effects, self.maps.first())?; + aging.begin( + crate::surface_patterns::ShadingSurface { surface: shared.surface, shading_normal: shared.shading_normal }, + shared.position, + shared.geometric_normal, + shared.body_index, + super::aging::eligible(&self.options, shared.body_index, shared.body_name), + )?; + } + if !aging.ready() { + let stack = self.options.aging.as_deref().ok_or_else(|| invalid("CPU aging stack disappeared"))?; + if !aging.advance(stack)? { + return Ok(()); + } } } pending.surface_ready = true; - let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first())?; + let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first(), self.aging.first())?; let mode = self.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); if self.options.shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { @@ -1113,7 +1542,7 @@ impl ImageTask { *pending.visibility.get_mut(pending.light).ok_or_else(|| invalid("light visibility index"))? = shadow.is_none(); pending.light += 1; if let Some(light) = self.lights.lights().get(pending.light) { - let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first())?; + let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first(), self.aging.first())?; pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); return Ok(()); } @@ -1135,7 +1564,7 @@ impl ImageTask { return Ok(()); } if pending.punctual_index < self.options.punctual_lights.as_ref().map_or(0, Vec::len) { - let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first())?; + let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first(), self.aging.first())?; let mode = self.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("punctual face missing"))?.face; @@ -1146,27 +1575,17 @@ impl ImageTask { return Ok(()); } if pending.area_light < self.options.area_lights.as_ref().map_or(0, Vec::len) { - let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first())?; + let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first(), self.aging.first())?; let mode = self.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("area face missing"))?.face; let target = anisotropic_faces::target_index(&self.options, shared.body_index, face) .map(|i| self.anisotropic_targets.get(i).copied().flatten().ok_or_else(|| invalid("area anisotropic target missing"))) .transpose()?; - area_one( - pending, - &self.options, - bvh, - (shared, target, mode), - &mut self.work, - &self.cancel, - area_sample_key( - self.pixel as u64, - self.spatial, - self.options.primary_samples, - self.progressive.as_ref().map_or(0, |progress| progress.film.samples()), - )?, - )?; + let ordinal = self.progressive.as_ref().map(|p| p.identity(self.pixel).map(|i| i.ordinal)).transpose()?.unwrap_or(0); + let key = area_sample_key(self.pixel as u64, self.spatial, self.options.primary_samples, ordinal)?; + let key = self.progressive.as_ref().map_or(Ok(key), |p| p.area_key(self.pixel, key))?; + area_one(pending, &self.options, bvh, (shared, target, mode), &mut self.work, &self.cancel, key)?; return Ok(()); } if let Some(cursor) = &mut pending.environment_cursor { @@ -1182,7 +1601,7 @@ impl ImageTask { } if pending.light == self.lights.lights().len() { self.work.tick(&self.cancel).map_err(error)?; - let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first())?; + let shared = resolved_surface_hit(&scene, pending, &self.effects, self.maps.first(), self.aging.first())?; let mode = self.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); let view = -pending.ray.direction(); @@ -1201,12 +1620,7 @@ impl ImageTask { }; let i = pending.environment_sample; let u = if let Some(progressive) = &self.progressive { - let [dx, dy] = progressive::variates( - progressive.options.seed, - self.pixel as u64, - progressive.film.samples(), - 0x1000 + u64::from(pending.bounce) * 128 + u64::from(i), - ); + let [dx, dy] = progressive.variates(self.pixel, 0x1000 + u64::from(pending.bounce) * 128 + u64::from(i))?; [(f64::from(i / side) + dx) / f64::from(side), (f64::from(i % side) + dy) / f64::from(side)] } else if side == 1 { [0.25, 0.375] @@ -1252,7 +1666,7 @@ impl ImageTask { if let Some(mode) = mode.filter(|_| pending.bounce < max_bounces) { let samples = self.options.reflections.as_ref().map_or(1, |r| u64::from(r.samples)); let u = if let Some(progressive) = &self.progressive { - progressive::variates(progressive.options.seed, self.pixel as u64, progressive.film.samples(), 0x100 + u64::from(pending.bounce)) + progressive.variates(self.pixel, 0x100 + u64::from(pending.bounce))? } else if self.options.primary_samples == 1 { reflection::variates(self.pixel as u64, self.sample as u64, pending.bounce as u64, samples).map_err(error)? } else { @@ -1373,7 +1787,7 @@ impl ImageTask { } state.ready = true; let Some(index) = state.selected else { - pending.surface_ready = self.effects.is_empty() && self.maps.is_empty(); + pending.surface_ready = self.effects.is_empty() && self.maps.is_empty() && self.aging.is_empty(); if !pending.surface_ready { return Ok(()); } @@ -1491,7 +1905,14 @@ impl ImageTask { self.builder = None; self.triangles = Vec::new(); self.pixels = Vec::new(); + self.linear = Vec::new(); + self.output = Vec::new(); + self.denoise = Vec::new(); + self.options.output = None; + self.options.adaptive = None; + self.options.volume = None; self.pending.release(); + self.path = Vec::new(); self.request.raytrace = None; self.options.lights = None; self.options.emissions = None; @@ -1499,9 +1920,14 @@ impl ImageTask { self.options.surface_effects = None; self.maps = Vec::new(); self.request.textures = None; + self.options.aging = None; + self.aging = Vec::new(); self.options.dielectrics = Vec::new(); self.options.environment = None; + self.options.sun = None; + self.options.sky = None; self.optical = Vec::new(); + self.glass = Vec::new(); self.effects = Vec::new(); self.options.punctual_lights = None; self.options.area_lights = None; @@ -1513,14 +1939,27 @@ impl ImageTask { fn resolve_progressive_one(&mut self) -> job::Result<()> { self.work.tick(&self.cancel).map_err(error)?; - let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing progressive resolve state"))?; + let progressive = self.progressive.as_ref().ok_or_else(|| invalid("missing progressive resolve state"))?; let count = self.request.width as usize * self.request.height as usize; if progressive.resolve_pixel < count { let (rgb, covered, samples) = progressive.film.pixel(progressive.resolve_pixel)?; - let rgba = composite_spatial(Vec3::new(rgb[0], rgb[1], rgb[2]), covered, samples, self.request.background, self.options.exposure_ev)?; - self.cancel.check()?; - self.pixels.extend_from_slice(&rgba); - progressive.resolve_pixel += 1; + let radiance = Vec3::new(rgb[0], rgb[1], rgb[2]); + self.append_linear(radiance, covered, samples)?; + if self.preserves_display() { + let rgba = composite_spatial_alpha( + radiance, + covered, + samples, + self.request.background, + self.options.exposure_ev, + self.request.transparent_background, + )?; + self.cancel.check()?; + self.pixels.extend_from_slice(&rgba); + } + self.progressive.as_mut().ok_or_else(|| invalid("missing progressive resolve state"))?.resolve_pixel += 1; + } else if self.needs_linear_pass() { + self.start_output()?; } else { let capacity = usize::try_from(self.admission.encoded_limit).map_err(|_| error(TraceError::MemoryLimit))?; let mut output = Vec::new(); @@ -1548,17 +1987,42 @@ impl ImageTask { return Err(JobError::new(ErrorCode::InvalidRequest, "invalid raytrace step or completed task")); } for _ in 0..units.min(4) { - if self.maps.first().is_some_and(|maps| !maps.ready()) { - self.maps - .first_mut() - .ok_or_else(|| invalid("CPU map cache disappeared"))? - .prepare_one(&self.cancel, &mut |units| self.work.charge(units, &self.cancel).map_err(error))?; + if self.optical.first().is_some_and(|optical| !optical.preparation.is_empty()) { + let optical = self.optical.first_mut().ok_or_else(|| invalid("missing optical preparation"))?; + let task = optical.preparation.first_mut().ok_or_else(|| invalid("missing legacy certificate cursor"))?; + if task.ready() { + self.work.tick(&self.cancel).map_err(error)?; + let proof = optical + .preparation + .pop() + .ok_or_else(|| invalid("missing completed legacy certificate"))? + .into_proof(self.work.used()) + .map_err(error)?; + optical.certificates = proof.into_legacy()?; + optical.preparation = Vec::new(); + } else { + task.step(&self.scene, &self.options, &mut self.work, &self.cancel).map_err(legacy_error)?; + } } else if self.progressive.as_ref().is_some_and(|p| !p.film.ready()) { self.progressive .as_mut() .ok_or_else(|| invalid("missing progressive initialization"))? .film .initialize_one(&self.cancel, &mut || self.work.tick(&self.cancel).map_err(error))?; + } else if !self.output.is_empty() { + let guides = self.denoise.first().map(super::denoise::Guides::pixels).transpose()?; + let counts = self.progressive.as_ref().map(|p| p.film.counts()).transpose()?.flatten(); + let output = self.output.first_mut().ok_or_else(|| invalid("missing CPU output task"))?; + match output.step(guides, counts, &mut |units| self.work.charge(units, &self.cancel).map_err(error))? { + TaskPoll::Pending(_) => {} + TaskPoll::Complete(png) => { + let output = self.output.pop().ok_or_else(|| invalid("missing completed CPU output task"))?; + let (rgba, exr) = output.finish()?; + self.pixels = rgba; + self.linear_exr = exr; + return self.complete_png(png, true); + } + } } else if let Some(encoder) = &mut self.encoder { if self.progressive.is_some() { self.work @@ -1566,26 +2030,38 @@ impl ImageTask { .map_err(error)?; } if let Some(png) = encoder.step(&self.pixels)? { - self.cancel.check()?; - if let Some(progressive) = &mut self.progressive { - // The host hashes these exact bytes incrementally. Debit - // their full scan here, before handing ownership over. - self.work.charge(png.len() as u64, &self.cancel).map_err(error)?; - let samples_per_pixel = progressive.film.samples(); - if samples_per_pixel < progressive.options.samples_per_pixel { - progressive.resolving = false; - progressive.resolve_pixel = 0; - self.encoder = None; - self.pixels.clear(); - self.pixel = 0; - return Ok(ImagePoll::Preview { png, samples_per_pixel }); - } - } - self.release_completed_work()?; - return Ok(ImagePoll::Complete(png)); + return self.complete_png(png, false); } } else if self.progressive.as_ref().is_some_and(|p| p.resolving) { self.resolve_progressive_one()?; + } else if self.maps.first().is_some_and(|maps| !maps.ready()) { + self.maps + .first_mut() + .ok_or_else(|| invalid("CPU map cache disappeared"))? + .prepare_one(&self.cancel, &mut |units| self.work.charge(units, &self.cancel).map_err(error))?; + } else if self.pixel == 0 && self.progressive.as_ref().is_some_and(|p| p.film.pilot_complete()) { + // The last pilot first takes the ordinary complete-pass resolve, + // finishing and PNG handoff. Only complete_png resets pixel to0; + // keep that pilot's film/counts available to finishing and host + // preview metadata until the next cooperative step begins reset. + self.progressive + .as_mut() + .ok_or_else(|| invalid("missing CPU pilot handoff"))? + .film + .begin_production(&self.cancel, &mut || self.work.tick(&self.cancel).map_err(error))?; + } else if self.progressive.as_ref().is_some_and(|p| p.film.resetting()) { + self.progressive + .as_mut() + .ok_or_else(|| invalid("missing CPU production reset"))? + .film + .reset_one(&self.cancel, &mut || self.work.tick(&self.cancel).map_err(error))?; + } else if self.glass.first().is_some_and(|glass| !glass.ready()) { + self.glass.first_mut().ok_or_else(|| invalid("CPU glass certificate disappeared"))?.step( + &self.scene, + &self.options, + &mut self.work, + &self.cancel, + )?; } else if self.environment.as_ref().is_some_and(|e| !e.ready()) { self.work.tick(&self.cancel).map_err(error)?; self.environment @@ -1593,16 +2069,28 @@ 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.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( + PreparedScene { bvh, primitives: &self.looks, source: &self.scene }, + &self.request, + &self.options, + self.clip, + &self.effects, + self.maps.first_mut(), + self.aging.first_mut(), + &mut self.work, + &self.cancel, + )?; } else if self.bvh.is_some() { if self.pixel == self.request.width as usize * self.request.height as usize { if let Some(progressive) = &mut self.progressive { self.work.tick(&self.cancel).map_err(error)?; - let samples = progressive.film.samples(); - if samples == progressive.options.samples_per_pixel || samples.is_power_of_two() { - progressive.resolving = true; - } else { - self.pixel = 0; - } + // Resolve every complete pass. The host keeps at most two + // immutable snapshots without changing sample order. + progressive.resolving = true; + } else if self.needs_linear_pass() { + self.start_output()?; } else { self.encoder = Some(job::encoding::PngEncoding::new( self.request.width, @@ -1611,8 +2099,19 @@ impl ImageTask { self.cancel.clone(), )?); } + } else if self.progressive.as_ref().map(|p| p.film.identity(self.pixel, p.options.seed)).transpose()?.is_some_and(|i| i.is_none()) { + self.progressive.as_mut().ok_or_else(|| invalid("missing CPU stopped-pixel film"))?.film.skip( + self.pixel, + &self.cancel, + &mut || self.work.tick(&self.cancel).map_err(error), + )?; + self.pixel += 1; } else { - self.pixel_one()?; + if self.options.path.is_some() { + indirect_image::step(self)?; + } else { + self.pixel_one()?; + } } } else if let Some(builder) = &mut self.builder { let progress = builder.step(1, &self.cancel).map_err(error)?; @@ -1637,10 +2136,25 @@ fn resolved_surface_hit<'a>( pending: &PendingPixel, effects: &[(usize, crate::surface_patterns::PreparedEffect)], maps: Option<&job::textures::cpu_cache::CpuTextureCache>, + aging: Option<&super::aging::Task>, ) -> job::Result> { if !pending.surface_ready { - return Err(invalid("mapped surface is incomplete")); + return Err(invalid("surface effect is not completely resolved")); } + let mut shared = unaged_surface_hit(scene, pending, effects, maps)?; + if let Some(aging) = aging { + let changed = aging.surface()?; + shared.surface = changed.surface; + shared.shading_normal = changed.shading_normal; + } + Ok(shared) +} +fn unaged_surface_hit<'a>( + scene: &PreparedScene<'a>, + pending: &PendingPixel, + effects: &[(usize, crate::surface_patterns::PreparedEffect)], + maps: Option<&job::textures::cpu_cache::CpuTextureCache>, +) -> job::Result> { let mut shared = unmapped_surface_hit(scene, pending, effects)?; if let Some(maps) = maps { let mapped = maps.surface()?; @@ -1655,7 +2169,7 @@ fn unmapped_surface_hit<'a>( effects: &[(usize, crate::surface_patterns::PreparedEffect)], ) -> job::Result> { if pending.surface_cursor != effects.len() { - return Err(invalid("surface effect is not completely resolved")); + return Err(invalid("surface effect scan is incomplete")); } let mut shared = scene.resolve_hit(pending.ray, pending.hit.ok_or_else(|| invalid("missing prepared surface hit"))?).map_err(error)?; if let Some(index) = pending.surface_index { @@ -1684,17 +2198,46 @@ fn primary_footprint( normal: Vec3, ) -> job::Result> { let width = request.width as usize; - let offset = if let Some(progressive) = progressive { - progressive::variates(progressive.options.seed, pixel as u64, progressive.film.samples(), 0) - } else { - primary_offset(options.primary_samples, spatial)? - }; + let offset = + if let Some(progressive) = progressive { progressive.variates(pixel, 0)? } else { primary_offset(options.primary_samples, spatial)? }; let x = (pixel % width) as f64 + offset[0]; let y = (pixel / width) as f64 + offset[1]; let spacing = if progressive.is_some() { 1.0 } else { 1.0 / f64::from(options.primary_samples).sqrt() }; + if let Some(lens) = options.lens.filter(|lens| lens.aperture_radius_mm > 0.0) { + // Counter-based lookup reproduces the primary ray's pupil without advancing + // its sampler or adding a dimension. Hold that pupil for both neighbours. + let progressive = progressive.ok_or_else(|| invalid("physical pupil requires progressive camera sampling"))?; + let pupil = progressive.variates(pixel, 0x4c454e53)?; + plane_footprint(position, normal, spacing, |dx, dy| lens_primary_ray(request, x + dx, y + dy, clip, lens, pupil).map_err(error)) + } else { + camera_footprint(request, x, y, spacing, clip, position, normal) + } +} + +/// Same geometric-plane footprint for deterministic guide rays, without changing +/// their center sample or the progressive camera's sampling stream. +#[allow(clippy::too_many_arguments)] +pub(super) fn camera_footprint( + request: &ImageRequest, + x: f64, + y: f64, + spacing: f64, + clip: (f64, f64), + position: Vec3, + normal: Vec3, +) -> job::Result> { + plane_footprint(position, normal, spacing, |dx, dy| primary_ray(request, x + dx, y + dy, clip).map_err(error)) +} + +fn plane_footprint( + position: Vec3, + normal: Vec3, + spacing: f64, + mut neighbour: impl FnMut(f64, f64) -> job::Result, +) -> job::Result> { let mut result = [Vec3::ZERO; 2]; for (output, [dx, dy]) in result.iter_mut().zip([[spacing, 0.0], [0.0, spacing]]) { - let ray = primary_ray(request, x + dx, y + dy, clip).map_err(error)?; + let ray = neighbour(dx, dy)?; let denominator = ray.direction().dot(normal); if !denominator.is_finite() || denominator.abs() < 1e-12 { return Ok(None); @@ -1751,6 +2294,37 @@ fn area_sample_key(pixel: u64, spatial: u8, spatial_samples: u8, film_sample: u3 .ok_or_else(|| invalid("area-light sample identity overflow")) } +/// Straight-alpha display from primary geometric coverage. Keep the original +/// opaque f64 route untouched, including its unexposed display backplate. +fn composite_spatial_alpha( + premultiplied: Vec3, + covered: u16, + attempts: u16, + background: [u8; 3], + exposure: f64, + transparent: bool, +) -> job::Result<[u8; 4]> { + if !transparent { + return composite_spatial(premultiplied, covered, attempts, background, exposure); + } + if attempts == 0 || u32::from(attempts) > job::MAX_CPU_SAMPLES_PER_PIXEL || covered > attempts || !bounded_radiance(premultiplied) { + return Err(invalid("invalid transparent coverage/radiance")); + } + if covered == 0 { + if premultiplied != Vec3::ZERO { + return Err(invalid("uncovered transparent radiance")); + } + return Ok([0; 4]); + } + let coverage = f64::from(covered) / f64::from(attempts); + let alpha = (coverage * 255.0).round() as u8; + if alpha == 0 { + return Ok([0; 4]); + } + let display = map_to_display(premultiplied / coverage, exposure).map_err(error)?; + Ok([encode8(display.x), encode8(display.y), encode8(display.z), alpha]) +} + fn composite_spatial(premultiplied: Vec3, covered: u16, attempts: u16, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { if attempts == 0 || u32::from(attempts) > job::MAX_CPU_SAMPLES_PER_PIXEL || covered > attempts || !bounded_radiance(premultiplied) { return Err(invalid("invalid spatial coverage/radiance")); @@ -1890,7 +2464,41 @@ fn shadow_ray(ray: Ray, hit: super::Hit, light: Vec3, vertices: [Vec3; 3]) -> su Ray::new(Vec3::new(outward(shifted.x, n.x), outward(shifted.y, n.y), outward(shifted.z, n.z)), light, 0.0_f64.next_up(), super::MAX_DISTANCE_MM) } -fn primary_ray(request: &ImageRequest, x: f64, y: f64, clip: (f64, f64)) -> super::Result { +/// A circular pupil in the eye plane, focused at an axial distance. The +/// original primary generator remains untouched for absent or zero aperture. +fn lens_primary_ray(request: &ImageRequest, x: f64, y: f64, clip: (f64, f64), lens: job::ThinLens, pupil: [f64; 2]) -> super::Result { + if lens.aperture_radius_mm == 0.0 { + return primary_ray(request, x, y, clip); + } + if pupil.into_iter().any(|v| !v.is_finite() || !(0.0..1.0).contains(&v)) { + return Err(TraceError::InvalidInput("thin-lens pupil sample")); + } + let camera = &request.camera; + let (right, up, back) = camera.basis(); + let eye = camera.eye(); + let (_, pinhole) = camera.ray(x, y, request.width as f64, request.height as f64); + let cosine = pinhole.dot(-back); + if !cosine.is_finite() || cosine <= 0.0 { + return Err(TraceError::InvalidInput("thin-lens camera direction")); + } + let radius = lens.aperture_radius_mm * pupil[0].sqrt(); + let phi = std::f64::consts::TAU * pupil[1]; + let displacement = (right * phi.cos() + up * phi.sin()) * radius; + // Work in eye-relative coordinates so large world translations cannot erase + // a small pupil before computing its aimed direction. + let focused = pinhole * (lens.focus_distance_mm / cosine); + let direction = super::unit(focused - displacement).ok_or(TraceError::InvalidInput("thin-lens focus direction"))?; + let cosine = direction.dot(-back); + if !cosine.is_finite() || cosine <= 0.0 { + return Err(TraceError::InvalidInput("thin-lens forward interval")); + } + let origin = eye + displacement; + let depth = (origin - eye).dot(-back); + let start = (clip.0 - depth) / cosine; + Ray::new(origin + direction * start, direction, 0.0, (clip.1 - clip.0) / cosine) +} + +pub(super) fn primary_ray(request: &ImageRequest, x: f64, y: f64, clip: (f64, f64)) -> super::Result { let camera = &request.camera; let (mut origin, direction) = camera.ray(x, y, request.width as f64, request.height as f64); if camera.fov == 0.0 { diff --git a/crates/render/src/raytrace/image_indirect.rs b/crates/render/src/raytrace/image_indirect.rs new file mode 100644 index 000000000..855f71b71 --- /dev/null +++ b/crates/render/src/raytrace/image_indirect.rs @@ -0,0 +1,1241 @@ +//! 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_scattering.rs"] +mod scattering; +#[path = "image_volume.rs"] +mod volume; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Stage { + New, + Origin, + Medium, + MediumOrigin, + MediumScatter, + MediumSurface, + Volume, + VolumeSurface, + VolumeShadow, + Trace, + Emitters, + Resolve, + Glass, + ShadowBeer, + ShadowGlass, + Effects, + Maps, + Aging, + Emission, + Directional, + Punctual, + Area, + Environment, + Sun, + Shadow, + ShadowEmitters, + Add, + Scatter, + Commit, +} +pub(super) struct State { + stage: Stage, + optical: Option, + volume: Option, + origins: Vec, + ray: Option, + cursor: Option, + hit: Option, + emitter: Option<(usize, f64, Vec3)>, + emitter_cursor: usize, + effect_cursor: usize, + effect: Option, + emission_cursor: usize, + light: usize, + sample: u32, + depth: u8, + throughput: Vec3, + radiance: Vec3, + previous_pdf: f64, + previous_position: Vec3, + contribution: Vec3, + after_shadow: Stage, + shadow_ray: Option, + shadow_emitter: usize, + shadow_excluded: Option, +} +impl Default for State { + fn default() -> Self { + Self { + stage: Stage::New, + optical: None, + volume: None, + origins: Vec::new(), + ray: None, + cursor: None, + hit: None, + emitter: None, + emitter_cursor: 0, + effect_cursor: 0, + effect: None, + emission_cursor: 0, + light: 0, + sample: 0, + depth: 0, + throughput: Vec3::new(1.0, 1.0, 1.0), + radiance: Vec3::ZERO, + previous_pdf: 0.0, + previous_position: Vec3::ZERO, + contribution: Vec3::ZERO, + after_shadow: Stage::Directional, + shadow_ray: None, + shadow_emitter: 0, + shadow_excluded: None, + } + } +} +#[cfg(test)] +pub(super) struct ShadowProbe { + pub ray_origin: Option, + pub contribution: Vec3, + pub probability: f64, + pub from: Vec3, + pub endpoint: Option, + pub mis: Option<[f64; 2]>, + pub radiance: Vec3, +} +#[cfg(test)] +pub(super) struct VolumeProbe { + pub source: Vec3, + pub incoming: Option, + pub ray: Option, + pub shadow: Option, + pub mis: Option<[f64; 2]>, + pub survival: f64, + pub contribution: Vec3, + pub radiance: Vec3, + pub throughput: Vec3, + pub depth: u8, +} +#[cfg(test)] +pub(super) struct MediumProbe { + pub ray_origin: Option, + pub depth: u8, + pub delta: bool, + pub pdf: f64, + pub throughput: Vec3, + pub from: Vec3, + pub emitter: Option, +} +#[cfg(test)] +impl State { + pub(super) fn volume_probe(&self) -> Option { + self.volume.as_ref().map(|v| VolumeProbe { + source: v.source, + incoming: v.event, + ray: self.ray, + shadow: self.shadow_ray, + mis: v.shadow_mis, + survival: v.shadow_probability, + contribution: self.contribution, + radiance: self.radiance, + throughput: self.throughput, + depth: self.depth, + }) + } + pub(super) fn surface_source(&self) -> Option<(u8, Ray, super::super::Hit)> { + Some((self.depth, self.ray?, self.hit?)) + } + pub(super) fn shadow_probe(&self) -> Option { + self.optical.as_ref().map(|o| ShadowProbe { + ray_origin: o.shadow_current.map(Ray::origin), + contribution: self.contribution, + probability: o.shadow_probability, + from: o.shadow_start, + endpoint: o.shadow_endpoint, + mis: o.shadow_mis, + radiance: self.radiance, + }) + } + pub(super) fn medium_probe(&self) -> Option { + self.optical.as_ref().map(|o| MediumProbe { + ray_origin: self.ray.map(Ray::origin), + depth: self.depth, + delta: o.delta, + pdf: self.previous_pdf, + throughput: self.throughput, + from: o.segment_start, + emitter: self.emitter.map(|(_, _, p)| p), + }) + } + pub(super) fn origin_slot_info(&self) -> (usize, usize, bool) { + (self.origins.len(), self.origins.capacity(), self.origins.first().is_some_and(|o| o.ready())) + } + pub(super) fn initial_medium(&self) -> Option<([usize; 8], usize, Vec3)> { + self.optical.as_ref().map(|o| (o.media, o.len, o.segment_start)) + } + pub(super) fn stage_name(&self) -> &'static str { + match self.stage { + Stage::New => "new", + Stage::Origin => "origin", + Stage::Medium => "medium", + Stage::MediumOrigin => "medium_origin", + Stage::MediumScatter => "medium_scatter", + Stage::MediumSurface => "medium_surface", + Stage::Volume => "volume", + Stage::VolumeSurface => "volume_surface", + Stage::VolumeShadow => "volume_shadow", + Stage::Trace => "trace", + Stage::Emitters => "emitters", + Stage::Resolve => "resolve", + Stage::Glass => "glass", + Stage::ShadowBeer => "shadow_beer", + Stage::ShadowGlass => "shadow_glass", + Stage::Effects => "effects", + Stage::Maps => "maps", + Stage::Aging => "aging", + Stage::Emission => "emission", + Stage::Directional => "directional", + Stage::Punctual => "punctual", + Stage::Area => "area", + Stage::Environment => "environment", + Stage::Sun => "sun", + Stage::Shadow => "shadow", + Stage::ShadowEmitters => "shadow_emitters", + Stage::Add => "add", + Stage::Scatter => "scatter", + Stage::Commit => "commit", + } + } +} +fn variates(task: &ImageTask, state: &State, domain: u64) -> job::Result<[f64; 2]> { + let p = task.progressive.as_ref().ok_or_else(|| invalid("CPU path needs progressive film"))?; + p.variates(task.pixel, (0x5041_5448_0000_u64 + u64::from(state.depth) * 0x10000).wrapping_add(domain)) +} +fn continuing(task: &ImageTask, state: &State) -> job::Result { + Ok(state.depth + 1 < task.options.path.ok_or_else(|| invalid("CPU path settings disappeared"))?.max_depth) +} +fn shared<'a>(task: &'a ImageTask, state: &State) -> job::Result> { + let mut hit = unaged(task, state)?; + if let Some(aging) = task.aging.first() { + let changed = aging.surface()?; + hit.surface = changed.surface; + hit.shading_normal = changed.shading_normal; + } + Ok(hit) +} +fn unaged<'a>(task: &'a ImageTask, state: &State) -> job::Result> { + let mut hit = unmapped(task, state)?; + if let Some(maps) = task.maps.first() { + let mapped = maps.surface()?; + hit.surface = mapped.surface; + hit.shading_normal = mapped.shading_normal; + } + Ok(hit) +} +fn unmapped<'a>(task: &'a ImageTask, state: &State) -> job::Result> { + let bvh = task.bvh.as_ref().ok_or_else(|| invalid("CPU path BVH missing"))?; + let scene = PreparedScene { bvh, primitives: &task.looks, source: &task.scene }; + let mut hit = scene + .resolve_hit(state.ray.ok_or_else(|| invalid("CPU path ray missing"))?, state.hit.ok_or_else(|| invalid("CPU path hit missing"))?) + .map_err(error)?; + if let Some(index) = state.effect { + let (_, effect) = task.effects.get(index).ok_or_else(|| invalid("CPU path effect missing"))?; + let changed = effect.apply(hit.surface, hit.shading_normal, hit.oriented_geometric_normal(), hit.position)?; + hit.surface = changed.surface; + hit.shading_normal = changed.shading_normal; + } + Ok(hit) +} +fn response(task: &ImageTask, state: &State, direction: Vec3) -> job::Result { + if state.volume.is_some() + && let Some(phase) = volume::response(task, state, direction)? + { + return Ok(Vec3::new(phase, phase, phase)); + } + let hit = shared(task, state)?; + let view = -state.ray.ok_or_else(|| invalid("CPU path ray missing"))?.direction(); + if hit.oriented_geometric_normal().dot(direction) <= 0.0 || hit.oriented_geometric_normal().dot(view) <= 0.0 { + return Ok(Vec3::ZERO); + } + hit.surface + .brdf(hit.shading_normal, view, direction) + .map(|f| f * hit.shading_normal.dot(direction).max(0.0)) + .map_err(|_| invalid("CPU path direct response")) +} +fn light_weight(task: &ImageTask, state: &State, direction: Vec3, pdf: f64, samples: u32) -> job::Result { + if !continuing(task, state)? || state.optical.is_some() || state.volume.is_some() { + return Ok(1.0); + } + let hit = shared(task, state)?; + let view = -state.ray.ok_or_else(|| invalid("CPU path ray missing"))?.direction(); + let bsdf = indirect::surface_pdf(hit.surface, hit.shading_normal, view, direction).map_err(error)?; + power_weight(f64::from(samples) * pdf, bsdf).map_err(error) +} +fn queue(task: &ImageTask, state: &mut State, value: Vec3, ray: Option, next: Stage) -> job::Result<()> { + state.contribution = multiply(state.throughput, value); + super::super::lighting::validate_radiance(state.contribution).map_err(error)?; + state.after_shadow = next; + state.shadow_excluded = None; + let shadow_start = if state.optical.is_some() { Some(unmapped(task, state)?.position) } else { None }; + if let Some(optical) = &mut state.optical { + optical.shadow_start = shadow_start.ok_or_else(|| invalid("CPU glass shadow origin disappeared"))?; + optical.shadow_mis = None; + optical.shadow_probability = 1.0; + optical.shadow_interfaces = 0; + optical.shadow_endpoint = None; + optical.shadow_inclusive = true; + optical.shadow_exact = false; + optical.shadow_current = ray; + optical.shadow_hit = None; + } + if let Some(v) = &mut state.volume { + v.shadow_mis = None; + v.shadow_probability = 1.0; + } + if task.options.shadows + && value != Vec3::ZERO + && let Some(ray) = ray + { + state.shadow_ray = Some(ray); + state.shadow_emitter = 0; + state.cursor = Some(if state.volume.is_some() { volume::cursor(task, state, ray)? } else { TraceCursor::new(ray, state.optical.is_none()) }); + state.stage = Stage::Shadow; + } else { + state.stage = Stage::Add; + } + Ok(()) +} +fn bounded_shadow(hit: super::super::prepared::SharedHit<'_>, point: Vec3, direction: Vec3) -> job::Result> { + let origin = hit.spawn(direction).map_err(error)?.origin(); + let delta = point - origin; + let distance = delta.len(); + if delta.dot(direction) <= 0.0 || !distance.is_finite() || distance.next_down() <= 0.0_f64.next_up() { + return Ok(None); + } + // Geometry wins equal-distance model/emitter ties in Stage::Emitters. Keep + // the sampled endpoint in model visibility too; only the analytic source + // itself is excluded separately from the emitter-occluder scan. + Ray::new(origin, delta, 0.0_f64.next_up(), distance).map(Some).map_err(error) +} + +pub(super) fn step(task: &mut ImageTask) -> job::Result<()> { + // Taking this fixed slot avoids aliasing the source scene with the mutable worker. + // Its exact capacity was reserved before transport; returning it cannot allocate. + let mut state = task.path.pop().ok_or_else(|| invalid("CPU path continuation missing"))?; + if state.stage == Stage::Commit { + task.finish_sample(state.radiance)?; + let mut origins = std::mem::take(&mut state.origins); + origins.clear(); + task.path.push(State { origins, ..Default::default() }); + return Ok(()); + } + let result = advance(task, &mut state); + task.path.push(state); + result +} +fn advance(task: &mut ImageTask, state: &mut State) -> job::Result<()> { + 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() { + task.work.tick(&task.cancel).map_err(error)?; + let (media, len, start) = origin.result()?; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU initial medium state missing"))?; + if state.stage == Stage::MediumOrigin { + if len != optical.len || media[..len] != optical.media[..len] { + return Err(invalid("CPU subsurface collision disagrees with the certified current medium")); + } + state.stage = Stage::MediumScatter; + return Ok(()); + } + optical.media = media; + optical.len = len; + optical.segment_start = start; + optical.delta = true; + state.cursor = Some(TraceCursor::new(state.ray.ok_or_else(|| invalid("CPU classified primary ray missing"))?, false)); + state.stage = Stage::Trace; + } else { + let certificate = task.glass.first().ok_or_else(|| invalid("CPU closed geometry certificate missing"))?; + let bvh = task.bvh.as_ref().ok_or_else(|| invalid("CPU origin classification BVH missing"))?; + origin.step( + certificate, + &task.options.dielectrics, + PreparedScene { bvh, primitives: &task.looks, source: &task.scene }, + &mut task.work, + &task.cancel, + )?; + } + return Ok(()); + } + + if state.stage == Stage::Shadow && scattering::needs_shadow_setup(state) { + task.work.tick(&task.cancel).map_err(error)?; + scattering::shadow_setup(task, state)?; + return Ok(()); + } + if state.stage == Stage::Trace || state.stage == Stage::Shadow { + let bvh = task.bvh.as_ref().ok_or_else(|| invalid("CPU path BVH missing"))?; + let cursor = state.cursor.as_mut().ok_or_else(|| invalid("CPU path traversal cursor missing"))?; + let complete = if state.optical.is_some() { + let looks = &task.looks; + let inputs = &task.options.dielectrics; + cursor.step_ordered(bvh, &mut task.work, &task.cancel, |new, old| { + let optical = |hit: super::super::Hit| { + looks.get(hit.primitive_index).is_some_and(|look| inputs.iter().any(|input| input.body_index == look.body_index)) + }; + // Opaque contact keeps its visible material. At a glass resting + // on a plane, shading reflects into the incident medium; crossing + // and then suppressing the coplanar plane would lose that surface. + match (optical(new), optical(old)) { + (false, true) => true, + (true, false) => false, + _ => new.primitive_index < old.primitive_index, + } + }) + } else { + cursor.step(bvh, &mut task.work, &task.cancel) + } + .map_err(error)?; + let Some(hit) = complete else { + return Ok(()); + }; + state.cursor = None; + if state.stage == Stage::Shadow { + if let Some(optical) = &mut state.optical { + optical.shadow_hit = hit; + state.stage = Stage::ShadowBeer; + } else if hit.is_some() { + state.contribution = Vec3::ZERO; + state.stage = Stage::Add; + } else { + state.stage = if state.volume.is_some() { Stage::VolumeShadow } else { Stage::ShadowEmitters }; + } + } else { + state.hit = hit; + volume::reset_hit(state); + if let Some(optical) = &mut state.optical { + optical.surface_range = None; + } + if let Some(maps) = task.maps.first_mut() { + maps.reset_hit(); + } + if let Some(aging) = task.aging.first_mut() { + aging.reset(); + } + state.emitter = None; + state.emitter_cursor = 0; + state.stage = Stage::Emitters; + } + return Ok(()); + } + task.work.tick(&task.cancel).map_err(error)?; + match state.stage { + Stage::New => { + let p = task.progressive.as_ref().ok_or_else(|| invalid("CPU path progressive film missing"))?; + if task.options.lens.is_some_and(|l| l.aperture_radius_mm > 0.0) && task.pupil_sample.is_none() { + task.pupil_sample = Some(p.variates(task.pixel, 0x4c454e53)?); + return Ok(()); + } + let [dx, dy] = p.variates(task.pixel, 0)?; + let x = (task.pixel % task.request.width as usize) as f64 + dx; + let y = (task.pixel / task.request.width as usize) as f64 + dy; + let mut physical_origin = None; + let ray = if let Some(lens) = task.options.lens.filter(|l| l.aperture_radius_mm > 0.0) { + let pupil = task.pupil_sample.take().ok_or_else(|| invalid("CPU path pupil missing"))?; + let ray = lens_primary_ray(&task.request, x, y, task.clip, lens, pupil).map_err(error)?; + if !task.glass.is_empty() || volume::enabled(task) { + let (right, up, _) = task.request.camera.basis(); + let radius = lens.aperture_radius_mm * pupil[0].sqrt(); + let phi = std::f64::consts::TAU * pupil[1]; + physical_origin = Some(task.request.camera.eye() + (right * phi.cos() + up * phi.sin()) * radius); + } + ray + } else { + let ray = primary_ray(&task.request, x, y, task.clip).map_err(error)?; + if (!task.glass.is_empty() || volume::enabled(task)) && task.request.camera.fov > 0.0 { + physical_origin = Some(task.request.camera.eye()); + } + ray + }; + let ray = if volume::enabled(task) { volume::primary(task, ray, physical_origin)? } else { ray }; + if volume::enabled(task) { + volume::begin(task, state, ray)?; + } + state.ray = Some(ray); + state.cursor = Some(TraceCursor::new(ray, false)); + state.stage = Stage::Trace; + if let Some(certificate) = task.glass.first() { + state.optical = Some(GlassPath { segment_start: ray.origin(), ..Default::default() }); + let origin = physical_origin.unwrap_or(ray.origin()); + if super::super::origin::Task::required(certificate, &task.options.dielectrics, origin, ray.origin())? { + if !state.origins.is_empty() { + return Err(invalid("CPU prior origin certificate was not drained")); + } + if state.origins.capacity() == 0 { + state.origins.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + } + if state.origins.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + state.origins.push(super::super::origin::Task::new(origin, ray.origin())?); + state.cursor = None; + state.stage = Stage::Origin; + } + } + } + + Stage::Emitters => { + if let Some(input) = task.options.area_lights.as_ref().and_then(|v| v.get(state.emitter_cursor)) { + let light = Rectangle::new(input).map_err(error)?; + if let Some((distance, position)) = light.intersect(state.ray.ok_or_else(|| invalid("CPU path ray missing"))?).map_err(error)? + && state.hit.is_none_or(|hit| distance < hit.geometry.distance) + && state.emitter.is_none_or(|(_, prior, _)| distance < prior) + { + state.emitter = Some((state.emitter_cursor, distance, position)); + } + state.emitter_cursor += 1; + } else { + state.stage = if state.volume.is_some() { + Stage::Volume + } else if scattering::active(task, state)? { + Stage::Medium + } else { + Stage::Resolve + }; + } + } + Stage::Medium | Stage::MediumScatter | Stage::MediumSurface => scattering::step(task, state)?, + Stage::Volume | Stage::VolumeSurface | Stage::VolumeShadow => volume::step(task, state)?, + Stage::Resolve => { + if state.optical.is_some() { + if let Some((_, _, position)) = state.emitter { + beer(task, state, position, false)?; + } else if state.hit.is_some() { + let position = unmapped(task, state)?.position; + beer(task, state, position, false)?; + } else if state.optical.as_ref().is_some_and(|optical| optical.len != 0) { + return Err(invalid("CPU ray escaped a certified closed glass medium")); + } + } + if let Some((index, _, position)) = state.emitter { + let input = task.options.area_lights.as_ref().and_then(|v| v.get(index)).ok_or_else(|| invalid("CPU path emitter disappeared"))?; + let light = Rectangle::new(input).map_err(error)?; + let weight = if state.depth == 0 || state.optical.as_ref().is_some_and(|optical| optical.delta) { + 1.0 + } else { + power_weight( + state.previous_pdf, + f64::from(task.options.area_samples.unwrap_or(16)) * light.pdf(state.previous_position, position).map_err(error)?, + ) + .map_err(error)? + }; + state.radiance += multiply(state.throughput, light.radiance) * weight; + if state.depth == 0 { + task.primary_coverage = 1; + } + state.stage = Stage::Commit; + } else if state.hit.is_some() { + if state.depth == 0 { + task.primary_coverage = 1; + } + state.effect_cursor = 0; + state.effect = None; + state.emission_cursor = 0; + if let Some(optical) = &mut state.optical { + optical.selector = 0; + optical.selected = None; + state.stage = Stage::Glass; + } else if state.volume.is_some() { + volume::surface(task, state)?; + } else { + state.stage = Stage::Effects; + } + } else { + // A camera miss remains the separate unexposed display background. + if state.depth > 0 { + let direction = state.ray.ok_or_else(|| invalid("CPU escaped path ray missing"))?.direction(); + let (radiance, pdf, n) = if let Some(environment) = &task.environment { + let env = environment.view().map_err(environment_error)?; + ( + env.radiance_linear_srgb(direction).map_err(environment_error)?, + env.pdf_solid_angle(direction).map_err(environment_error)?, + environment.samples, + ) + } else if let Some(sky) = task.options.sky.as_deref() { + (sky.radiance(direction)?, indirect::ENVIRONMENT_PDF, 1) + } else if let Some(environment) = task.options.environment { + ( + Vec3::new(environment.color[0], environment.color[1], environment.color[2]) * environment.intensity, + indirect::ENVIRONMENT_PDF, + 1, + ) + } else { + (Vec3::ZERO, 0.0, 0) + }; + let weight = if state.optical.as_ref().is_some_and(|optical| optical.delta) { + 1.0 + } else { + power_weight(state.previous_pdf, f64::from(n) * pdf).map_err(error)? + }; + state.radiance += multiply(state.throughput, radiance) * weight; + if let Some(sun) = task.options.sun.as_deref().copied() { + let pdf = super::super::celestial::pdf(sun, direction).map_err(error)?; + let weight = if state.optical.as_ref().is_some_and(|o| o.delta) { + 1.0 + } else { + power_weight(state.previous_pdf, pdf).map_err(error)? + }; + state.radiance += multiply(state.throughput, super::super::celestial::radiance(sun, direction).map_err(error)?) * weight; + } + } + state.stage = Stage::Commit; + } + super::super::lighting::validate_radiance(state.radiance).map_err(error)?; + } + Stage::Glass => { + glass_one(task, state)?; + } + Stage::ShadowBeer => { + shadow_beer(task, state)?; + } + Stage::ShadowGlass => { + shadow_glass(task, state)?; + } + Stage::Effects => { + let hit = unmapped(task, state)?; + if let Some((body, _)) = task.effects.get(state.effect_cursor) { + if *body == hit.body_index { + state.effect = Some(state.effect_cursor); + state.effect_cursor = task.effects.len(); + } else { + state.effect_cursor += 1; + } + } else { + state.stage = if !task.maps.is_empty() { + Stage::Maps + } else if !task.aging.is_empty() { + Stage::Aging + } else { + Stage::Emission + }; + } + } + Stage::Maps => { + let input = { + let hit = unmapped(task, state)?; + let has_face_override = task.looks.get(hit.primitive_index).is_none_or(|look| look.has_face_override); + // Primary rays retain the upstream physical footprint. Secondary + // derivatives are unavailable, so the cache selects its coarsest mip. + let footprint = if state.depth == 0 { + primary_footprint( + &task.request, + &task.options, + task.progressive.as_ref(), + task.pixel, + task.spatial, + task.clip, + hit.position, + hit.oriented_geometric_normal(), + )? + } else { + None + }; + ( + crate::surface_patterns::ShadingSurface { surface: hit.surface, shading_normal: hit.shading_normal }, + (!has_face_override).then_some(hit.body_index), + crate::job::textures::cpu_preparation::MapPoint { + position: hit.position, + geometric_normal: hit.oriented_geometric_normal(), + view_direction: -state.ray.ok_or_else(|| invalid("CPU mapped path ray missing"))?.direction(), + }, + footprint, + ) + }; + let maps = task.maps.first_mut().ok_or_else(|| invalid("CPU path map cache disappeared"))?; + if !maps.hit_started() { + maps.begin_hit(input.0, input.1, input.2, input.3)?; + } + if maps.hit_ready() || maps.advance_hit()? { + state.stage = if task.aging.is_empty() { Stage::Emission } else { Stage::Aging }; + } + } + Stage::Aging => { + let input = { + let hit = unaged(task, state)?; + ( + crate::surface_patterns::ShadingSurface { surface: hit.surface, shading_normal: hit.shading_normal }, + hit.position, + hit.geometric_normal, + hit.body_index, + super::super::aging::eligible(&task.options, hit.body_index, hit.body_name), + ) + }; + let aging = task.aging.first_mut().ok_or_else(|| invalid("CPU path aging task disappeared"))?; + if !aging.started() { + aging.begin(input.0, input.1, input.2, input.3, input.4)?; + } + if aging.ready() || aging.advance(task.options.aging.as_deref().ok_or_else(|| invalid("CPU path aging stack disappeared"))?)? { + state.stage = Stage::Emission; + } + } + Stage::Emission => { + if let Some((body, emission)) = task.emissions.get(state.emission_cursor) { + let hit = shared(task, state)?; + if *body == hit.body_index { + state.radiance += multiply(state.throughput, emission.radiance(hit.front_face)); + } + state.emission_cursor += 1; + super::super::lighting::validate_radiance(state.radiance).map_err(error)?; + } else { + state.light = 0; + state.stage = Stage::Directional; + } + } + Stage::Directional => { + if let Some(light) = task.lights.lights().get(state.light) { + let value = multiply(response(task, state, light.direction())?, light.color()) * light.intensity(); + let ray = + volume::ray(task, state, light.direction(), None, true)?.ok_or_else(|| invalid("CPU directional source interval collapsed"))?; + state.light += 1; + queue(task, state, value, Some(ray), Stage::Directional)?; + } else { + state.light = 0; + state.stage = Stage::Punctual; + } + } + Stage::Punctual => { + if let Some(input) = task.options.punctual_lights.as_ref().and_then(|v| v.get(state.light)) { + let sample = input.light().map_err(error)?.sample(volume::source(task, state)?).map_err(error)?; + state.light += 1; + if let Some(why) = sample.omitted { + match why { + super::super::punctual::OmittedSample::NearSource => { + task.punctual_diagnostics.near_source = task.punctual_diagnostics.near_source.saturating_add(1) + } + super::super::punctual::OmittedSample::RadianceLimit => { + task.punctual_diagnostics.radiance_limit = task.punctual_diagnostics.radiance_limit.saturating_add(1) + } + } + } else { + let value = multiply(response(task, state, sample.direction)?, sample.incident_linear_srgb); + if super::super::lighting::validate_radiance(value).is_err() { + task.punctual_diagnostics.radiance_limit = task.punctual_diagnostics.radiance_limit.saturating_add(1); + } else if let Some(ray) = if state.volume.is_some() { + volume::ray( + task, + state, + sample.direction, + Some(Vec3::new(input.position_mm[0], input.position_mm[1], input.position_mm[2])), + false, + )? + } else { + sample.shadow_ray(shared(task, state)?).map_err(error)? + } { + let endpoint = Vec3::new(input.position_mm[0], input.position_mm[1], input.position_mm[2]); + queue(task, state, value, Some(ray), Stage::Punctual)?; + if let Some(optical) = &mut state.optical { + optical.shadow_endpoint = Some(endpoint); + optical.shadow_inclusive = false; + } + } else { + task.punctual_diagnostics.shadow_offset_crossed = task.punctual_diagnostics.shadow_offset_crossed.saturating_add(1); + } + } + } else { + state.light = 0; + state.sample = 0; + state.stage = Stage::Area; + } + } + Stage::Area => { + if let Some(input) = task.options.area_lights.as_ref().and_then(|v| v.get(state.light)) { + let count = task.options.area_samples.unwrap_or(16); + if state.sample == count { + state.light += 1; + state.sample = 0; + return Ok(()); + } + let side = match count { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + let [dx, dy] = variates( + task, + state, + (0x1000 + state.light as u64 * 128 + u64::from(state.sample)) ^ (u64::from(task.options.seed.unwrap_or(0)) << 32), + )?; + let u = [ + indirect::open_stratum(dx, state.sample / side, side).map_err(error)?, + indirect::open_stratum(dy, state.sample % side, side).map_err(error)?, + ]; + let light = Rectangle::new(input).map_err(error)?; + state.sample += 1; + if let Some(sample) = light.sample(volume::source(task, state)?, u).map_err(error)? { + let weight = light_weight(task, state, sample.direction, sample.pdf, count)?; + let value = multiply(response(task, state, sample.direction)?, light.radiance) * (weight / (f64::from(count) * sample.pdf)); + if let Some(ray) = volume::ray(task, state, sample.direction, Some(sample.position), true)? { + queue(task, state, value, Some(ray), Stage::Area)?; + state.shadow_excluded = Some(state.light); + defer_mis(task, state, sample.direction, sample.pdf, count)?; + if let Some(optical) = &mut state.optical { + optical.shadow_endpoint = Some(sample.position); + } + } + } + } else { + state.sample = 0; + state.stage = Stage::Environment; + } + } + Stage::Environment => { + let count = + task.environment.as_ref().map_or_else(|| u32::from(task.options.environment.is_some() || task.options.sky.is_some()), |e| e.samples); + if state.sample == count { + state.stage = if task.options.sun.is_some() { Stage::Sun } else { Stage::Scatter }; + return Ok(()); + } + let side = match count { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + let [dx, dy] = variates(task, state, 0x2000 + u64::from(state.sample))?; + let u = [ + indirect::open_stratum(dx, state.sample / side, side).map_err(error)?, + indirect::open_stratum(dy, state.sample % side, side).map_err(error)?, + ]; + let (direction, emitted, pdf) = if let Some(environment) = &task.environment { + let env = environment.view().map_err(environment_error)?; + env.require_linear_srgb().map_err(environment_error)?; + let sample = env.sample(u).map_err(environment_error)?; + (sample.direction, sample.radiance_source_rgb, sample.pdf_solid_angle) + } else if let Some(sky) = task.options.sky.as_deref() { + let direction = indirect::uniform_environment(u); + (direction, sky.radiance(direction)?, indirect::ENVIRONMENT_PDF) + } else { + let environment = task.options.environment.ok_or_else(|| invalid("CPU path environment missing"))?; + ( + indirect::uniform_environment(u), + Vec3::new(environment.color[0], environment.color[1], environment.color[2]) * environment.intensity, + indirect::ENVIRONMENT_PDF, + ) + }; + let weight = light_weight(task, state, direction, pdf, count)?; + let value = multiply(response(task, state, direction)?, emitted) * (weight / (f64::from(count) * pdf)); + let ray = volume::ray(task, state, direction, None, true)?.ok_or_else(|| invalid("CPU environment source interval collapsed"))?; + state.sample += 1; + queue(task, state, value, Some(ray), Stage::Environment)?; + defer_mis(task, state, direction, pdf, count)?; + } + Stage::Sun => { + let sun = task.options.sun.as_deref().copied().ok_or_else(|| invalid("CPU finite Sun disappeared"))?; + //0x5000/0x5001 are reserved for the independent SSS free-flight/HG arc. + let u = variates(task, state, 0x7000)?; + let sample = super::super::celestial::sample(sun, u).map_err(error)?; + let weight = light_weight(task, state, sample.direction, sample.pdf, 1)?; + let value = multiply(response(task, state, sample.direction)?, sample.radiance) * (weight / sample.pdf); + let ray = volume::ray(task, state, sample.direction, None, true)?.ok_or_else(|| invalid("CPU finite Sun source interval collapsed"))?; + queue(task, state, value, Some(ray), Stage::Scatter)?; + defer_mis(task, state, sample.direction, sample.pdf, 1)?; + } + Stage::ShadowEmitters => { + if let Some(input) = task.options.area_lights.as_ref().and_then(|v| v.get(state.shadow_emitter)) { + let ray = state.shadow_ray.ok_or_else(|| invalid("CPU path finite shadow ray missing"))?; + if state.shadow_excluded != Some(state.shadow_emitter) + && Rectangle::new(input).map_err(error)?.intersect(ray).map_err(error)?.is_some() + { + state.contribution = Vec3::ZERO; + state.stage = Stage::Add; + } else { + state.shadow_emitter += 1; + } + } else { + state.stage = Stage::Add; + } + } + Stage::Add => { + let volume_mis = state.volume.as_mut().and_then(|v| v.shadow_mis.take().map(|mis| (mis, v.shadow_probability))); + if let Some(([light, bsdf], survival)) = volume_mis { + let weight = if !continuing(task, state)? { 1.0 } else { power_weight(light, bsdf * survival).map_err(error)? }; + state.contribution = state.contribution * weight; + } + if let Some(optical) = &mut state.optical + && let Some([light, bsdf]) = optical.shadow_mis.take() + { + let max = task.options.path.ok_or_else(|| invalid("CPU glass path settings disappeared"))?.max_depth; + let weight = if u16::from(state.depth) + 1 + u16::from(optical.shadow_interfaces) >= u16::from(max) { + 1.0 + } else { + power_weight(light, bsdf * optical.shadow_probability).map_err(error)? + }; + state.contribution = state.contribution * weight; + } + state.radiance += state.contribution; + super::super::lighting::validate_radiance(state.radiance).map_err(error)?; + state.stage = state.after_shadow; + } + Stage::Scatter => { + if state.volume.as_ref().is_some_and(|v| v.event.is_some()) { + volume::scatter(task, state)?; + return Ok(()); + } + if !continuing(task, state)? { + state.stage = Stage::Commit; + return Ok(()); + } + let hit = shared(task, state)?; + let [component, x] = variates(task, state, 0x3000)?; + let [y, _] = variates(task, state, 0x3001)?; + let sample = indirect::sample( + hit.surface, + hit.shading_normal, + hit.oriented_geometric_normal(), + -state.ray.ok_or_else(|| invalid("CPU path ray missing"))?.direction(), + [component, x, y], + ) + .map_err(error)?; + if let Some(sample) = sample { + state.throughput = multiply(state.throughput, sample.weight); + super::super::lighting::validate_radiance(state.throughput).map_err(error)?; + if state.throughput != Vec3::ZERO { + state.previous_pdf = sample.pdf; + state.previous_position = hit.position; + if let Some(optical) = &mut state.optical { + optical.delta = false; + optical.segment_start = hit.position; + optical.source_plane = Some(hit.vertices); + } + let (ray, cursor) = if state.volume.is_some() { + let ray = + volume::ray(task, state, sample.direction, None, true)?.ok_or_else(|| invalid("CPU volume surface launch collapsed"))?; + (ray, volume::cursor(task, state, ray)?) + } else if state.optical.as_ref().is_some_and(|o| o.surface_range.is_some()) { + scattering::surface_cursor(state, hit, sample.direction, super::super::MAX_DISTANCE_MM)? + } else { + let ray = hit.spawn(sample.direction).map_err(error)?; + (ray, TraceCursor::new(ray, false)) + }; + state.ray = Some(ray); + state.cursor = Some(cursor); + state.hit = None; + state.depth += 1; + state.stage = Stage::Trace; + return Ok(()); + } + } + state.stage = Stage::Commit; + } + Stage::Trace | Stage::Shadow | Stage::Commit | Stage::Origin | Stage::MediumOrigin => { + return Err(invalid("CPU path phase bypassed its continuation")); + } + } + Ok(()) +} + +/// Conditional state on the existing single path slot: no ray tree or new film. +/// Interface events consume the same finite depth domain as opaque surfaces. +#[derive(Clone, Copy, Default)] +struct GlassPath { + media: [usize; 8], + len: usize, + segment_start: Vec3, + source_plane: Option<[Vec3; 3]>, + collision: Option, + surface_range: Option<[usize; 2]>, + surface_forward: bool, + shadow_exact: bool, + delta: bool, + selector: usize, + selected: Option, + shadow_start: Vec3, + shadow_current: Option, + shadow_hit: Option, + shadow_endpoint: Option, + shadow_inclusive: bool, + shadow_probability: f64, + shadow_interfaces: u8, + shadow_mis: Option<[f64; 2]>, +} +fn current(optical: &GlassPath) -> job::Result> { + if optical.len == 0 { Ok(None) } else { optical.media.get(optical.len - 1).copied().map(Some).ok_or_else(|| invalid("CPU medium stack index")) } +} +fn beer(task: &ImageTask, state: &mut State, to: Vec3, shadow: bool) -> job::Result<()> { + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU glass segment state missing"))?; + let from = if shadow { optical.shadow_start } else { optical.segment_start }; + if let Some(index) = current(optical)? { + let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU medium disappeared"))?; + let factor = dielectric::attenuation(input.absorption_per_mm, from.dist(to)).map_err(error)?; + if shadow { + state.contribution = multiply(state.contribution, factor); + if let Some(scattering) = input.subsurface.filter(|s| s.active()) { + let survival = scattering.survival(from.dist(to)).map_err(|e| JobError::new(ErrorCode::InvalidScene, e.to_string()))?; + state.contribution = state.contribution * survival; + state.optical.as_mut().ok_or_else(|| invalid("CPU subsurface visibility state missing"))?.shadow_probability *= survival; + } + } else { + state.throughput = multiply(state.throughput, factor); + } + } + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU glass segment state missing"))?; + if shadow { + optical.shadow_start = to; + } else { + optical.segment_start = to; + } + Ok(()) +} +fn thin_probability(r: Vec3, t: Vec3) -> job::Result { + let reflected = (r.x + r.y + r.z) / 3.0; + let transmitted = (t.x + t.y + t.z) / 3.0; + if !reflected.is_finite() || !transmitted.is_finite() || reflected < 0.0 || transmitted < 0.0 { + return Err(invalid("CPU glass sheet has no finite scattering mass")); + } + Ok(if reflected + transmitted == 0.0 { 0.0 } else { reflected / (reflected + transmitted) }) +} +fn interface_cursor( + task: &ImageTask, + index: usize, + hit: SharedHit<'_>, + direction: Vec3, + endpoint: Option, + inclusive: bool, +) -> job::Result<(Ray, TraceCursor)> { + let region = task.glass.first().ok_or_else(|| invalid("CPU glass geometry certificate missing"))?.region(index)?; + let (direction, far) = if let Some(endpoint) = endpoint { + let delta = endpoint - hit.position; + let distance = delta.len(); + if !distance.is_finite() || distance <= 0.0 || delta.dot(direction) <= 0.0 { + return Err(invalid("CPU glass finite connection crosses its endpoint")); + } + let far = if inclusive { distance } else { distance.next_down() }; + if far <= 0.0_f64.next_up() { + return Err(invalid("CPU glass finite light interval is empty")); + } + (delta, far) + } else { + (direction, super::super::MAX_DISTANCE_MM) + }; + // Physical boundary coordinates are retained. Exact source-plane exclusion + // avoids consuming a short interior segment with a geometric offset. + let ray = Ray::new(hit.position, direction, 0.0_f64.next_up(), far).map_err(error)?; + let cursor = TraceCursor::from_plane(ray, region.primitive_begin..region.primitive_end, hit.vertices); + Ok((ray, cursor)) +} +fn glass_one(task: &mut ImageTask, state: &mut State) -> job::Result<()> { + let hit = unmapped(task, state)?; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU glass selector state missing"))?; + if let Some(input) = task.options.dielectrics.get(optical.selector) { + if input.body_index == hit.body_index { + if input.body_name != hit.body_name { + return Err(invalid("CPU glass captured identity changed")); + } + optical.selected = Some(optical.selector); + optical.selector = task.options.dielectrics.len(); + } else { + optical.selector += 1; + } + return Ok(()); + } + let Some(index) = optical.selected else { + if scattering::enabled(task) { + optical.surface_range = + Some([hit.primitive_index, hit.primitive_index.checked_add(1).ok_or_else(|| invalid("CPU source primitive overflow"))?]); + optical.surface_forward = false; + state.stage = Stage::MediumSurface; + } else { + state.stage = Stage::Effects; + } + return Ok(()); + }; + if !continuing(task, state)? { + state.stage = Stage::Commit; + return Ok(()); + } + let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU glass interface disappeared"))?; + let direction = state.ray.ok_or_else(|| invalid("CPU glass incident ray missing"))?.direction(); + let normal = hit.oriented_geometric_normal(); + 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 p = thin_probability(r, t)?; + if draw < p { + (interface.reflected, r / p, None) + } else { + let probability = 1.0 - p; + if probability <= 0.0 { + return Err(invalid("CPU thin transmission has zero sampling mass")); + } + preserve_pdf = input.shadow_transmission; + if preserve_pdf { + state.previous_pdf *= probability; + } + (direction, t / probability, None) + } + } else { + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU glass stack missing"))?; + let current = current(optical)?; + let region = task.glass.first().ok_or_else(|| invalid("CPU glass certificate missing"))?.region(index)?; + let parent = region.parent; + let next = if hit.front_face { + if current != parent { + return Err(invalid("CPU glass entered outside its certified medium parent")); + } + Some(index) + } else { + if current != Some(index) { + return Err(invalid("CPU glass exit does not match the active medium")); + } + parent + }; + let ior = |i: Option| -> job::Result { + i.map(|i| task.options.dielectrics.get(i).map(|v| v.ior).ok_or_else(|| invalid("CPU glass IOR index"))).unwrap_or(Ok(1.0)) + }; + let ni = ior(current)?; + let nt = ior(next)?; + let (interface, _) = dielectric::shaded_interface(direction, normal, hit.shading_normal, ni, nt).map_err(error)?; + if draw < interface.reflectance || interface.transmitted.is_none() { + (interface.reflected, Vec3::new(1.0, 1.0, 1.0), None) + } else { + ( + interface.transmitted.ok_or_else(|| invalid("CPU Snell transmission missing"))?, + Vec3::new(1.0, 1.0, 1.0) * (ni / nt).powi(2), + Some(hit.front_face), + ) + } + }; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU glass stack missing"))?; + if let Some(enter) = entering { + if enter { + let slot = optical.media.get_mut(optical.len).ok_or_else(|| invalid("CPU glass medium stack exceeds eight"))?; + *slot = index; + optical.len += 1; + } else { + optical.len = optical.len.checked_sub(1).ok_or_else(|| invalid("CPU glass stack underflow"))?; + } + } + if !preserve_pdf { + optical.delta = true; + state.previous_pdf = 0.0; + state.previous_position = hit.position; + } + optical.segment_start = hit.position; + optical.source_plane = Some(hit.vertices); + state.throughput = multiply(state.throughput, weight); + super::super::lighting::validate_radiance(state.throughput).map_err(error)?; + if state.throughput == Vec3::ZERO { + state.stage = Stage::Commit; + return Ok(()); + } + let (ray, cursor) = interface_cursor(task, index, hit, outgoing, None, true)?; + state.ray = Some(ray); + state.cursor = Some(cursor); + state.hit = None; + state.depth += 1; + state.stage = Stage::Trace; + Ok(()) +} +fn defer_mis(task: &ImageTask, state: &mut State, direction: Vec3, pdf: f64, count: u32) -> job::Result<()> { + if state.volume.is_some() { + if continuing(task, state)? { + let bsdf = if let Some(phase) = volume::response(task, state, direction)? { + phase + } else { + let hit = shared(task, state)?; + indirect::surface_pdf( + hit.surface, + hit.shading_normal, + -state.ray.ok_or_else(|| invalid("CPU volume incident ray missing"))?.direction(), + direction, + ) + .map_err(error)? + }; + state.volume.as_mut().ok_or_else(|| invalid("CPU volume MIS state missing"))?.shadow_mis = Some([f64::from(count) * pdf, bsdf]); + } + return Ok(()); + } + if state.optical.is_none() || !continuing(task, state)? { + return Ok(()); + } + let hit = shared(task, state)?; + let view = -state.ray.ok_or_else(|| invalid("CPU glass NEE incident ray missing"))?.direction(); + let bsdf = indirect::surface_pdf(hit.surface, hit.shading_normal, view, direction).map_err(error)?; + state.optical.as_mut().ok_or_else(|| invalid("CPU glass NEE state missing"))?.shadow_mis = Some([f64::from(count) * pdf, bsdf]); + Ok(()) +} +fn shadow_beer(task: &ImageTask, state: &mut State) -> job::Result<()> { + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU glass visibility state missing"))?; + if let Some(hit) = optical.shadow_hit { + let ray = optical.shadow_current.ok_or_else(|| invalid("CPU glass visibility ray missing"))?; + let bvh = task.bvh.as_ref().ok_or_else(|| invalid("CPU glass visibility BVH missing"))?; + let shared = PreparedScene { bvh, primitives: &task.looks, source: &task.scene }.resolve_hit(ray, hit).map_err(error)?; + beer(task, state, shared.position, true)?; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU glass visibility state missing"))?; + optical.selector = 0; + optical.selected = None; + state.stage = Stage::ShadowGlass; + } else { + if let Some(endpoint) = optical.shadow_endpoint { + beer(task, state, endpoint, true)?; + } else if optical.len != 0 { + return Err(invalid("CPU visibility escaped a certified medium")); + } + state.stage = Stage::ShadowEmitters; + } + Ok(()) +} +fn shadow_glass(task: &ImageTask, state: &mut State) -> job::Result<()> { + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU glass visibility state missing"))?; + let ray = optical.shadow_current.ok_or_else(|| invalid("CPU glass visibility ray missing"))?; + let hit = optical.shadow_hit.ok_or_else(|| invalid("CPU glass visibility hit missing"))?; + let bvh = task.bvh.as_ref().ok_or_else(|| invalid("CPU glass visibility BVH missing"))?; + let hit = PreparedScene { bvh, primitives: &task.looks, source: &task.scene }.resolve_hit(ray, hit).map_err(error)?; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU glass visibility state missing"))?; + if let Some(input) = task.options.dielectrics.get(optical.selector) { + if input.body_index == hit.body_index && input.body_name == hit.body_name { + optical.selected = Some(optical.selector); + optical.selector = task.options.dielectrics.len(); + } else { + optical.selector += 1; + } + return Ok(()); + } + let Some(index) = optical.selected else { + state.contribution = Vec3::ZERO; + state.stage = Stage::Add; + return Ok(()); + }; + let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU glass visibility material disappeared"))?; + if !input.shadow_transmission { + state.contribution = Vec3::ZERO; + state.stage = Stage::Add; + return Ok(()); + } + 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)?; + optical.shadow_probability *= 1.0 - thin_probability(r, t)?; + optical.shadow_interfaces = optical + .shadow_interfaces + .checked_add(1) + .filter(|n| *n <= 16) + .ok_or_else(|| invalid("CPU thin light visibility exceeds sixteen interfaces"))?; + state.contribution = multiply(state.contribution, t); + if state.contribution == Vec3::ZERO { + state.stage = Stage::Add; + return Ok(()); + } + let (ray, cursor) = interface_cursor(task, index, hit, ray.direction(), optical.shadow_endpoint, optical.shadow_inclusive)?; + optical.shadow_current = Some(ray); + optical.shadow_hit = None; + state.cursor = Some(cursor); + state.stage = Stage::Shadow; + Ok(()) +} diff --git a/crates/render/src/raytrace/image_scattering.rs b/crates/render/src/raytrace/image_scattering.rs new file mode 100644 index 000000000..04e46d1cc --- /dev/null +++ b/crates/render/src/raytrace/image_scattering.rs @@ -0,0 +1,192 @@ +//! Analog elastic collisions in the existing single finite dielectric/GI path. +//! No light connection through a refracting boundary, ray tree or image plane. +use super::*; + +#[derive(Clone, Copy)] +pub(super) struct Collision { + position: Vec3, + distance: f64, +} + +pub(super) fn enabled(task: &ImageTask) -> bool { + task.options.dielectrics.iter().any(|input| input.subsurface.is_some_and(|s| s.active())) +} +pub(super) fn active(task: &ImageTask, state: &State) -> job::Result { + let Some(optical) = &state.optical else { return Ok(false) }; + let Some(index) = current(optical)? else { return Ok(false) }; + Ok(task + .options + .dielectrics + .get(index) + .ok_or_else(|| invalid("CPU subsurface medium disappeared"))? + .subsurface + .is_some_and(|scattering| scattering.active())) +} + +pub(super) fn step(task: &mut ImageTask, state: &mut State) -> job::Result<()> { + match state.stage { + Stage::Medium => decide(task, state), + Stage::MediumScatter => scatter(task, state), + Stage::MediumSurface => surface_range(task, state), + _ => Err(invalid("CPU subsurface bypassed its charged phase")), + } +} +fn decide(task: &ImageTask, state: &mut State) -> job::Result<()> { + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU subsurface stack missing"))?; + let index = current(optical)?.ok_or_else(|| invalid("CPU subsurface cannot scatter in vacuum"))?; + let scattering = task + .options + .dielectrics + .get(index) + .and_then(|input| input.subsurface) + .filter(|s| s.active()) + .ok_or_else(|| invalid("CPU subsurface rate disappeared"))?; + let ray = state.ray.ok_or_else(|| invalid("CPU subsurface incident ray missing"))?; + let geometry = if let Some(hit) = state.hit { + let bvh = task.bvh.as_ref().ok_or_else(|| invalid("CPU subsurface BVH missing"))?; + Some(PreparedScene { bvh, primitives: &task.looks, source: &task.scene }.resolve_hit(ray, hit).map_err(error)?) + } else { + None + }; + // Emitters is already the nearest-endpoint selection. An absent endpoint + // inside a certified closed medium is a failed boundary, not infinite fog. + let endpoint = if let Some((_, _, point)) = state.emitter { + point + } else { + geometry.as_ref().ok_or_else(|| invalid("CPU subsurface escaped its certified closed boundary"))?.position + }; + let from = optical.segment_start; + let distance = from.dist(endpoint); + if !distance.is_finite() || distance <= 0.0 { + return Err(invalid("CPU subsurface physical segment is not positive and finite")); + } + let [uniform, _] = variates(task, state, 0x5000)?; + let travel = scattering.free_flight(uniform).map_err(|e| JobError::new(ErrorCode::InvalidScene, e.to_string()))?; + if travel >= distance { + // Analog survival is already sampled, so throughput is not attenuated + // again. Its probability belongs in the competing endpoint MIS density. + state.previous_pdf *= scattering.survival(distance).map_err(|e| JobError::new(ErrorCode::InvalidScene, e.to_string()))?; + state.stage = Stage::Resolve; + return Ok(()); + } + let position = from + ray.direction() * travel; + if position == from || position == endpoint { + return Err(invalid("CPU subsurface collision is not representable between its physical endpoints; change the scene scale explicitly")); + } + for plane in [optical.source_plane, geometry.as_ref().map(|hit| hit.vertices)].into_iter().flatten() { + if super::super::super::glass_mesh::origin_on_plane(plane, position)? { + return Err(invalid("CPU subsurface collision rounds onto a source or endpoint plane; change the scene scale explicitly")); + } + } + if let Some((index, _, _)) = state.emitter { + let input = + task.options.area_lights.as_ref().and_then(|lights| lights.get(index)).ok_or_else(|| invalid("CPU subsurface emitter missing"))?; + if Rectangle::new(input).map_err(error)?.on_plane(position) { + return Err(invalid("CPU subsurface collision rounds onto its analytic emitter plane; change the scene scale explicitly")); + } + } + // Reuse the already prepaid one-element origin slot. Exact classification + // catches boundary rounding and verifies the current nested chain before a + // collision may launch any new direction. Each scan operation yields. + state.origins.clear(); + if state.origins.capacity() == 0 { + state.origins.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + } + if state.origins.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + state.origins.push(super::super::super::origin::Task::new(position, position)?); + state.optical.as_mut().ok_or_else(|| invalid("CPU subsurface pending stack missing"))?.collision = Some(Collision { position, distance: travel }); + state.stage = Stage::MediumOrigin; + Ok(()) +} +fn scatter(task: &mut ImageTask, state: &mut State) -> job::Result<()> { + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU subsurface stack missing"))?; + 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)?; + state.throughput = throughput; + state.optical.as_mut().ok_or_else(|| invalid("CPU subsurface stack missing"))?.collision = None; + // A real collision is foreground even when the eye starts inside, before + // any model/emitter hit. The depth limit counts this collision as a vertex. + if state.depth == 0 { + task.primary_coverage = 1; + } + if throughput == Vec3::ZERO || !continuing(task, state)? { + state.stage = Stage::Commit; + return Ok(()); + } + let incoming = state.ray.ok_or_else(|| invalid("CPU subsurface incident ray missing"))?.direction(); + 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 optical = state.optical.as_mut().ok_or_else(|| invalid("CPU subsurface stack missing"))?; + optical.segment_start = event.position; + optical.source_plane = None; + optical.delta = true; + state.previous_pdf = 0.0; + state.previous_position = event.position; + state.ray = Some(ray); + state.cursor = Some(TraceCursor::new(ray, false)); + state.hit = None; + state.emitter = None; + state.depth += 1; + state.stage = Stage::Trace; + Ok(()) +} + +// Captured preparation keeps each body's primitives contiguous. Walk that range +// cooperatively instead of an uncharged all-body prefix scan or another array. +fn surface_range(task: &ImageTask, state: &mut State) -> job::Result<()> { + let hit = state.hit.ok_or_else(|| invalid("CPU physical surface hit missing"))?; + let body = task.looks.get(hit.primitive_index).ok_or_else(|| invalid("CPU physical surface primitive missing"))?.body_index; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU physical surface state missing"))?; + let range = optical.surface_range.as_mut().ok_or_else(|| invalid("CPU physical surface range missing"))?; + if !optical.surface_forward { + if range[0] > 0 && task.looks.get(range[0] - 1).is_some_and(|primitive| primitive.body_index == body) { + range[0] -= 1; + } else { + optical.surface_forward = true; + } + } else if task.looks.get(range[1]).is_some_and(|primitive| primitive.body_index == body) { + range[1] = range[1].checked_add(1).ok_or_else(|| invalid("CPU physical surface range overflow"))?; + } else { + state.stage = Stage::Effects; + } + Ok(()) +} +pub(super) fn surface_cursor(state: &State, hit: SharedHit<'_>, direction: Vec3, far: f64) -> job::Result<(Ray, TraceCursor)> { + let range = state.optical.as_ref().and_then(|o| o.surface_range).ok_or_else(|| invalid("CPU physical surface cursor range missing"))?; + let ray = Ray::new(hit.position, direction, 0.0_f64.next_up(), far).map_err(error)?; + Ok((ray, TraceCursor::from_plane(ray, range[0]..range[1], hit.vertices))) +} +pub(super) fn needs_shadow_setup(state: &State) -> bool { + state.optical.as_ref().is_some_and(|o| o.surface_range.is_some() && !o.shadow_exact) +} +pub(super) fn shadow_setup(task: &ImageTask, state: &mut State) -> job::Result<()> { + let hit = unmapped(task, state)?; + let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU physical shadow state missing"))?; + let old = optical.shadow_current.ok_or_else(|| invalid("CPU physical shadow ray missing"))?; + let (direction, far) = if let Some(endpoint) = optical.shadow_endpoint { + let direction = endpoint - hit.position; + let distance = direction.len(); + let far = if optical.shadow_inclusive { distance } else { distance.next_down() }; + if direction.dot(old.direction()) <= 0.0 || !far.is_finite() || far <= 0.0_f64.next_up() { + return Err(invalid("CPU physical shadow endpoint collapsed")); + } + (direction, far) + } else { + (old.direction(), old.interval()[1]) + }; + let (ray, cursor) = surface_cursor(state, hit, direction, far)?; + let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU physical shadow state missing"))?; + optical.shadow_current = Some(ray); + optical.shadow_exact = true; + state.shadow_ray = Some(ray); + state.cursor = Some(cursor); + Ok(()) +} diff --git a/crates/render/src/raytrace/image_tests.rs b/crates/render/src/raytrace/image_tests.rs index 1ecff0deb..a8d798191 100644 --- a/crates/render/src/raytrace/image_tests.rs +++ b/crates/render/src/raytrace/image_tests.rs @@ -814,7 +814,9 @@ fn surface_effect_shared_hit_reaches_directional_point_area_and_hdr_consumers() reference_options.surface_effects = None; let reference_request = ImageRequest { raytrace: Some(reference_options.clone()), ..request.clone() }; request.raytrace = Some(options.clone()); - let environment = || if mask & 8 != 0 { Some(surface_constant_environment()) } else { None }; + let environment = || { + if mask & 8 != 0 { Some(surface_constant_environment()) } else { None } + }; let expected = surface_consumer_png( ImageTask::new_with_environment(reference_scene, reference_request, CancelToken::default(), reference_options, environment()) .unwrap(), @@ -1011,6 +1013,8 @@ fn dielectric_triangle_task(cancel: CancelToken) -> ImageTask { let mut request = task.request; let options = RaytraceOptions { dielectrics: vec![job::DielectricOptions { + shadow_transmission: false, + subsurface: None, body_index: 0, body_name: "work fixture".into(), boundary: job::DielectricBoundary::ThinSheet, @@ -1125,6 +1129,8 @@ 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 { + shadow_transmission: false, + subsurface: None, body_index, body_name: body_name.into(), boundary: job::DielectricBoundary::ThinSheet, @@ -1253,7 +1259,9 @@ fn unit_ior_sheet_rejoins_surface_emission_and_every_existing_light_consumer() { sides: job::EmissionSides::Front, }]); request.raytrace = Some(options.clone()); - let environment = || if mask & 8 != 0 { Some(surface_constant_environment()) } else { None }; + let environment = || { + if mask & 8 != 0 { Some(surface_constant_environment()) } else { None } + }; let expected = optical_png( ImageTask::new_with_environment(scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()).unwrap(), 1, @@ -1387,7 +1395,11 @@ fn optical_admission_bills_capacity_and_refuses_ambiguous_effect_and_environment let without_optics = admit(&scene, &plain_request, &plain).unwrap(); assert_eq!( with_optics.estimated_total_bytes - without_optics.estimated_total_bytes, - bytes + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + std::mem::size_of::() as u64 + bytes + + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + + std::mem::size_of::() as u64 + + super::super::legacy_certificates::Task::required_bytes(&scene, &options).unwrap() + + std::mem::size_of::() as u64 ); options.surface_effects = Some(vec![crate::surface_patterns::SurfaceEffect { body: name, @@ -1485,6 +1497,717 @@ fn cancelled_pending_pixel_allocation_is_refused_before_any_continuation() { assert_eq!(PendingPixelSlot::new(&cancel).err().unwrap().code, ErrorCode::Cancelled); } +fn progressive_optics_fixture(samples: u32, thin: bool, ior: f64, cancel: CancelToken) -> ImageTask { + let mut body = dielectric::tests::box_body(8.0); + let boundary = if thin { + std::sync::Arc::make_mut(&mut body.mesh).triangles = vec![[4, 5, 7], [4, 7, 6]]; + job::DielectricBoundary::ThinSheet + } else { + job::DielectricBoundary::ClosedBox + }; + let mut material = dielectric::tests::input(boundary); + material.ior = ior; + material.absorption_per_mm = [0.1, 0.2, 0.0]; + material.thickness_mm = if thin { 8.0 } else { 0.0 }; + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 83 }), + dielectrics: vec![material], + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + // A small parallel camera keeps every independently jittered sample well inside + // the certified slab; this analytic fixture does not sample a boundary edge. + request.camera.distance = 10.0; + request.camera.fov = 0.0; + ImageTask::new(dielectric::tests::scene(body), request, cancel, options).unwrap() +} + +fn progressive_optics_complete(mut task: ImageTask, quantum: usize) -> (Vec<(u32, Vec)>, Vec, u64) { + let mut previews = Vec::new(); + let mut branches = 0; + for _ in 0..2_000_000 { + let used = task.work.used(); + let transport = task.progress().phase == Phase::Running; + let poll = task.step_with_previews(quantum).unwrap(); + if quantum == 1 && transport { + assert!(task.work.used() - used <= 4, "an optical continuation exceeded the shared work quantum"); + } + assert!(task.primary_coverage <= 1, "Fresnel branches cannot become additional camera coverage samples"); + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) + && state.path.boundaries > 0 + { + branches += 1; + assert!(!task.pending.as_ref().unwrap().repeatable_primary); + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.optical.first().is_some_and(|o| o.pending.is_none()), "a complete pass must drain every optical branch"); + previews.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + assert!(branches > 0, "the actual image producer must consume optical interfaces"); + assert!(task.optical.is_empty()); + return (previews, png, task.work.used()); + } + } + } + panic!("bounded progressive optical fixture did not finish"); +} + +#[test] +fn progressive_certified_optics_keep_beer_lambert_energy_prefixes_and_shared_work() { + for thin in [false, true] { + for ior in [1.0, 1.5] { + let actual = progressive_optics_complete(progressive_optics_fixture(5, thin, ior, CancelToken::default()), 1); + assert_eq!(actual.0.iter().map(|p| p.0).collect::>(), [1, 2, 3, 4]); + assert_eq!(actual, progressive_optics_complete(progressive_optics_fixture(5, thin, ior, CancelToken::default()), 16_384)); + for (samples, png) in &actual.0 { + let prefix = progressive_optics_complete(progressive_optics_fixture(*samples, thin, ior, CancelToken::default()), 3); + assert_eq!(*png, prefix.1, "target sample count must not change an optical prefix"); + } + if ior == 1.0 { + // Index-matched slab/sheet: no reflection, exactly eight millimetres + // of Beer attenuation in each independent camera sample. + let linear = Vec3::new((-0.8f64).exp(), (-1.6f64).exp(), 1.0); + let mapped = map_to_display(linear, 0.0).unwrap(); + let expected = [encode8(mapped.x), encode8(mapped.y), encode8(mapped.z), 255]; + assert_eq!(::image::load_from_memory(&actual.1).unwrap().to_rgba8().get_pixel(0, 0).0, expected); + } + } + } +} + +#[test] +fn progressive_certified_optical_branches_cancel_and_exhaust_before_any_late_pass() { + for exhausted in [false, true] { + let cancel = CancelToken::default(); + let mut task = progressive_optics_fixture(5, false, 1.5, cancel.clone()); + let mut stopped = false; + for _ in 0..200_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|state| state.path.boundaries > 0) { + let used = task.work.used(); + if exhausted { + task.work.limit = used; + } else { + cancel.cancel(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if exhausted { ErrorCode::LimitExceeded } else { ErrorCode::Cancelled }); + assert_eq!(task.work.used(), used); + assert!(!task.done); + stopped = true; + break; + } + } + assert!(stopped, "test must stop inside a real Fresnel branch"); + } +} + +type DenoiseOracleGuide = [[f64; 4]; 3]; +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a.into_iter().zip(b).map(|(x, y)| x * y).sum() +} +fn diff(a: [f64; 4], b: [f64; 4]) -> [f64; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn xyz(a: [f64; 4]) -> [f64; 3] { + [a[0], a[1], a[2]] +} + +// Independent f64 gather oracle: all inputs are averaged linear values, so the +// GPU's accumulated-sample scaling is absent from this numerical implementation. +fn cpu_denoise_reference(width: usize, input: &[[f64; 4]], guides: &[DenoiseOracleGuide], step: usize) -> Vec<[f64; 4]> { + let height = input.len() / width; + let kernel = [1.0, 4.0, 6.0, 4.0, 1.0]; + input + .iter() + .enumerate() + .map(|(i, ¢er)| { + let [a, n, p] = guides[i]; + if a[3] == 0.0 || center[3] < 0.999 { + return center; + } + let mut result = [0.0; 4]; + let mut total = 0.0; + for (ky, &wy) in kernel.iter().enumerate() { + for (kx, &wx) in kernel.iter().enumerate() { + let x = (i % width) as isize + (kx as isize - 2) * step as isize; + let y = (i / width) as isize + (ky as isize - 2) * step as isize; + if x < 0 || y < 0 || x >= width as isize || y >= height as isize { + continue; + } + let j = y as usize * width + x as usize; + let [b, m, q] = guides[j]; + let value = input[j]; + if a[3] != b[3] || (value[3] - center[3]).abs() > 0.01 { + continue; + } + let albedo = diff(a, b); + let position = diff(q, p); + let plane = dot(position, xyz(n)).abs() + dot(position, xyz(m)).abs(); + let scale = (0.05 * p[3].max(q[3]) * step as f64).max(1e-6); + let depth = (n[3] - m[3]).abs() / (8.0 * p[3].max(q[3]) * step as f64).max(1e-6); + let color = diff(center, value); + let maximum = |v: [f64; 3]| v.into_iter().fold(0.0, f64::max); + let color_scale = 0.25 + 0.5 * maximum(xyz(center)).max(maximum(xyz(value))); + let weight = wx + * wy + * (-dot(albedo, albedo) / 0.04 - plane / scale - depth - maximum(color.map(f64::abs)) / color_scale).exp() + * dot(xyz(n), xyz(m)).max(0.0).powi(32); + for k in 0..3 { + result[k] += value[k] * weight; + } + total += weight; + } + } + for v in result.iter_mut().take(3) { + *v /= total; + } + result[3] = center[3]; + result + }) + .collect() +} + +fn denoise_test_guide(x: usize, y: usize) -> job::denoise::Guide { + job::denoise::Guide { albedo: [0.5; 3], body: 1, normal: [0.0, 0.0, 1.0], depth: 4.0, position: [x as f32, y as f32, 0.0], footprint: 1.0 } +} +fn oracle_guides(guides: &[job::denoise::Guide]) -> Vec { + guides + .iter() + .map(|g| { + [ + [f64::from(g.albedo[0]), f64::from(g.albedo[1]), f64::from(g.albedo[2]), f64::from(g.body)], + [f64::from(g.normal[0]), f64::from(g.normal[1]), f64::from(g.normal[2]), f64::from(g.depth)], + [f64::from(g.position[0]), f64::from(g.position[1]), f64::from(g.position[2]), f64::from(g.footprint)], + ] + }) + .collect() +} +fn complete_denoise(width: u32, pixels: Vec<[f32; 4]>, guides: &[job::denoise::Guide]) -> (Vec<[f32; 4]>, usize) { + let mut task = job::denoise::DenoiseTask::new(width, pixels.len() as u32 / width, pixels).unwrap(); + let mut visits = 0; + for _ in 0..1000 { + let count = task.next_pixels(); + assert!(count <= job::denoise::MAX_STEP_PIXELS); + visits += count; + if task.step(guides, &CancelToken::default()).unwrap() { + return (task.finish().unwrap(), visits); + } + } + panic!("bounded filter did not finish") +} +#[test] +fn cpu_atrous_matches_independent_f64_gather_preserves_hdr_coverage_and_edges() { + let width = 17u32; + let count = (width * width) as usize; + let guides: Vec<_> = (0..count).map(|i| denoise_test_guide(i % 17, i / 17)).collect(); + let pixels: Vec<_> = (0..count) + .map(|i| { + let hash = (i as u32).wrapping_mul(2654435761); + let value = 0.4 + 0.2 * (hash >> 8) as f32 / 16777216.0; + [value, value * 0.7, value * 1.3, 1.0] + }) + .collect(); + let original = pixels.clone(); + let saved = guides.clone(); + let (actual, visits) = complete_denoise(width, pixels, &guides); + let mut expected: Vec<_> = original.iter().map(|p| p.map(f64::from)).collect(); + for step in [1, 2, 4] { + expected = cpu_denoise_reference(17, &expected, &oracle_guides(&guides), step); + } + assert_eq!(visits, 3 * count, "bounded pixel visits, not an invented scalar-FLOP budget"); + for (a, b) in actual.iter().zip(expected) { + for c in 0..4 { + assert!((f64::from(a[c]) - b[c]).abs() < 2e-6) + } + } + let variance = |v: &[[f32; 4]]| { + let mean = v.iter().map(|p| f64::from(p[0])).sum::() / v.len() as f64; + v.iter().map(|p| (f64::from(p[0]) - mean).powi(2)).sum::() / v.len() as f64 + }; + assert!(variance(&actual) < variance(&original) / 4.0); + assert_eq!(guides.iter().map(|g| g.position).collect::>(), saved.iter().map(|g| g.position).collect::>()); + for constant in [[0.75, 0.25, 0.5, 1.0], [1e30, 1e20, 1e10, 1.0], [0.7, 0.3, 0.1, 0.5]] { + assert_eq!(complete_denoise(width, vec![constant; count], &guides).0, vec![constant; count]); + } + for edge in 0..6 { + let mut g = guides.clone(); + let mut p = vec![[0.0, 0.0, 0.0, 1.0]; count]; + for (i, value) in p.iter_mut().enumerate() { + if i % 17 >= 8 { + *value = [1.0; 4]; + match edge { + 0 => g[i].body = 2, + 1 => g[i].normal = [1.0, 0.0, 0.0], + 2 => g[i].position[2] = 10.0, + 3 => g[i].albedo = [1.0; 3], + 4 => g[i].depth = 1004.0, + _ => g[i].body = 0, + } + } else if edge == 3 { + g[i].albedo = [0.0; 3] + } + } + let filtered = complete_denoise(width, p.clone(), &g).0; + assert!(filtered.iter().zip(p).all(|(a, b)| (a[0] - b[0]).abs() < 1e-12), "edge {edge}"); + } + let bypass = vec![job::denoise::Guide::default(); count]; + assert_eq!(complete_denoise(width, original.clone(), &bypass).0, original); +} + +fn denoised_plane(samples: u32, denoise: bool, output: Option) -> ImageTask { + let (scene, mut request, _) = emission_fixture(false); + request.width = 13; + request.height = 13; + let options = RaytraceOptions { + denoise, + output: output.map(Box::new), + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 7 }), + lights: Some(Vec::new()), + area_lights: Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [14.0, 0.0, 0.0], + edge_v_mm: [0.0, -14.0, 0.0], + color: [1.0, 0.7, 0.3], + intensity: 10.0, + }]), + area_samples: Some(1), + seed: Some(31), + ..Default::default() + }; + request.raytrace = Some(options.clone()); + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +type DenoisedImageOutput = (Vec<(u32, Vec)>, Vec, Option>, u64); +fn finish_denoise_image(mut task: ImageTask, units: usize) -> DenoisedImageOutput { + let mut previews = Vec::new(); + for _ in 0..300000 { + match task.step_with_previews(units).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.take_linear_exr().is_none()); + previews.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + assert_eq!(task.denoise.capacity(), 0, "guides are work-owned, never retained with the final master"); + return (previews, png, task.take_linear_exr(), task.work.used()); + } + } + } + panic!("bounded denoised image did not finish") +} +#[test] +fn cpu_denoising_filters_actual_complete_prefixes_without_changing_raw_film_or_exr() { + let output = job::OutputOptions { linear_exr: true, ..Default::default() }; + let first = finish_denoise_image(denoised_plane(4, true, Some(output)), 1); + assert_eq!(first.0.iter().map(|p| p.0).collect::>(), [1, 2, 3]); + assert_eq!(first, finish_denoise_image(denoised_plane(4, true, Some(output)), 16384)); + for (samples, png) in &first.0 { + assert_eq!(png, &finish_denoise_image(denoised_plane(*samples, true, Some(output)), 3).1) + } + let raw = finish_denoise_image(denoised_plane(4, false, Some(output)), 1); + assert_eq!(first.2, raw.2, "EXR is encoded before filtering from identical absolute Monte Carlo samples"); + assert_ne!(first.1, raw.1, "the actual CPU soft-light picture must pass through the filter"); + let mut task = denoised_plane(2, true, None); + for _ in 0..300000 { + if task.linear.len() == 169 && task.output.is_empty() { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + assert_eq!(task.linear.len(), 169); + let guides = task.denoise.first().unwrap().pixels().unwrap().to_vec(); + assert!(guides.iter().all(|g| g.body > 0)); + assert!(guides.iter().all(|g| (g.normal[2] - 1.0).abs() < 1e-6)); + let film: Vec<_> = (0..169).map(|i| task.progressive.as_ref().unwrap().film.pixel(i).unwrap()).collect(); + let mut expected: Vec<_> = task.linear.iter().map(|p| p.map(f64::from)).collect(); + for step in [1, 2, 4] { + expected = cpu_denoise_reference(13, &expected, &oracle_guides(&guides), step) + .into_iter() + .map(|pixel| pixel.map(|value| f64::from(value as f32))) + .collect() + } + let linear: Vec<_> = expected.iter().map(|p| p.map(|v| v as f32)).collect(); + let mut rgba = vec![0; 169 * 4]; + job::presentation::Presentation { background: task.request.background, ..Default::default() } + .display(13, 13) + .unwrap() + .encode(&linear, &mut rgba, &CancelToken::default()) + .unwrap(); + let png = loop { + match task.step_with_previews(1).unwrap() { + ImagePoll::Preview { png, .. } => break png, + ImagePoll::Pending(_) => {} + ImagePoll::Complete(_) => panic!("first prefix was lost"), + } + }; + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().as_raw(), &rgba); + assert_eq!((0..169).map(|i| task.progressive.as_ref().unwrap().film.pixel(i).unwrap()).collect::>(), film); +} +#[test] +fn cpu_denoising_admits_actual_guides_and_colour_scratch_only_when_enabled() { + let plain = denoised_plane(4, false, None); + let filtered = denoised_plane(4, true, None); + assert_eq!(plain.denoise.capacity(), 0); + assert_eq!(filtered.denoise.capacity(), 1); + let expected = 169 * 80 + std::mem::size_of::() as u64 + std::mem::size_of::() as u64; + assert_eq!(filtered.admission.estimated_total_bytes - plain.admission.estimated_total_bytes, expected); + let output = Some(job::OutputOptions { linear_exr: true, ..Default::default() }); + let plain = denoised_plane(4, false, output); + let filtered = denoised_plane(4, true, output); + assert_eq!( + filtered.admission.estimated_total_bytes - plain.admission.estimated_total_bytes, + 169 * 64 + std::mem::size_of::() as u64 + ); + let mut request = plain.request.clone(); + request.width = 8193; + request.height = 1; + let options = RaytraceOptions { denoise: true, budget: job::CpuBudget::Workstation, ..Default::default() }; + request.raytrace = Some(options.clone()); + assert!(admit(&plain.scene, &request, &options).unwrap_err().message.contains("CPU denoising")); +} +#[test] +fn cpu_denoising_guides_and_filter_keep_cancellation_and_cumulative_work() { + for guide_stage in [true, false] { + for cancel in [true, false] { + let mut task = denoised_plane(2, true, Some(job::OutputOptions { linear_exr: true, ..Default::default() })); + for _ in 0..300000 { + let reached = if guide_stage { + task.bvh.is_some() && task.denoise.first().is_some_and(|g| !g.ready()) + } else { + task.output.first().is_some_and(|o| o.stage_name() == "denoise") + }; + if reached { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + if guide_stage { + assert!(!task.denoise.first().unwrap().ready()) + } else { + assert_eq!(task.output.first().unwrap().stage_name(), "denoise") + } + if cancel { + task.cancel.cancel() + } else { + task.work.limit = task.work.used() + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + assert!(task.take_linear_exr().is_none()); + } + } +} + +fn actual_denoise_guides(mut task: ImageTask) -> Vec { + for _ in 0..300000 { + if task.denoise.first().is_some_and(|guides| guides.ready()) { + assert_eq!(task.pixel, 0, "guide construction cannot consume a Monte Carlo sample"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + return task.denoise.first().unwrap().pixels().unwrap().to_vec(); + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + panic!("bounded production guides did not finish") +} +#[test] +fn cpu_denoise_production_guides_use_exact_body_and_material_bypass_policy() { + for case in 0..7 { + let base = denoised_plane(2, true, None); + let mut source = base.scene.clone(); + let mut options = base.options.clone(); + match case { + 0 | 1 => { + for body in &mut source.meshes { + body.surface = Some(OpaqueSurface::new(Vec3::new(0.4, 0.6, 0.8), 1.0, if case == 0 { 0.2 } else { 0.3 }, 1.5).unwrap()); + } + } + 2 | 3 => { + for body in &mut source.meshes { + body.surface = Some( + OpaqueSurface::new(Vec3::new(0.4, 0.6, 0.8), 0.0, 0.5, 1.5) + .unwrap() + .with_clear_coat(crate::clear_coat::ClearCoat::new(1.0, if case == 2 { 0.045 } else { 0.1 }, 1.5).unwrap()), + ); + } + } + 4 => { + options.dielectrics = source + .meshes + .iter() + .enumerate() + .map(|(body_index, body)| job::DielectricOptions { + shadow_transmission: false, + subsurface: None, + body_index, + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }) + .collect(); + } + 5 => { + options.reflections = Some(job::ReflectionOptions { + samples: 1, + bodies: source + .meshes + .iter() + .map(|body| job::ReflectionBody { body: body.name.clone(), mode: job::ReflectionMode::Mirror }) + .collect(), + ..Default::default() + }) + } + _ => { + options.emissions = Some( + source + .meshes + .iter() + .enumerate() + .map(|(body_index, body)| job::SurfaceEmission { + body_index, + body: body.name.clone(), + color: [1.0; 3], + strength: 1.0, + sides: job::EmissionSides::Both, + }) + .collect(), + ) + } + } + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let guides = actual_denoise_guides(ImageTask::new(source, request, CancelToken::default(), options).unwrap()); + let eligible = matches!(case, 1 | 3); + assert!(guides.iter().all(|g| (g.body != 0) == eligible), "case {case}"); + if eligible { + assert!(guides.iter().all(|g| g.body == 1 || g.body == 2)); + assert!(guides.iter().all(|g| g.albedo == [0.4, 0.6, 0.8])); + } + } +} +#[test] +fn cpu_denoise_center_guides_are_translation_stable_and_independent_of_pupil_sampling() { + let base = denoised_plane(2, true, None); + let expected = actual_denoise_guides(denoised_plane(2, true, None)); + let shift = Vec3::new(9e8, -8e8, 7e8); + let mut scene = base.scene.clone(); + for body in &mut scene.meshes { + let mut mesh = (*body.mesh).clone(); + for position in &mut mesh.positions { + *position += shift; + } + body.mesh = std::sync::Arc::new(mesh); + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds())); + let mut request = base.request.clone(); + request.camera.target += shift; + let translated = actual_denoise_guides(ImageTask::new(scene, request, CancelToken::default(), base.options.clone()).unwrap()); + for (a, b) in expected.iter().zip(translated) { + assert_eq!((a.body, a.albedo, a.normal), (b.body, b.albedo, b.normal)); + for i in 0..3 { + assert!((a.position[i] - b.position[i]).abs() < 1e-4); + } + assert!((a.depth - b.depth).abs() < 1e-4); + assert_eq!(a.footprint, b.footprint); + } + let mut request = base.request.clone(); + request.camera.fov = 0.8; + let no_lens = actual_denoise_guides(ImageTask::new(base.scene.clone(), request.clone(), CancelToken::default(), base.options.clone()).unwrap()); + let mut options = base.options.clone(); + options.lens = Some(job::ThinLens { aperture_radius_mm: 0.2, focus_distance_mm: 25.0 }); + request.raytrace = Some(options.clone()); + let lens = actual_denoise_guides(ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap()); + for (a, b) in no_lens.iter().zip(lens) { + assert_eq!((a.body, a.albedo, a.normal, a.position, a.depth, a.footprint), (b.body, b.albedo, b.normal, b.position, b.depth, b.footprint)); + } +} +#[test] +fn cpu_denoising_rejects_invalid_raw_radiance_and_never_masks_it_with_bypass() { + for body in [0, 1] { + let mut guide = denoise_test_guide(0, 0); + guide.body = body; + for pixel in [[f32::NAN, 0.0, 0.0, 1.0], [f32::INFINITY, 0.0, 0.0, 1.0], [-1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.1]] { + let mut task = job::denoise::DenoiseTask::new(1, 1, vec![pixel]).unwrap(); + assert!(task.step(&[guide], &CancelToken::default()).is_err()); + } + } + let cancel = CancelToken::default(); + cancel.cancel(); + let mut task = job::denoise::DenoiseTask::new(1, 1, vec![[1.0; 4]]).unwrap(); + assert_eq!(task.step(&[denoise_test_guide(0, 0)], &cancel).unwrap_err().code, ErrorCode::Cancelled); +} + +#[test] +fn cpu_denoise_hit_and_miss_guide_continuations_charge_one_unit_before_each_store() { + for miss in [false, true] { + for exhaust_at_store in [false, true] { + let base = denoised_plane(2, true, None); + let source = if miss { ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY } } else { base.scene.clone() }; + let mut task = ImageTask::new(source, base.request.clone(), CancelToken::default(), base.options.clone()).unwrap(); + let mut guide_calls = 0; + let mut tested_store = false; + for _ in 0..300000 { + if task.bvh.is_some() && task.denoise.first().is_some_and(|guides| !guides.ready()) { + let guide = task.denoise.first().unwrap(); + let stored = guide.completed_pixels(); + let at_store = guide.ready_to_store(&task.options); + let before = task.work.used(); + if exhaust_at_store && at_store { + task.work.limit = before; + assert_eq!(task.step_with_previews(1).err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(task.work.used(), before); + let guide = task.denoise.first().unwrap(); + assert_eq!(guide.completed_pixels(), stored); + assert!(guide.ready_to_store(&task.options), "an exhausted debit cannot consume the pending guide"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + tested_store = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert_eq!(task.work.used() - before, 1, "one guide call; miss={miss}, store={at_store}"); + guide_calls += 1; + if task.denoise.first().unwrap().ready() { + break; + } + } else { + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + } + assert!(guide_calls > 0); + if exhaust_at_store { + assert!(tested_store); + } else { + let guides = task.denoise.first().unwrap(); + assert!(guides.ready()); + assert_eq!(guides.completed_pixels(), 169); + assert!(guides.pixels().unwrap().iter().all(|guide| (guide.body == 0) == miss)); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + } + } + } +} + +#[test] +fn adaptive_certified_optics_drain_pilot_branches_and_keep_exact_independent_production_beer_energy() { + use crate::job::adaptive::AdaptiveSampling; + for thin in [false, true] { + for ior in [1.0, 1.5] { + let build = || { + let original = progressive_optics_fixture(16, thin, ior, CancelToken::default()); + let options = RaytraceOptions { + adaptive: Some(Box::new(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + let actual = progressive_optics_complete(build(), 1); + assert_eq!(actual, progressive_optics_complete(build(), 16384)); + assert_eq!(actual.0.iter().map(|p| p.0).collect::>(), (1..32).collect::>()); + let production = progressive_optics_complete(progressive_optics_fixture(16, thin, ior, CancelToken::default()), 3); + assert_eq!(actual.1, production.1, "discarded pilots cannot alter the existing16-sample production optical estimator"); + if ior == 1.0 { + let mapped = map_to_display(Vec3::new((-0.8_f64).exp(), (-1.6_f64).exp(), 1.0), 0.0).unwrap(); + let expected = [encode8(mapped.x), encode8(mapped.y), encode8(mapped.z), 255]; + for (_, png) in actual.0.iter().chain(std::iter::once(&(32, actual.1.clone()))) { + assert_eq!( + ::image::load_from_memory(png).unwrap().to_rgba8().get_pixel(0, 0).0, + expected, + "all pilot/production prefixes retain the independent8mm Beer oracle" + ); + } + } + } + } +} + +#[test] +fn prepaid_legacy_certificate_and_standalone_cursor_share_cumulative_work_and_exact_output() { + let scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + let options = RaytraceOptions { + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + lights: Some(Vec::new()), + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..Default::default() + }; + let request = dielectric::tests::request(options.clone()); + let cancel = CancelToken::default(); + let proof = certify_for_request(&scene, &request, &options, &cancel).unwrap().unwrap(); + let prepared_work = proof.work_used(); + assert!(prepared_work > 12, "the complete tiled-boundary proof is real work"); + let mut prepared = ImageTask::new_prepared(scene.clone(), request.clone(), cancel, options.clone(), None, Some(proof)).unwrap(); + let mut standalone = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert!(prepared.optical[0].preparation.is_empty(), "the factory consumes the proof instead of certifying again"); + assert!(!standalone.optical[0].preparation.is_empty()); + assert_eq!(prepared.work.used(), prepared_work); + while !standalone.optical[0].preparation.is_empty() { + let before = standalone.work.used(); + assert!(matches!(standalone.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(standalone.work.used() - before, 1); + assert!(standalone.triangles.is_empty() && standalone.pixels.is_empty(), "proof precedes geometry/pixels"); + } + assert_eq!(standalone.work.used(), prepared.work.used(), "background proof/store credit transfers into the one cumulative budget"); + let complete = |task: &mut ImageTask| { + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(1).unwrap() { + return png; + } + } + panic!("tiny certified image did not complete"); + }; + let a = complete(&mut prepared); + let b = complete(&mut standalone); + assert_eq!(a, b); + let raw = prepared.take_linear_exr().expect("final raw EXR"); + assert_eq!(Some(raw.as_slice()), standalone.take_linear_exr().as_deref(), "prepared proof does not alter raw master bytes"); + assert_eq!(prepared.work.used(), standalone.work.used()); + // Independent native uncompressed FLOAT EXR scanline: one1×1 chunk stores + // the four A/B/G/R channels, all exactly1 for this lossless white furnace. + assert_eq!(&raw[..8], &[0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]); + let mut header = 8; + while raw[header] != 0 { + header += raw[header..].iter().position(|byte| *byte == 0).unwrap() + 1; + header += raw[header..].iter().position(|byte| *byte == 0).unwrap() + 1; + let count = u32::from_le_bytes(raw[header..header + 4].try_into().unwrap()) as usize; + header += 4 + count; + } + header += 1; + let chunk = u64::from_le_bytes(raw[header..header + 8].try_into().unwrap()) as usize; + assert_eq!(chunk, header + 8); + assert_eq!(i32::from_le_bytes(raw[chunk..chunk + 4].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(raw[chunk + 4..chunk + 8].try_into().unwrap()), 16); + let channels: [f32; 4] = std::array::from_fn(|i| f32::from_le_bytes(raw[chunk + 8 + i * 4..chunk + 12 + i * 4].try_into().unwrap())); + assert_eq!(channels, [1.0; 4], "lossless raw radiance/coverage remains exactly1 before presentation"); + // Default Reinhard maps linear1 to.5; standard sRGB encoding rounds to188. + assert_eq!( + ::image::load_from_memory(&a).unwrap().to_rgba8().get_pixel(0, 0).0, + [188, 188, 188, 255], + "white furnace follows the existing presentation contract" + ); +} + +#[test] +fn standalone_legacy_preparation_cancellation_never_advances_or_allocates_pixels() { + let scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + let options = RaytraceOptions { dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], ..Default::default() }; + let request = dielectric::tests::request(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene, request, cancel.clone(), options).unwrap(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + let before = (task.work.used(), task.optical[0].preparation.len(), task.triangles.len(), task.pixels.len()); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!((task.work.used(), task.optical[0].preparation.len(), task.triangles.len(), task.pixels.len()), before); +} + fn mapped_wood_fixture() -> (ProductScene, ImageRequest, RaytraceOptions) { use crate::job::textures::{BaseColorMode, PlanarFrame, RuntimeTextures, TextureBinding, TextureMap}; use image::ImageEncoder; @@ -1610,6 +2333,52 @@ fn cpu_wood_footprint_uses_unwrapped_physical_spacing_and_applies_supersampling_ } } } +#[test] +fn thin_lens_map_footprint_holds_the_sampled_pupil_on_off_focus_planes() { + let (scene, mut request, mut options) = mapped_wood_fixture(); + request.width = 64; + request.height = 32; + request.camera.distance = 10.0; + request.camera.fov = std::f64::consts::FRAC_PI_2; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 2, seed: 81 }); + for focus_distance_mm in [5.0, 20.0] { + let lens = job::ThinLens { aperture_radius_mm: 0.8, focus_distance_mm }; + options.lens = Some(lens); + request.raytrace = Some(options.clone()); + let task = ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); + let progressive = task.progressive.as_ref().unwrap(); + let (right, up, back) = request.camera.basis(); + let plane = request.camera.target; + let depth = request.camera.distance; + // On a frontoparallel plane a fixed pupil translates every hit equally. + // One output-pixel differential is 2*depth*tan(fov/2)/height, regardless + // of focus distance or pupil position. This is an analytic scale oracle. + let expected = 2.0 * depth * (request.camera.fov * 0.5).tan() / f64::from(request.height); + for pixel in [0, 37, 1024, 2047] { + let [dx, dy] = progressive.variates(pixel, 0).unwrap(); + let pupil = progressive.variates(pixel, 0x4c454e53).unwrap(); + let x = (pixel % request.width as usize) as f64 + dx; + let y = (pixel / request.width as usize) as f64 + dy; + let hit = |ray: Ray| ray.origin() + ray.direction() * ((plane - ray.origin()).dot(back) / ray.direction().dot(back)); + let point = hit(lens_primary_ray(&request, x, y, task.clip, lens, pupil).unwrap()); + let pinhole = hit(primary_ray(&request, x, y, task.clip).unwrap()); + assert!((point - pinhole).len() > 1e-6, "the fixture must expose off-focus pupil parallax"); + let footprint = primary_footprint(&request, &options, Some(progressive), pixel, 0, task.clip, point, back).unwrap().unwrap(); + assert!((footprint[0] - right * expected).len() < 1e-10, "horizontal footprint must hold the sampled pupil"); + assert!((footprint[1] + up * expected).len() < 1e-10, "vertical footprint must hold the sampled pupil"); + assert_eq!(progressive.variates(pixel, 0).unwrap(), [dx, dy]); + assert_eq!(progressive.variates(pixel, 0x4c454e53).unwrap(), pupil); + let mut zero = options.clone(); + zero.lens = Some(job::ThinLens { aperture_radius_mm: 0.0, focus_distance_mm }); + assert_eq!( + primary_footprint(&request, &zero, Some(progressive), pixel, 0, task.clip, pinhole, back).unwrap(), + camera_footprint(&request, x, y, 1.0, task.clip, pinhole, back).unwrap(), + "zero aperture keeps the existing pinhole footprint exactly" + ); + } + } +} + #[test] fn cpu_wood_preparation_cancel_and_role_work_limit_never_publish_partial_pixels() { let (scene, request, options) = mapped_wood_fixture(); diff --git a/crates/render/src/raytrace/image_volume.rs b/crates/render/src/raytrace/image_volume.rs new file mode 100644 index 000000000..e32c6b442 --- /dev/null +++ b/crates/render/src/raytrace/image_volume.rs @@ -0,0 +1,268 @@ +//! One bounded homogeneous-medium continuation on the existing finite path slot. +//! No ray tree, image plane or change to model/camera/framing bounds. +use super::*; + +#[derive(Default)] +pub(super) struct Context { + pub source: Vec3, + source_plane: Option<[Vec3; 3]>, + /// Incoming propagation direction while evaluating a collision vertex. + pub event: Option, + range: Option<[usize; 2]>, + forward: bool, + pub shadow_mis: Option<[f64; 2]>, + pub shadow_probability: f64, +} +pub(super) fn enabled(task: &ImageTask) -> bool { + task.options.volume.as_ref().is_some_and(|v| v.active()) +} +fn medium(task: &ImageTask) -> job::Result { + task.options.volume.as_ref().copied().filter(|v| v.active()).ok_or_else(|| invalid("CPU Atmosphere disappeared")) +} +fn array(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} +fn segment(v: job::volume::HomogeneousVolume, point: Vec3, direction: Vec3, limit: f64) -> job::Result<[f64; 2]> { + let result = v.segment(array(point), array(direction), limit)?; + if limit == super::super::super::MAX_DISTANCE_MM { + let mut enter = f64::NEG_INFINITY; + let mut leave = f64::INFINITY; + for (axis, (p, d)) in [(point.x, direction.x), (point.y, direction.y), (point.z, direction.z)].into_iter().enumerate() { + if d == 0.0 { + if p < v.min_mm[axis] || p > v.max_mm[axis] { + return Ok(result); + } + } else { + let a = (v.min_mm[axis] - p) / d; + let b = (v.max_mm[axis] - p) / d; + enter = enter.max(a.min(b)); + leave = leave.min(a.max(b)); + } + } + if enter < leave && leave > limit && leave > 0.0 { + return Err(invalid("CPU Atmosphere extends beyond the admitted ray distance; move/resize it explicitly")); + } + } + Ok(result) +} +fn context(state: &State) -> job::Result<&Context> { + state.volume.as_ref().ok_or_else(|| invalid("CPU Atmosphere context missing")) +} +fn context_mut(state: &mut State) -> job::Result<&mut Context> { + state.volume.as_mut().ok_or_else(|| invalid("CPU Atmosphere context missing")) +} + +/// Keep the model's original near interval. Perspective optics start at the +/// physical eye/pupil. Orthographic optics start before the union of its original +/// near plane and the box's signed line entry, without changing that pixel line. +pub(super) fn primary(task: &ImageTask, ray: Ray, physical: Option) -> job::Result { + let v = medium(task)?; + let direction = ray.direction(); + let (source, near) = if let Some(eye) = physical { + let near = (ray.origin() - eye).dot(direction); + if !near.is_finite() || near < 0.0 { + return Err(invalid("CPU Atmosphere physical near interval is invalid")); + } + (eye, near) + } else { + let mut enter = f64::NEG_INFINITY; + let mut leave = f64::INFINITY; + let origin = array(ray.origin()); + let d = array(direction); + for axis in 0..3 { + if d[axis] == 0.0 { + if origin[axis] < v.min_mm[axis] || origin[axis] > v.max_mm[axis] { + return Ray::new(ray.origin(), direction, ray.interval()[0], super::super::super::MAX_DISTANCE_MM).map_err(error); + } + } else { + let a = (v.min_mm[axis] - origin[axis]) / d[axis]; + let b = (v.max_mm[axis] - origin[axis]) / d[axis]; + enter = enter.max(a.min(b)); + leave = leave.min(a.max(b)); + } + } + let shift = if enter < leave { enter.min(0.0) } else { 0.0 }; + (ray.origin() + direction * shift, ray.interval()[0] - shift) + }; + Ray::new(source, direction, near, super::super::super::MAX_DISTANCE_MM).map_err(error) +} +pub(super) fn begin(task: &ImageTask, state: &mut State, ray: Ray) -> job::Result<()> { + medium(task)?; + state.volume = Some(Context { source: ray.origin(), ..Default::default() }); + Ok(()) +} +pub(super) fn reset_hit(state: &mut State) { + if let Some(v) = &mut state.volume { + v.range = None; + } +} +pub(super) fn surface(task: &ImageTask, state: &mut State) -> job::Result<()> { + let hit = unmapped(task, state)?; + let v = context_mut(state)?; + v.source = hit.position; + v.source_plane = Some(hit.vertices); + v.event = None; + v.range = Some([hit.primitive_index, hit.primitive_index.checked_add(1).ok_or_else(|| invalid("CPU Atmosphere source range overflow"))?]); + v.forward = false; + state.stage = Stage::VolumeSurface; + Ok(()) +} +pub(super) fn source(task: &ImageTask, state: &State) -> job::Result { + if let Some(v) = &state.volume { Ok(v.source) } else { Ok(shared(task, state)?.position) } +} +pub(super) fn ray(task: &ImageTask, state: &State, direction: Vec3, endpoint: Option, inclusive: bool) -> job::Result> { + if let Some(v) = &state.volume { + let (direction, far) = if let Some(point) = endpoint { + let delta = point - v.source; + let length = delta.len(); + let far = if inclusive { length } else { length.next_down() }; + if !far.is_finite() || far <= 0.0_f64.next_up() || delta.dot(direction) <= 0.0 { + return Ok(None); + } + (delta, far) + } else { + (direction, super::super::super::MAX_DISTANCE_MM) + }; + Ray::new(v.source, direction, 0.0_f64.next_up(), far).map(Some).map_err(error) + } else if let Some(point) = endpoint { + bounded_shadow(shared(task, state)?, point, direction) + } else { + shared(task, state)?.spawn(direction).map(Some).map_err(error) + } +} +pub(super) fn cursor(task: &ImageTask, state: &State, ray: Ray) -> job::Result { + let v = context(state)?; + if let Some(range) = v.range { + let plane = v.source_plane.ok_or_else(|| invalid("CPU Atmosphere source plane missing"))?; + // The same producing body's exact plane is excluded, not an offset path. + if range[1] > task.looks.len() { + return Err(invalid("CPU Atmosphere source range changed")); + } + Ok(TraceCursor::from_plane(ray, range[0]..range[1], plane)) + } else { + Ok(TraceCursor::new(ray, false)) + } +} +pub(super) fn response(task: &ImageTask, state: &State, direction: Vec3) -> job::Result> { + context(state)?.event.map(|incoming| medium(task)?.phase(incoming.dot(direction).clamp(-1.0, 1.0))).transpose() +} +pub(super) fn step(task: &mut ImageTask, state: &mut State) -> job::Result<()> { + match state.stage { + Stage::Volume => decide(task, state), + Stage::VolumeSurface => range(task, state), + Stage::VolumeShadow => shadow(task, state), + _ => Err(invalid("CPU Atmosphere bypassed its charged phase")), + } +} +fn decide(task: &mut ImageTask, state: &mut State) -> job::Result<()> { + let v = medium(task)?; + let c = context(state)?; + let ray = state.ray.ok_or_else(|| invalid("CPU Atmosphere incident ray missing"))?; + let endpoint = if let Some((_, _, point)) = state.emitter { + Some(point) + } else if state.hit.is_some() { + Some(unmapped(task, state)?.position) + } else { + None + }; + let limit = endpoint.map_or(super::super::super::MAX_DISTANCE_MM, |p| c.source.dist(p)); + let [near, far] = segment(v, c.source, ray.direction(), limit)?; + if near >= far { + state.stage = Stage::Resolve; + return Ok(()); + } + let [u, _] = variates(task, state, 0x6000)?; + let u = if u == 0.0 { 2.0_f64.powi(-54) } else { u }; + let travel = -(-u).ln_1p() / v.extinction_per_mm; + if travel >= far - near { + state.previous_pdf *= v.transmittance(far - near)?; + state.stage = Stage::Resolve; + return Ok(()); + } + let point = c.source + ray.direction() * (near + travel); + if point == c.source || endpoint == Some(point) || !array(point).into_iter().enumerate().all(|(i, x)| x > v.min_mm[i] && x < v.max_mm[i]) { + return Err(invalid("CPU Atmosphere collision is not representable strictly inside its box; change scale or density explicitly")); + } + for plane in [c.source_plane, state.hit.map(|_| unmapped(task, state)).transpose()?.map(|h| h.vertices)].into_iter().flatten() { + if super::super::super::glass_mesh::origin_on_plane(plane, point)? { + return Err(invalid("CPU Atmosphere collision rounds onto a source/endpoint plane")); + } + } + if let Some((i, _, _)) = state.emitter { + let light = task.options.area_lights.as_ref().and_then(|l| l.get(i)).ok_or_else(|| invalid("CPU Atmosphere emitter disappeared"))?; + if Rectangle::new(light).map_err(error)?.on_plane(point) { + return Err(invalid("CPU Atmosphere collision rounds onto its emitter plane")); + } + } + state.throughput = multiply(state.throughput, Vec3::new(v.scattering_albedo[0], v.scattering_albedo[1], v.scattering_albedo[2])); + super::super::super::lighting::validate_radiance(state.throughput).map_err(error)?; + if state.depth == 0 { + task.primary_coverage = 1; + } + let c = context_mut(state)?; + c.source = point; + c.source_plane = None; + c.range = None; + c.event = Some(ray.direction()); + if state.throughput == Vec3::ZERO { + state.stage = Stage::Commit; + return Ok(()); + } + state.light = 0; + state.sample = 0; + state.stage = Stage::Directional; + Ok(()) +} +fn range(task: &ImageTask, state: &mut State) -> job::Result<()> { + let hit = state.hit.ok_or_else(|| invalid("CPU Atmosphere source hit missing"))?; + let body = task.looks.get(hit.primitive_index).ok_or_else(|| invalid("CPU Atmosphere source primitive missing"))?.body_index; + let c = context_mut(state)?; + let r = c.range.as_mut().ok_or_else(|| invalid("CPU Atmosphere source range missing"))?; + if !c.forward { + if r[0] > 0 && task.looks.get(r[0] - 1).is_some_and(|p| p.body_index == body) { + r[0] -= 1; + } else { + c.forward = true; + } + } else if task.looks.get(r[1]).is_some_and(|p| p.body_index == body) { + r[1] = r[1].checked_add(1).ok_or_else(|| invalid("CPU Atmosphere source range overflow"))?; + } else { + state.stage = Stage::Effects; + } + Ok(()) +} +fn shadow(task: &ImageTask, state: &mut State) -> job::Result<()> { + let ray = state.shadow_ray.ok_or_else(|| invalid("CPU Atmosphere visibility ray missing"))?; + let v = medium(task)?; + let [a, b] = segment(v, ray.origin(), ray.direction(), ray.interval()[1])?; + let survival = v.transmittance(b - a)?; + state.contribution = state.contribution * survival; + context_mut(state)?.shadow_probability = survival; + state.stage = Stage::ShadowEmitters; + Ok(()) +} +pub(super) fn scatter(task: &ImageTask, state: &mut State) -> job::Result<()> { + let c = context(state)?; + let incoming = c.event.ok_or_else(|| invalid("CPU Atmosphere collision vertex missing"))?; + let position = c.source; + if !continuing(task, state)? { + state.stage = Stage::Commit; + return Ok(()); + } + let v = medium(task)?; + let u = variates(task, state, 0x6001)?; + // Reuse the exact shared HG inverse/frame, not a new approximation or BRDF. + let hg = crate::transmission::subsurface::Subsurface { scattering_per_mm: 1.0, anisotropy: v.anisotropy }; + let direction = hg.sample_direction(incoming, u).map_err(|e| JobError::new(ErrorCode::InvalidScene, e.to_string()))?; + state.previous_pdf = v.phase(incoming.dot(direction).clamp(-1.0, 1.0))?; + state.previous_position = position; + let ray = Ray::new(position, direction, 0.0_f64.next_up(), super::super::super::MAX_DISTANCE_MM).map_err(error)?; + state.ray = Some(ray); + state.cursor = Some(TraceCursor::new(ray, false)); + state.hit = None; + state.emitter = None; + state.depth += 1; + context_mut(state)?.event = None; + state.stage = Stage::Trace; + Ok(()) +} diff --git a/crates/render/src/raytrace/indirect.rs b/crates/render/src/raytrace/indirect.rs new file mode 100644 index 000000000..77e79ee7d --- /dev/null +++ b/crates/render/src/raytrace/indirect.rs @@ -0,0 +1,216 @@ +//! Original f64 opaque path proposals and finite rectangular emitter geometry. +//! Evaluation remains the shared surface BRDF; no radiance clamp or changed material model. +use super::{Ray, Result, TraceError}; +use crate::{ + job::RectangleLightOptions, + surface::{OpaqueSurface, unit_direction}, +}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use std::f64::consts::{PI, TAU}; + +fn invalid(message: &'static str) -> TraceError { + TraceError::InvalidInput(message) +} +fn vector(v: [f64; 3]) -> Vec3 { + Vec3::new(v[0], v[1], v[2]) +} +pub(super) fn multiply(a: Vec3, b: Vec3) -> Vec3 { + Vec3::new(a.x * b.x, a.y * b.y, a.z * b.z) +} + +/// Ratio form remains finite when the competing strategy has a very large density. +pub(super) fn power_weight(a: f64, b: f64) -> Result { + if !a.is_finite() || !b.is_finite() || a < 0.0 || b < 0.0 { + return Err(invalid("invalid CPU MIS density")); + } + if a == 0.0 { + return Ok(0.0); + } + let ratio = b / a; + Ok(1.0 / (1.0 + ratio * ratio)) +} +pub(super) fn surface_pdf(surface: OpaqueSurface, n: Vec3, v: Vec3, l: Vec3) -> Result { + crate::clear_coat::surface_pdf(surface, n, v, l).map_err(|_| invalid("invalid CPU path mixture PDF")) +} +fn from_local(n: Vec3, local: Vec3) -> Result { + let axis = if n.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z }; + let tangent = unit_direction(axis.cross(n)).map_err(|_| invalid("CPU path tangent"))?; + unit_direction(tangent * local.x + n.cross(tangent) * local.y + n * local.z).map_err(|_| invalid("CPU path local direction")) +} +#[derive(Clone, Copy, Debug)] +pub(super) struct Sample { + pub direction: Vec3, + pub pdf: f64, + pub weight: Vec3, +} + +/// Exact proposal used by clear_coat::surface_pdf: base is half cosine/half GGX NDF; +/// a coat selects its own NDF with probability weight/2. Null mass is never retried. +pub(super) fn sample(surface: OpaqueSurface, n: Vec3, geometric: Vec3, v: Vec3, u: [f64; 3]) -> Result> { + if u.into_iter().any(|x| !x.is_finite() || !(0.0..1.0).contains(&x)) { + return Err(invalid("CPU path variates must be in [0,1)")); + } + let n = unit_direction(n).map_err(|_| invalid("CPU path shading normal"))?; + let geometric = unit_direction(geometric).map_err(|_| invalid("CPU path geometric normal"))?; + let v = unit_direction(v).map_err(|_| invalid("CPU path view"))?; + if n.dot(v) <= 0.0 || geometric.dot(v) <= 0.0 { + return Ok(None); + } + let coat_probability = surface.clear_coat().map_or(0.0, |coat| coat.weight() * 0.5); + let base_component = (u[0] - coat_probability) / (1.0 - coat_probability); + let direction = if u[0] >= coat_probability && base_component < 0.5 { + let radius = u[1].sqrt(); + let phi = TAU * u[2]; + from_local(n, Vec3::new(radius * phi.cos(), radius * phi.sin(), (1.0 - u[1]).sqrt()))? + } else { + let roughness = if u[0] < coat_probability { + surface.clear_coat().ok_or_else(|| invalid("CPU coat selection disappeared"))?.roughness() + } else { + surface.roughness() + }; + let a2 = roughness.powi(4); + let cosine = ((1.0 - u[1]) / (1.0 + (a2 - 1.0) * u[1])).sqrt(); + let sine = (1.0 - cosine * cosine).max(0.0).sqrt(); + let phi = TAU * u[2]; + let half = from_local(n, Vec3::new(sine * phi.cos(), sine * phi.sin(), cosine))?; + if v.dot(half) <= 0.0 { + return Ok(None); + } + unit_direction(half * (2.0 * v.dot(half)) - v).map_err(|_| invalid("CPU reflected proposal"))? + }; + let cosine = n.dot(direction); + if cosine <= 0.0 || geometric.dot(direction) <= 0.0 { + return Ok(None); + } + let pdf = surface_pdf(surface, n, v, direction)?; + if pdf <= 0.0 { + return Err(invalid("CPU sampled direction has zero mixture PDF")); + } + let weight = surface.brdf(n, v, direction).map_err(|_| invalid("CPU path BRDF"))? * (cosine / pdf); + super::lighting::validate_radiance(weight)?; + Ok(Some(Sample { direction, pdf, weight })) +} + +#[derive(Clone, Copy)] +pub(super) struct Rectangle { + center: Vec3, + u: Vec3, + v: Vec3, + normal: Vec3, + area: f64, + pub radiance: Vec3, +} +#[derive(Clone, Copy, Debug)] +pub(super) struct LightSample { + pub position: Vec3, + pub direction: Vec3, + pub pdf: f64, +} +impl Rectangle { + /// Use the actual analytic consumer's plane arithmetic for event precision. + pub(super) fn on_plane(&self, point: Vec3) -> bool { + self.normal.dot(self.center - point) == 0.0 + } + pub(super) fn new(input: &RectangleLightOptions) -> Result { + // Reuse the existing bounds/units, including corners and orthogonal side vectors. + let checked = super::area::RectangleLight::new( + vector(input.center_mm), + vector(input.edge_u_mm), + vector(input.edge_v_mm), + vector(input.color), + input.intensity, + )?; + Ok(Self { + center: vector(input.center_mm), + u: vector(input.edge_u_mm), + v: vector(input.edge_v_mm), + normal: checked.normal(), + area: checked.area_mm2(), + radiance: vector(input.color) * input.intensity, + }) + } + pub(super) fn pdf(self, origin: Vec3, position: Vec3) -> Result { + let delta = position - origin; + let distance = delta.len(); + if !distance.is_finite() || distance <= 0.0 || distance > super::MAX_DISTANCE_MM { + return Err(invalid("CPU emitter distance outside ray bounds")); + } + let cosine = self.normal.dot(-delta / distance); + if cosine <= 0.0 { + return Ok(0.0); + } + let density = (distance * distance) / (self.area * cosine); + if !density.is_finite() { + return Err(invalid("CPU emitter PDF overflow")); + } + Ok(density) + } + pub(super) fn sample(self, origin: Vec3, u: [f64; 2]) -> Result> { + if u.into_iter().any(|x| !x.is_finite() || !(0.0..1.0).contains(&x)) { + return Err(invalid("CPU emitter variates")); + } + let position = self.center + self.u * (u[0] - 0.5) + self.v * (u[1] - 0.5); + let pdf = self.pdf(origin, position)?; + if pdf == 0.0 { + return Ok(None); + } + let delta = position - origin; + let distance = delta.len(); + Ok(Some(LightSample { position, direction: delta / distance, pdf })) + } + /// One-sided exact plane/basis intersection. Geometry wins equal-distance ties. + pub(super) fn intersect(self, ray: Ray) -> Result> { + let denominator = ray.direction().dot(self.normal); + if denominator >= 0.0 { + return Ok(None); + } + let distance = (self.center - ray.origin()).dot(self.normal) / denominator; + let [near, far] = ray.interval(); + if !distance.is_finite() || distance < near || distance > far { + return Ok(None); + } + let position = ray.origin() + ray.direction() * distance; + let delta = position - self.center; + // The admitted contract permits a small nonzero U.V. Independent projections + // fail badly for extreme aspect ratios; solve the actual two-vector basis. + let uu = self.u.len2(); + let vv = self.v.len2(); + let uv = self.u.dot(self.v); + let determinant = uu * vv - uv * uv; + if !determinant.is_finite() || determinant <= 0.0 { + return Err(invalid("CPU emitter basis is singular")); + } + let du = delta.dot(self.u); + let dv = delta.dot(self.v); + let u = (du * vv - dv * uv) / determinant; + let v = (dv * uu - du * uv) / determinant; + if !(-0.5..=0.5).contains(&u) || !(-0.5..=0.5).contains(&v) { + return Ok(None); + } + Ok(Some((distance, position))) + } +} + +/// Source samplers require an open unit interval. Counter samples and camera +/// jitter retain their original [0,1) contract; only the stratified source input +/// is repaired at floating-point endpoints, including last-cell rounding to one. +pub(super) fn open_stratum(raw: f64, cell: u32, side: u32) -> Result { + if !raw.is_finite() || !(0.0..1.0).contains(&raw) || !matches!(side, 1 | 2 | 4 | 8) || cell >= side { + return Err(invalid("CPU source stratum outside its bounded domain")); + } + let value = (f64::from(cell) + raw) / f64::from(side); + Ok(value.max(0.0_f64.next_up()).min(1.0_f64.next_down())) +} + +pub(super) fn uniform_environment(u: [f64; 2]) -> Vec3 { + let z = 1.0 - 2.0 * u[0]; + let radius = (1.0 - z * z).max(0.0).sqrt(); + let phi = TAU * u[1]; + Vec3::new(radius * phi.cos(), radius * phi.sin(), z) +} +pub(super) const ENVIRONMENT_PDF: f64 = 1.0 / (4.0 * PI); + +#[cfg(test)] +#[path = "indirect_tests.rs"] +mod tests; diff --git a/crates/render/src/raytrace/indirect_tests.rs b/crates/render/src/raytrace/indirect_tests.rs new file mode 100644 index 000000000..6814a5a22 --- /dev/null +++ b/crates/render/src/raytrace/indirect_tests.rs @@ -0,0 +1,247 @@ +use super::*; +use crate::clear_coat::ClearCoat; + +fn white() -> OpaqueSurface { + OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap() +} +fn rectangle() -> Rectangle { + Rectangle::new(&RectangleLightOptions { + center_mm: [0.0, 0.0, 2.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }) + .unwrap() +} + +#[test] +fn opaque_path_mixture_has_analytic_lambert_and_matched_full_coat_density() { + let count = 16384; + let mut mean = Vec3::ZERO; + for component in [0.25, 0.75] { + for i in 0..count { + if let Some(s) = sample(white(), Vec3::Z, Vec3::Z, Vec3::Z, [component, (f64::from(i) + 0.5) / f64::from(count), 0.37]).unwrap() { + // For alpha=1 and normal view, NDF reflection density is 1/(4*pi). + let expected = 0.5 * s.direction.z / PI + 0.5 / (4.0 * PI); + assert!((s.pdf - expected).abs() < 1e-14); + assert!((s.weight.x * s.pdf - s.direction.z / PI).abs() < 1e-14); + mean += s.weight / (2.0 * f64::from(count)); + } + } + } + assert!((mean - Vec3::new(1.0, 1.0, 1.0)).len() < 1e-6, "index-matched Lambert white furnace: {mean:?}"); + for metallic in [0.0, 0.5, 1.0] { + let surface = + OpaqueSurface::new(Vec3::new(0.7, 0.3, 0.1), metallic, 0.4, 1.5).unwrap().with_clear_coat(ClearCoat::new(0.8, 0.3, 1.4).unwrap()); + for i in 0..4096 { + let u = [(f64::from(i) + 0.5) / 4096.0, ((i * 37 % 4096) as f64 + 0.5) / 4096.0, ((i * 101 % 4096) as f64 + 0.5) / 4096.0]; + if let Some(s) = sample(surface, Vec3::Z, Vec3::Z, Vec3::Z, u).unwrap() { + let h = unit_direction(Vec3::Z + s.direction).unwrap(); + let ndf = |roughness: f64| { + let a2 = roughness.powi(4); + let denom = 1.0 - h.z * h.z + h.z * h.z * a2; + a2 / (PI * denom * denom) * h.z / (4.0 * h.z) + }; + let expected = 0.6 * (0.5 * s.direction.z / PI + 0.5 * ndf(0.4)) + 0.4 * ndf(0.3); + assert!((s.pdf - expected).abs() < 1e-12 * expected.max(1.0)); + let expected = surface.brdf(Vec3::Z, Vec3::Z, s.direction).unwrap() * s.direction.z; + assert!((s.weight * s.pdf - expected).len() < 1e-11 * expected.len().max(1.0)); + } + } + } + for bad in [f64::NAN, -0.1, 1.0] { + assert!(sample(white(), Vec3::Z, Vec3::Z, Vec3::Z, [bad, 0.3, 0.7]).is_err()); + } + assert!((power_weight(3.0, 4.0).unwrap() - 9.0 / 25.0).abs() < 1e-16); + assert_eq!(power_weight(0.0, 0.0).unwrap(), 0.0); + assert!(power_weight(f64::INFINITY, 1.0).is_err()); +} + +#[test] +fn opaque_path_rectangles_have_exact_facing_intervals_area_pdf_and_sample_count_weights() { + let light = rectangle(); + let center = light.sample(Vec3::ZERO, [0.5, 0.5]).unwrap().unwrap(); + assert_eq!(center.position, Vec3::new(0.0, 0.0, 2.0)); + assert_eq!(center.pdf, 1.0); // distance² / (area*cos) = 4/4. + let ray = Ray::new(Vec3::ZERO, Vec3::Z, 0.0, 3.0).unwrap(); + assert_eq!(light.intersect(ray).unwrap().unwrap(), (2.0, center.position)); + assert!(light.intersect(Ray::new(Vec3::ZERO, Vec3::Z, 0.0, 2.0_f64.next_down()).unwrap()).unwrap().is_none()); + assert!(light.intersect(Ray::new(Vec3::new(0.0, 0.0, 3.0), -Vec3::Z, 0.0, 4.0).unwrap()).unwrap().is_none()); + assert!(light.sample(Vec3::new(0.0, 0.0, 3.0), [0.5, 0.5]).unwrap().is_none()); + for samples in [1, 4, 16, 64] { + let p = surface_pdf(white(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap(); + let light_density = f64::from(samples) * center.pdf; + let a = power_weight(light_density, p).unwrap(); + let b = power_weight(p, light_density).unwrap(); + assert!((a + b - 1.0).abs() < 2e-16, "sample count belongs to both MIS competitors"); + } +} + +#[test] +fn opaque_path_rectangle_nee_and_bsdf_mis_means_match_the_analytic_projected_solid_angle() { + let light = rectangle(); + // Independent projected solid angle of a parallel rectangle, half extents1, height2. + let expected = 4.0 / 5.0_f64.sqrt() * (1.0 / 5.0_f64.sqrt()).atan() / PI; + for samples in [1, 4, 16] { + let mut nee = 0.0; + let mut bsdf = 0.0; + let side = 512; + for y in 0..side { + for x in 0..side { + let u = [(f64::from(x) + 0.5) / f64::from(side), (f64::from(y) + 0.5) / f64::from(side)]; + let s = light.sample(Vec3::ZERO, u).unwrap().unwrap(); + let p = surface_pdf(white(), Vec3::Z, Vec3::Z, s.direction).unwrap(); + nee += s.direction.z / (PI * s.pdf) * power_weight(f64::from(samples) * s.pdf, p).unwrap(); + for component in [0.25, 0.75] { + if let Some(s) = sample(white(), Vec3::Z, Vec3::Z, Vec3::Z, [component, u[0], u[1]]).unwrap() + && let Some((_, point)) = light.intersect(Ray::new(Vec3::ZERO, s.direction, 0.0, 100.0).unwrap()).unwrap() + { + bsdf += 0.5 * s.weight.x * power_weight(s.pdf, f64::from(samples) * light.pdf(Vec3::ZERO, point).unwrap()).unwrap(); + } + } + } + } + let actual = (nee + bsdf) / f64::from(side * side); + // A fixed midpoint grid crosses the emitter boundary; its integration error is + // bounded here at 0.002 absolute radiance, independent of production's sampler. + assert!((actual - expected).abs() < 0.002, "N={samples}: {actual} vs {expected}"); + } +} + +#[test] +fn opaque_path_oblique_and_grazing_coated_response_and_null_mass_match_independent_hemisphere_quadrature() { + let side = 512; + let cells = f64::from(side * side); + for cosine in [0.4_f64, 0.02] { + let view = Vec3::new((1.0 - cosine * cosine).sqrt(), 0.0, cosine); + for metallic in [0.0, 0.5, 1.0] { + let surface = + OpaqueSurface::new(Vec3::new(0.7, 0.3, 0.1), metallic, 0.6, 1.5).unwrap().with_clear_coat(ClearCoat::new(0.8, 0.5, 1.4).unwrap()); + let mut quadrature = Vec3::ZERO; + let mut density = 0.0; + let mut sampled = Vec3::ZERO; + let mut mass = 0.0; + for row in 0..side { + let u = (f64::from(row) + 0.5) / f64::from(side); + for col in 0..side { + let v = (f64::from(col) + 0.5) / f64::from(side); + // Independent integration over light-direction solid angle, not the + // proposal's half-vector coordinates. Equal-area cells have dω=2π/N². + let phi = TAU * v; + let l = Vec3::new((1.0 - u * u).sqrt() * phi.cos(), (1.0 - u * u).sqrt() * phi.sin(), u); + let half = unit_direction(view + l).unwrap(); + let vh = view.dot(half); + let ndf = |roughness: f64| { + let a2 = roughness.powi(4); + let denominator = 1.0 - half.z * half.z + half.z * half.z * a2; + a2 * half.z / (PI * denominator * denominator * 4.0 * vh) + }; + let independent_pdf = 0.6 * (0.5 * u / PI + 0.5 * ndf(0.6)) + 0.4 * ndf(0.5); + density += independent_pdf * TAU / cells; + quadrature += surface.brdf(Vec3::Z, view, l).unwrap() * (u * TAU / cells); + // Enumerate mixture components with their original probability. + // Rejected NDF directions contribute zero mass and zero radiance; + // no retry and no division by the number of accepted samples. + for (component, probability) in [(0.2, 0.4), (0.55, 0.3), (0.85, 0.3)] { + if let Some(s) = sample(surface, Vec3::Z, Vec3::Z, view, [component, u, v]).unwrap() { + mass += probability / cells; + sampled += s.weight * (probability / cells); + assert!((s.pdf - surface_pdf(surface, Vec3::Z, view, s.direction).unwrap()).abs() < 1e-12 * s.pdf.max(1.0)); + } + } + } + } + assert!(mass < 0.99, "grazing NDF null samples must remain in the estimator"); + assert!((mass - density).abs() < 0.005, "nv={cosine}, metal={metallic}: accepted mass{mass}, independent PDF mass{density}"); + for (actual, expected) in [sampled.x, sampled.y, sampled.z].into_iter().zip([quadrature.x, quadrature.y, quadrature.z]) { + assert!((actual - expected).abs() < 0.005, "nv={cosine}, metal={metallic}: sampled{actual}, independent hemisphere{expected}"); + } + } + } +} + +#[test] +fn opaque_path_nearly_orthogonal_extreme_aspect_rectangles_round_trip_their_admitted_samples() { + // The common light contract permits |cos(U,V)| <= 1e-10. A diagonal + // projection would infer s≈22.5 for the first sample despite its true s=0. + let light = Rectangle::new(&RectangleLightOptions { + center_mm: [0.0, 0.0, 2.0], + edge_u_mm: [1e-6, 0.0, 0.0], + edge_v_mm: [9e-5, -1e6, 0.0], + color: [1.0; 3], + intensity: 1.0, + }) + .unwrap(); + for uv in [[0.5, 0.75], [0.25, 0.125], [0.75, 0.625]] { + let sample = light.sample(Vec3::ZERO, uv).unwrap().unwrap(); + let ray = Ray::new(Vec3::ZERO, sample.direction, 0.0, sample.position.len() * 2.0).unwrap(); + let (distance, point) = light.intersect(ray).unwrap().expect("every admitted interior sample belongs to the BSDF support"); + assert!((distance - sample.position.len()).abs() <= 1e-9 * distance); + assert!((point - sample.position).len() <= 1e-9 * distance); + assert!((light.pdf(Vec3::ZERO, point).unwrap() - sample.pdf).abs() <= 1e-9 * sample.pdf); + } +} + +#[test] +fn opaque_path_source_strata_are_open_at_both_floating_point_endpoints() { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + let mut input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 64).unwrap().begin().unwrap(); + for _ in 0..10000 { + if input.ready() { + break; + } + input.prepare_one(|| false).unwrap(); + } + assert!(input.ready()); + let environment = input.view().unwrap(); + for side in [1, 2, 4, 8] { + for cell in 0..side { + for raw in [0.0, 1.0_f64.next_down()] { + let value = open_stratum(raw, cell, side).unwrap(); + assert!(value > 0.0 && value < 1.0, "N={}, cell={cell}, raw={raw}, value={value}", side * side); + assert!(environment.sample([value, value]).is_ok()); + assert!(rectangle().sample(Vec3::ZERO, [value, value]).is_ok()); + } + } + } + for (raw, cell, side) in [(1.0, 0, 1), (-0.1, 0, 1), (f64::NAN, 0, 1), (0.5, 1, 1), (0.5, 0, 3)] { + assert!(open_stratum(raw, cell, side).is_err()); + } +} + +#[test] +fn authored_point_zero_two_base_and_coated_path_pdf_use_the_exact_unclamped_finish() { + let original = white(); + let finish = original.with_authored_finish(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.02).unwrap(); + for coat_weight in [0.0, 0.6] { + let coat = crate::clear_coat::ClearCoat::new(coat_weight, 0.2, 1.5).unwrap(); + let surface = finish.with_clear_coat(coat); + let a2 = 0.02_f64.powi(4); + let ca2 = 0.2_f64.powi(4); + let c = 0.8; + let h2 = (1.0 + c) / 2.0; + let density = |alpha2: f64| { + let d = (1.0 - h2) + h2 * alpha2; + alpha2 / (std::f64::consts::PI * d * d) / 4.0 + }; + let p = coat_weight / 2.0; + let expected = (1.0 - p) * (0.5 * c / std::f64::consts::PI + 0.5 * density(a2)) + p * density(ca2); + let l = Vec3::new(0.6, 0.0, c); + let actual = surface_pdf(surface, Vec3::Z, Vec3::Z, l).unwrap(); + assert!((actual - expected).abs() < 1e-14); + for u in [[0.1, 0.2, 0.3], [0.8, 0.2, 0.3], [0.99, 0.9, 0.7]] { + if let Some(sample) = sample(surface, Vec3::Z, Vec3::Z, Vec3::Z, u).unwrap() { + assert!(sample.pdf.is_finite() && sample.pdf > 0.0); + let pdf = surface_pdf(surface, Vec3::Z, Vec3::Z, sample.direction).unwrap(); + assert_eq!(sample.pdf, pdf); + let brdf = surface.brdf(Vec3::Z, Vec3::Z, sample.direction).unwrap(); + assert_eq!(sample.weight, brdf * (sample.direction.z / pdf)); + } + } + } +} diff --git a/crates/render/src/raytrace/legacy_certificates.rs b/crates/render/src/raytrace/legacy_certificates.rs new file mode 100644 index 000000000..1baf72bb3 --- /dev/null +++ b/crates/render/src/raytrace/legacy_certificates.rs @@ -0,0 +1,207 @@ +//! Bounded legacy sheet/box preparation. The strict synchronous admission API +//! may drain this cursor; an image task instead yields before tracing any pixel. +use super::{ + Bounds, Result, TraceError, WorkBudget, + box_certificate::BoxTask, + dielectric::{self, Certificate, MAX_OVERRIDES}, +}; +use crate::{ + ProductScene, + job::{CancelToken, DielectricBoundary, ImageRequest, RaytraceOptions}, +}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +use std::mem::size_of; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Stage { + Shape, + Box, + FinishBox, + Pairs, + Sheets, + Lens, + Done, +} + +pub(crate) struct Task { + values: [Option; MAX_OVERRIDES], + boxes: Vec, + count: usize, + stage: Stage, + i: usize, + j: usize, + pupil: Option<(Vec3, f64)>, +} + +fn selected_box_capacity(scene: &ProductScene, options: &RaytraceOptions) -> Result { + if options.dielectrics.len() > MAX_OVERRIDES { + return Err(TraceError::InvalidInput("too many dielectric overrides")); + } + let mut maximum = 0; + for input in &options.dielectrics { + let body = scene.meshes.get(input.body_index).ok_or(TraceError::InvalidInput("dielectric body ordinal"))?; + if body.name != input.body_name { + return Err(TraceError::InvalidInput("dielectric captured body identity mismatch")); + } + if input.boundary == DielectricBoundary::ClosedMesh || input.shadow_transmission { + return Err(TraceError::InvalidInput("general glass requires explicit CPU Path transport")); + } + if input.boundary == DielectricBoundary::ClosedBox { + BoxTask::required_bytes(body.mesh.triangles.len())?; + maximum = maximum.max(body.mesh.triangles.len()); + } else if !(1..=2).contains(&body.mesh.triangles.len()) || body.mesh.positions.len() > 36 { + return Err(TraceError::InvalidInput("unsupported dielectric boundary tessellation")); + } + } + Ok(maximum) +} + +impl Task { + pub(crate) fn required_bytes(scene: &ProductScene, options: &RaytraceOptions) -> Result { + if options.dielectrics.is_empty() || options.path.is_some() { + return Ok(0); + } + let maximum = selected_box_capacity(scene, options)?; + let buffers = if maximum == 0 { 0 } else { BoxTask::required_bytes(maximum)? }; + buffers.checked_add(size_of::() as u64).ok_or(TraceError::MemoryLimit) + } + + pub(super) fn new(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> Result { + Self::required_bytes(scene, options)?; + let maximum = selected_box_capacity(scene, options)?; + let mut boxes = Vec::new(); + if maximum != 0 { + boxes.try_reserve_exact(1).map_err(|_| TraceError::AllocationFailed)?; + if boxes.capacity() != 1 { + return Err(TraceError::MemoryLimit); + } + boxes.push(BoxTask::new(maximum)?); + } + Ok(Self { + values: [None; MAX_OVERRIDES], + boxes, + count: options.dielectrics.len(), + stage: Stage::Shape, + i: 0, + j: 1, + pupil: options.lens.filter(|lens| lens.aperture_radius_mm > 0.0).map(|lens| (request.camera.eye(), lens.aperture_radius_mm)), + }) + } + + pub(super) fn ready(&self) -> bool { + self.stage == Stage::Done + } + pub(super) fn into_proof(self, work_used: u64) -> Result { + if !self.ready() { + return Err(TraceError::BuildIncomplete); + } + Ok(super::image::CertifiedOptics::legacy(self.values, work_used)) + } + + pub(super) fn step(&mut self, scene: &ProductScene, options: &RaytraceOptions, work: &mut WorkBudget, cancel: &CancelToken) -> Result<()> { + if self.ready() { + return super::check_cancel(cancel); + } + if self.stage == Stage::Box { + let input = options.dielectrics.get(self.i).ok_or(TraceError::Internal("legacy box target"))?; + let body = scene + .meshes + .get(input.body_index) + .filter(|body| body.name == input.body_name) + .ok_or(TraceError::InvalidInput("dielectric captured body identity mismatch"))?; + if self.boxes.first_mut().ok_or(TraceError::Internal("legacy box cursor"))?.step(&body.mesh, work, cancel)? { + self.stage = Stage::FinishBox; + } + return Ok(()); + } + work.tick(cancel)?; + match self.stage { + Stage::Shape => { + if let Some(input) = options.dielectrics.get(self.i) { + let body = scene + .meshes + .get(input.body_index) + .filter(|body| body.name == input.body_name) + .ok_or(TraceError::InvalidInput("dielectric captured body identity mismatch"))?; + if input.boundary == DielectricBoundary::ClosedBox { + self.boxes.first_mut().ok_or(TraceError::Internal("legacy box cursor"))?.reset(body.mesh.triangles.len())?; + self.stage = Stage::Box; + } else { + let value = dielectric::certify_sheet(&body.mesh)?; + *self.values.get_mut(self.i).ok_or(TraceError::Internal("legacy sheet result"))? = Some(value); + self.i += 1; + } + } else { + self.i = 0; + self.j = 1; + self.stage = Stage::Pairs; + } + } + Stage::FinishBox => { + let bounds = self.boxes.first().ok_or(TraceError::Internal("legacy box result"))?.result()?; + *self.values.get_mut(self.i).ok_or(TraceError::Internal("legacy box result slot"))? = Some(Certificate::ClosedBox(bounds)); + self.i += 1; + self.stage = Stage::Shape; + } + Stage::Pairs => { + if self.i >= self.count { + self.i = 0; + self.j = 0; + self.stage = Stage::Sheets; + } else if self.j >= self.count { + self.i += 1; + self.j = self.i + 1; + } else { + if let (Some(Some(Certificate::ClosedBox(a))), Some(Some(Certificate::ClosedBox(b)))) = + (self.values.get(self.i), self.values.get(self.j)) + && dielectric::overlaps(*a, *b) + { + return Err(TraceError::InvalidInput("nested, touching or overlapping dielectric volumes are unsupported")); + } + self.j += 1; + } + } + Stage::Sheets => { + if self.i >= self.count { + self.i = 0; + self.stage = Stage::Lens; + } else if self.j >= self.count { + self.i += 1; + self.j = 0; + } else { + if self.i != self.j + && let Some(Some(Certificate::ClosedBox(a))) = self.values.get(self.i) + && matches!(self.values.get(self.j), Some(Some(Certificate::ThinSheet))) + { + let input = options.dielectrics.get(self.j).ok_or(TraceError::Internal("sheet override index"))?; + let body = scene.meshes.get(input.body_index).ok_or(TraceError::Internal("sheet body index"))?; + let bounds = body.mesh.bounds(); + if dielectric::overlaps(*a, Bounds::new(bounds.min, bounds.max)?) { + return Err(TraceError::InvalidInput("thin sheets touching or inside dielectric volumes are unsupported")); + } + } + self.j += 1; + } + } + Stage::Lens => { + if let Some((eye, radius)) = self.pupil + && let Some(value) = self.values.get(self.i).filter(|_| self.i < self.count) + { + if let Some(Certificate::ClosedBox(bounds)) = value { + let nearest = eye.max(bounds.min()).min(bounds.max()); + if eye.dist(nearest) <= radius { + return Err(TraceError::InvalidInput("thin-lens aperture sphere touches or enters a certified dielectric volume")); + } + } + self.i += 1; + } else { + self.stage = Stage::Done; + } + } + Stage::Box => return Err(TraceError::Internal("legacy box skipped bounded cursor")), + Stage::Done => {} + } + Ok(()) + } +} diff --git a/crates/render/src/raytrace/mod.rs b/crates/render/src/raytrace/mod.rs index 45a834fc1..9211f6acd 100644 --- a/crates/render/src/raytrace/mod.rs +++ b/crates/render/src/raytrace/mod.rs @@ -8,13 +8,22 @@ use crate::job::CancelToken; use solidcore_record::Vec3; use solidcraft_geom::prelude::*; +mod aging; mod anisotropic_faces; pub mod area; +mod box_certificate; mod bvh; +mod celestial; +mod denoise; pub mod dielectric; pub mod emission; +mod glass_mesh; +mod glass_volume; pub mod image; +mod indirect; +pub(crate) mod legacy_certificates; pub mod lighting; +mod origin; pub mod prepared; mod progressive; pub mod punctual; @@ -272,7 +281,7 @@ impl Triangle { let z = component(delta, kz); [component(delta, kx) - sx * z, component(delta, ky) - sy * z, z / dominant] }); - let [[ax, ay, az], [bx, by, bz], [cx, cy, cz]] = projected; + let [[ax, ay, _], [bx, by, _], [cx, cy, _]] = projected; let weights = [bx * cy - by * cx, cx * ay - cy * ax, ax * by - ay * bx]; let [u, v, w] = weights; if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) { @@ -283,12 +292,12 @@ impl Triangle { return None; } let barycentric = weights.map(|value| value / determinant); - let [u, v, w] = barycentric; - // Divide before multiplying by depth: very small triangle areas need not - // underflow their otherwise well-represented hit distance. - // An exact coordinate plane has a direct depth equation. Summing - // depths along another dominant ray axis can cancel large tangential - // terms into a false positive. No interval or edge policy changes. + // Solve depth from the geometric plane, independently of the closed-edge + // shear weights. Weighted depths along another ray axis can cancel large + // tangential terms into a positive self-hit, even for an outward ray. + // This also matters for evaluated CAD faces that differ from a coordinate + // plane by a few ULPs; they must not rely on the exact-axis shortcut. + // Exact coordinate planes retain their direct interval arithmetic. let axis_plane = (0..3).find_map(|axis| { let [a, b, c] = self.vertices.map(|point| component(point, axis)); (a == b && b == c).then_some((axis, a)) @@ -296,7 +305,7 @@ impl Triangle { let distance = if let Some((axis, coordinate)) = axis_plane { (coordinate - component(ray.origin, axis)) / component(d, axis) } else { - u * az + v * bz + w * cz + normal.dot(self.vertices[0] - ray.origin) / normal.dot(d) }; if !distance.is_finite() || distance < ray.min || distance > ray.max { return None; diff --git a/crates/render/src/raytrace/origin.rs b/crates/render/src/raytrace/origin.rs new file mode 100644 index 000000000..805de8571 --- /dev/null +++ b/crates/render/src/raytrace/origin.rs @@ -0,0 +1,216 @@ +//! One reusable prepaid primary-origin certificate. No camera sample, RNG, image +//! plane or scene mutation: one bounds/BVH/triangle/hierarchy operation per step. +use super::{ + Bounds, WorkBudget, + bvh::{PrimitiveScan, ScanPoll}, + glass_mesh, +}; +use crate::job::{self, CancelToken, DielectricBoundary, DielectricOptions}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; +fn invalid(message: &str) -> job::JobError { + job::JobError::new(job::ErrorCode::InvalidScene, message) +} +fn contains(b: Bounds, p: Vec3) -> bool { + let lo = b.min(); + let hi = b.max(); + p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y && p.z >= lo.z && p.z <= hi.z +} +#[derive(Clone, Copy)] +enum Stage { + Bounds, + Faces, + FaceResult, + Preclip, + PreclipScan, + Order, + Done, +} +pub(super) struct Task { + origin: Vec3, + near: Vec3, + point: usize, + medium: usize, + winding: i32, + bits: [u8; 2], + stage: Stage, + ordered: [usize; 8], + occupied: u8, + len: usize, + cursor: Option, +} +impl Task { + pub(super) fn required_bytes() -> u64 { + std::mem::size_of::() as u64 + } + /// Outward bounds are conservative. Existing outside rays pay no new work + /// and allocate no classifier slot; actual ambiguous pupil samples decide. + pub(super) fn required(certificate: &glass_mesh::Task, inputs: &[DielectricOptions], origin: Vec3, near: Vec3) -> job::Result { + for (i, _) in inputs.iter().enumerate() { + let b = certificate.region(i)?.bounds; + let lo = origin.min(near); + let hi = origin.max(near); + let min = b.min(); + let max = b.max(); + if lo.x <= max.x && hi.x >= min.x && lo.y <= max.y && hi.y >= min.y && lo.z <= max.z && hi.z >= min.z { + return Ok(true); + } + } + Ok(false) + } + pub(super) fn new(origin: Vec3, near: Vec3) -> job::Result { + if !super::bounded(origin) || !super::bounded(near) { + return Err(invalid("CPU camera origin exceeds the bounded world envelope")); + } + Ok(Self { + origin, + near, + point: 0, + medium: 0, + winding: 0, + bits: [0; 2], + stage: Stage::Bounds, + ordered: [0; 8], + occupied: 0, + len: 0, + cursor: None, + }) + } + pub(super) fn ready(&self) -> bool { + matches!(self.stage, Stage::Done) + } + pub(super) fn result(&self) -> job::Result<([usize; 8], usize, Vec3)> { + if !self.ready() { + return Err(invalid("CPU camera medium certificate is incomplete")); + } + Ok((self.ordered, self.len, self.origin)) + } + pub(super) fn step( + &mut self, + certificate: &glass_mesh::Task, + inputs: &[DielectricOptions], + scene: super::prepared::PreparedScene<'_>, + work: &mut WorkBudget, + cancel: &CancelToken, + ) -> job::Result<()> { + if matches!(self.stage, Stage::Faces | Stage::PreclipScan) { + let poll = self + .cursor + .as_mut() + .ok_or_else(|| invalid("CPU camera classification cursor missing"))? + .step(scene.bvh, work, cancel) + .map_err(super::image::error)?; + match poll { + ScanPoll::Pending => {} + ScanPoll::Done => { + self.cursor = None; + self.stage = if matches!(self.stage, Stage::Faces) { Stage::FaceResult } else { Stage::Order }; + self.medium = if matches!(self.stage, Stage::Order) { 0 } else { self.medium }; + } + ScanPoll::Primitive(index) => { + let look = scene.primitives.get(index).ok_or_else(|| invalid("CPU camera classification primitive missing"))?; + if matches!(self.stage, Stage::Faces) { + let region = certificate.region(self.medium)?; + if (region.primitive_begin..region.primitive_end).contains(&index) { + let p = if self.point == 0 { self.origin } else { self.near }; + self.winding = self + .winding + .checked_add(i32::from(glass_mesh::origin_crossing(look.vertices, p)?)) + .ok_or_else(|| invalid("CPU camera winding overflow"))?; + } + } else if inputs.iter().any(|input| input.body_index == look.body_index) + && glass_mesh::origin_segment_contact(look.vertices, self.origin, self.near)? + { + return Err(invalid("CPU camera near clipping meets a Glass boundary; move the camera or pupil away from that boundary")); + } + } + } + return Ok(()); + } + work.tick(cancel).map_err(super::image::error)?; + if inputs.len() > 8 { + return Err(invalid("CPU camera classification exceeds eight media")); + } + match self.stage { + Stage::Bounds => { + let Some(input) = inputs.get(self.medium) else { + if self.point == 0 && self.origin != self.near { + self.point = 1; + self.medium = 0; + return Ok(()); + } + if self.point == 0 { + self.bits[1] = self.bits[0]; + } + if self.bits[0] != self.bits[1] { + return Err(invalid("CPU camera near clipping crosses a Glass boundary; move the camera or pupil away from that boundary")); + } + self.medium = 0; + self.stage = if self.origin == self.near { Stage::Order } else { Stage::Preclip }; + return Ok(()); + }; + let region = certificate.region(self.medium)?; + let p = if self.point == 0 { self.origin } else { self.near }; + if input.boundary == DielectricBoundary::ThinSheet || !contains(region.bounds, p) { + self.medium += 1; + return Ok(()); + } + self.winding = 0; + self.cursor = Some(PrimitiveScan::new(p, Vec3::new(region.bounds.max().x, p.y, p.z)).map_err(super::image::error)?); + self.stage = Stage::Faces; + } + Stage::FaceResult => { + if !(0..=1).contains(&self.winding) { + return Err(invalid("CPU camera winding disagrees with its certified closed manifold")); + } + if self.winding == 1 { + let bits = self.bits.get_mut(self.point).ok_or_else(|| invalid("CPU camera point cursor"))?; + *bits |= 1_u8 << self.medium; + } + self.medium += 1; + self.stage = Stage::Bounds; + } + Stage::Preclip => { + self.cursor = Some(PrimitiveScan::new(self.origin.min(self.near), self.origin.max(self.near)).map_err(super::image::error)?); + self.stage = Stage::PreclipScan; + } + Stage::Order => { + let Some(_) = inputs.get(self.medium) else { + if self.occupied.count_ones() as usize != self.len { + return Err(invalid("CPU camera medium hierarchy has a missing parent")); + } + self.stage = Stage::Done; + return Ok(()); + }; + if self.bits[0] & (1_u8 << self.medium) != 0 { + let mut parent = certificate.region(self.medium)?.parent; + let mut depth = 0; + for _ in 0..8 { + let Some(p) = parent else { + break; + }; + if p >= inputs.len() || self.bits[0] & (1_u8 << p) == 0 { + return Err(invalid("CPU camera origin is not inside its certified medium parent")); + } + depth += 1; + parent = certificate.region(p)?.parent; + } + if parent.is_some() || depth >= 8 { + return Err(invalid("CPU camera medium hierarchy exceeds eight layers")); + } + let occupied = 1_u8 << depth; + if self.occupied & occupied != 0 { + return Err(invalid("CPU camera origin is inside unrelated optical regions")); + } + *self.ordered.get_mut(depth).ok_or_else(|| invalid("CPU camera ordered medium slot"))? = self.medium; + self.occupied |= occupied; + self.len = self.len.max(depth + 1); + } + self.medium += 1; + } + Stage::Done => return Err(invalid("CPU camera medium certificate already complete")), + Stage::Faces | Stage::PreclipScan => return Err(invalid("CPU camera scan bypassed its charged continuation")), + } + Ok(()) + } +} diff --git a/crates/render/src/raytrace/planar_shadow_tests.rs b/crates/render/src/raytrace/planar_shadow_tests.rs index bfc44cf48..0d4980a52 100644 --- a/crates/render/src/raytrace/planar_shadow_tests.rs +++ b/crates/render/src/raytrace/planar_shadow_tests.rs @@ -1,4 +1,4 @@ -//! Proposed regressions, not compiled or run; install only with the reviewed depth change. +//! Analytic shadow-ray depth regressions for exact and nearly coordinate-planar faces. use super::*; use prepared::SharedHit; @@ -123,3 +123,44 @@ fn exact_coordinate_plane_depth_keeps_closed_intervals_signed_zero_and_oblique_p let oblique = Triangle::new([Vec3::new(-4.0, -4.0, -4.0), Vec3::new(4.0, -4.0, 4.0), Vec3::new(4.0, 4.0, 4.0)]).unwrap(); assert_eq!(oblique.intersect(&Ray::new(Vec3::new(1.0, 1.0, 9.0), -Vec3::Z, 0.0, 10.0).unwrap()).unwrap().distance, 8.0); } + +#[test] +fn native_sample_plate_front_face_does_not_shadow_its_outgoing_rim_ray() { + // These are the two front-side triangles of the built-in Sample Plate, + // exported at standard quality. Tiny evaluated coordinate differences make + // this a real slanted plane, not an exactly axis-aligned special case. + let fixtures = [ + ( + [ + Vec3::new(5.9999999999993445, -1.7763568393612512e-15, 0.0), + Vec3::new(74.00000000000065, 1.77635683943593e-15, 8.0), + Vec3::new(5.999999999999999, -1.7763568394002505e-15, 8.0), + ], + Vec3::new(12.935950282461624, -1.413982641678367e-15, 5.4093378813347), + ), + ( + [ + Vec3::new(73.99999999999999, 1.7763568394002296e-15, 0.0), + Vec3::new(74.00000000000065, 1.77635683943593e-15, 8.0), + Vec3::new(5.9999999999993445, -1.7763568393612512e-15, 0.0), + ], + Vec3::new(42.44826731118756, 1.2791165835596725e-16, 3.8240400501773513), + ), + ]; + for (vertices, origin) in fixtures { + let triangle = Triangle::new(vertices).unwrap(); + let ray = Ray::new(origin, Vec3::new(0.0, -0.6, 0.8), 0.0_f64.next_up(), MAX_DISTANCE_MM).unwrap(); + let normal = triangle.geometric_normal().unwrap(); + // Independent plane-side oracle: the origin is outside and the ray + // travels farther outside. No positive plane intersection can exist. + assert!((origin - vertices[0]).dot(normal) > 0.0); + assert!(ray.direction().dot(normal) > 0.0); + assert!(triangle.intersect(&ray).is_none(), "the departed Sample Plate face cannot occlude its own rim light"); + // A distinct surface only 5 micrometres along this same ray must remain + // visible. The repair must not introduce a near-distance rejection floor. + let center = ray.at(0.005).unwrap(); + let blocker = + Triangle::new([center + Vec3::new(-1.0, 0.0, -1.0), center + Vec3::new(1.0, 0.0, -1.0), center + Vec3::new(0.0, 0.0, 1.0)]).unwrap(); + assert!(blocker.intersect(&ray).is_some()); + } +} diff --git a/crates/render/src/raytrace/primary_aa_tests.rs b/crates/render/src/raytrace/primary_aa_tests.rs index 3af7007ae..687574ebe 100644 --- a/crates/render/src/raytrace/primary_aa_tests.rs +++ b/crates/render/src/raytrace/primary_aa_tests.rs @@ -1,4 +1,92 @@ -//! Spatial AA regressions: WRITTEN NOT RUN. No historical gate is transferred. +//! Spatial camera sampling and CPU output presentation regressions. +// Independent reader for the public uncompressed scanline/FLOAT wire layout used +// by these retained masters. It deliberately uses neither our encoder's header +// constructor nor the production native-master decoder, and preserves raw bits. +fn native_exr_pixels(bytes: &[u8]) -> ::image::Rgba32FImage { + fn word(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) + } + fn string<'a>(bytes: &'a [u8], cursor: &mut usize) -> &'a [u8] { + let begin = *cursor; + let length = bytes[begin..].iter().position(|b| *b == 0).unwrap(); + *cursor += length + 1; + &bytes[begin..begin + length] + } + assert_eq!(word(bytes, 0), 20_000_630, "OpenEXR magic"); + assert_eq!(word(bytes, 4), 2, "single-part scanline version, no feature flags"); + let mut cursor = 8; + let mut dimensions = None; + let mut channels = false; + let mut uncompressed = false; + let mut increasing = false; + while bytes[cursor] != 0 { + let name = string(bytes, &mut cursor); + let kind = string(bytes, &mut cursor); + let length = word(bytes, cursor) as usize; + cursor += 4; + let value = &bytes[cursor..cursor + length]; + cursor += length; + match name { + b"channels" => { + assert_eq!(kind, b"chlist"); + let mut at = 0; + for channel in [b"A", b"B", b"G", b"R"] { + assert_eq!(string(value, &mut at), channel); + assert_eq!(word(value, at), 2, "FLOAT channel type"); + assert_eq!(&value[at + 4..at + 8], &[0; 4]); + assert_eq!(word(value, at + 8), 1, "full horizontal sampling"); + assert_eq!(word(value, at + 12), 1, "full vertical sampling"); + at += 16; + } + assert_eq!(&value[at..], &[0], "exactly A/B/G/R"); + assert!(!channels); + channels = true; + } + b"dataWindow" => { + assert_eq!(kind, b"box2i"); + assert_eq!(value.len(), 16); + assert_eq!((word(value, 0), word(value, 4)), (0, 0)); + let (width, height) = (word(value, 8) + 1, word(value, 12) + 1); + assert!(width > 0 && height > 0); + assert!(dimensions.replace((width, height)).is_none()); + } + b"compression" => { + assert_eq!(kind, b"compression"); + assert_eq!(value, &[0]); + uncompressed = true; + } + b"lineOrder" => { + assert_eq!(kind, b"lineOrder"); + assert_eq!(value, &[0]); + increasing = true; + } + _ => {} + } + } + cursor += 1; + assert!(channels && uncompressed && increasing); + let (width, height) = dimensions.unwrap(); + let table = cursor; + cursor += height as usize * 8; + let mut pixels = ::image::Rgba32FImage::new(width, height); + for y in 0..height { + let at = table + y as usize * 8; + assert_eq!(u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()), cursor as u64); + assert_eq!(word(bytes, cursor), y); + assert_eq!(word(bytes, cursor + 4), width * 16); + cursor += 8; + for (plane, channel) in [3, 2, 1, 0].into_iter().enumerate() { + for x in 0..width { + let at = cursor + (plane * width as usize + x as usize) * 4; + pixels.get_pixel_mut(x, y).0[channel] = f32::from_bits(word(bytes, at)); + } + } + cursor += width as usize * 16; + } + assert_eq!(cursor, bytes.len(), "complete scanlines with no trailing payload"); + pixels +} + use super::*; use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; use crate::{ProductMesh, StandardView}; @@ -35,7 +123,7 @@ fn progressive_complete(mut task: ImageTask, quantum: usize) -> ProgressiveOutpu #[test] fn progressive_real_png_has_stable_prefixes_quanta_and_fresh_primary_samples() { let (previews, final_png, work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 1); - assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 4]); + assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6, 7]); let (other, other_final, other_work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 16_384); assert_eq!(other, previews); assert_eq!(other_final, final_png); @@ -75,7 +163,7 @@ fn progressive_coverage_keeps_backplate_outside_exposure_and_tone_mapping() { assert_eq!(::image::load_from_memory(&half).unwrap().to_rgba8().get_pixel(0, 0).0, [expected, expected, expected, 255]); } let (previews, _, _) = progressive_complete(progressive_fixture(5, 9, Some(true), 0.0), 1); - assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 4], "non-power-of-two target still has an exact final pass"); + assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4], "every complete nonfinal pass is published"); } #[test] @@ -134,6 +222,147 @@ fn progressive_film_and_resolve_share_cancellation_and_one_cumulative_work_budge } } +fn progressive_area_fixture(samples: u32, led: bool) -> ImageTask { + let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + let receiver = ProductMesh { + transmission: None, + name: "diffuse area receiver".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 0.0), Vec3::new(-20.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.6, 0.4), 0.0, 0.7, 1.5).unwrap()), + faces: Vec::new(), + }; + let mut options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 9 }), + lights: Some(Vec::new()), + shadows: true, + ..Default::default() + }; + let strip = job::led_strip::LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 4.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 8.0, + }; + if led { + strip.append_to(&mut options, 4).unwrap(); + } else { + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [4.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 8.0, + }]); + options.area_samples = Some(4); + } + options.seed = Some(73); + let bounds = receiver.mesh.bounds(); + let request = ImageRequest { + studio_weights: None, + environment: None, + textures: None, + integrator: job::Integrator::Raytrace, + raytrace: Some(options.clone()), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + }; + ImageTask::new(ProductScene { meshes: vec![receiver], bounds }, request, CancelToken::default(), options).unwrap() +} + +fn progressive_area_expected(task: &ImageTask, samples: u32) -> [u8; 4] { + let light = super::super::area::RectangleLight::new( + Vec3::new(0.0, 0.0, 10.0), + Vec3::new(4.0, 0.0, 0.0), + Vec3::new(0.0, -2.0, 0.0), + Vec3::new(1.0, 0.5, 0.25), + 8.0, + ) + .unwrap(); + let surface = task.scene.meshes[0].surface.unwrap(); + let mut sum = Vec3::ZERO; + for ordinal in 0..samples { + let [dx, dy] = progressive::variates(9, 0, ordinal, 0); + let (origin, direction) = task.request.camera.ray(dx, dy, 1.0, 1.0); + // This infinite receiver is z=0. Its closed-form hit does not use the BVH. + let point = origin + direction * (-origin.z / direction.z); + let key = area_sample_key(0, 0, 1, ordinal).unwrap(); + for index in 0..4 { + let emitter = light.sample(point, key, 0, index, 4, 73).unwrap().unwrap().position(); + let delta = emitter - point; + let distance_squared = delta.len2(); + let incoming = delta / distance_squared.sqrt(); + // A*cos(emitter)/(r²*N), independently of the image light cursor. + let incident = Vec3::new(1.0, 0.5, 0.25) * (8.0 * 8.0 * incoming.z / distance_squared / 4.0); + let brdf = surface.brdf(Vec3::Z, -direction, incoming).unwrap(); + sum += multiply(brdf, incident) * incoming.z; + } + } + let mean = sum / f64::from(samples); + [encode8(mean.x / (1.0 + mean.x)), encode8(mean.y / (1.0 + mean.y)), encode8(mean.z / (1.0 + mean.z)), 255] +} + +#[test] +fn progressive_area_and_led_pngs_match_numeric_means_prefixes_and_quanta() { + let mut rectangle = None; + for led in [false, true] { + let expected: Vec<_> = (1..=5).map(|samples| progressive_area_expected(&progressive_area_fixture(5, led), samples)).collect(); + let (previews, final_png, work) = progressive_complete(progressive_area_fixture(5, led), 1); + assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4]); + assert_eq!((previews.clone(), final_png.clone(), work), progressive_complete(progressive_area_fixture(5, led), 16_384)); + for (samples, checkpoint) in &previews { + let (_, prefix, _) = progressive_complete(progressive_area_fixture(*samples, led), 3); + assert_eq!(&prefix, checkpoint); + assert_eq!(::image::load_from_memory(checkpoint).unwrap().to_rgba8().get_pixel(0, 0).0, expected[(*samples - 1) as usize]); + } + assert_eq!(::image::load_from_memory(&final_png).unwrap().to_rgba8().get_pixel(0, 0).0, expected[4]); + if let Some(previous) = &rectangle { + assert_eq!(&(previews, final_png, work), previous, "a continuous LED uses exactly the same rectangular transport"); + } else { + rectangle = Some((previews, final_png, work)); + } + } +} + +#[test] +fn progressive_area_and_led_shadow_continuations_observe_cancel_and_cumulative_work() { + for led in [false, true] { + for cancel in [false, true] { + let mut task = progressive_area_fixture(3, led); + for _ in 0..100_000 { + if task.pending.as_ref().is_some_and(|pending| pending.area_shadow) { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(task.pending.as_ref().unwrap().area_shadow); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0, "an interrupted area integral cannot publish a pass"); + } + } +} + fn fixture(samples: u8, r: u8, left: Option) -> ImageTask { let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; camera.set_view(StandardView::Top); @@ -460,7 +689,7 @@ fn workstation_progressive_resolves_every_checkpoint_through_its_admitted_cap() let request = ImageRequest { raytrace: Some(options.clone()), ..fixed.request.clone() }; let task = ImageTask::new(fixed.scene.clone(), request, CancelToken::default(), options).unwrap(); let (previews, final_png, _) = progressive_complete(task, 16_384); - let expected: Vec<_> = (0..samples.ilog2()).map(|power| 1_u32 << power).collect(); + let expected: Vec<_> = (1..samples).collect(); assert_eq!(previews.iter().map(|(n, _)| *n).collect::>(), expected); for (_, png) in &previews { assert_eq!(::image::load_from_memory(png).unwrap().to_rgba8().dimensions(), (1, 1)); @@ -489,3 +718,5213 @@ fn area_light_points_include_spatial_and_film_sample_identity() { assert!(area_sample_key(41, 4, 4, 0).is_err()); assert!(area_sample_key(u64::MAX, 0, 4, 0).is_err()); } + +fn presentation_fixture(samples: Option, primary: u8, output: Option, exposure: f64) -> ImageTask { + let initial = fixture(primary, 1, Some(true)); + let mut options = initial.options.clone(); + options.reflections = None; + options.progressive = samples.map(|samples_per_pixel| job::CpuProgressiveOptions { samples_per_pixel, seed: 9 }); + options.output = output.map(Box::new); + options.exposure_ev = exposure; + options.emissions = Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Black half".into(), + color: [1.0, 0.5, 0.25], + strength: 9.0, + sides: job::EmissionSides::Both, + }]); + let request = ImageRequest { raytrace: Some(options.clone()), ..initial.request.clone() }; + ImageTask::new(initial.scene.clone(), request, CancelToken::default(), options).unwrap() +} +type PresentedOutput = (Vec<(u32, Vec)>, Vec, Option>, u64); +fn complete_presentation(mut task: ImageTask, units: usize) -> PresentedOutput { + let mut previews = Vec::new(); + for _ in 0..200_000 { + match task.step_with_previews(units).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.take_linear_exr().is_none(), "provisional images never expose a raw master"); + previews.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + 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()); + } + } + } + panic!("bounded CPU presentation did not finish"); +} +fn creative_output() -> job::OutputOptions { + job::OutputOptions { + tone_map: job::ToneMap::AcesFitted, + linear_exr: true, + finishing: job::finishing::Finishing { + rgb_gain: [1.3, 0.8, 1.1], + contrast: 1.2, + saturation: 0.7, + bloom: Some(job::bloom::Bloom { strength: 0.2, threshold: 0.5, radius: 1 }), + photographic: job::photographic::Photographic { grain: 0.03, seed: 42, ..Default::default() }, + ..Default::default() + }, + ..Default::default() + } +} + +#[test] +fn cpu_identity_output_and_raw_retention_preserve_original_f64_pngs() { + for (samples, primary) in [(None, 1), (None, 4), (Some(7), 1)] { + let original = complete_presentation(presentation_fixture(samples, primary, None, 1.5), 1); + for linear_exr in [false, true] { + let identity = job::OutputOptions { linear_exr, ..Default::default() }; + let actual = complete_presentation(presentation_fixture(samples, primary, Some(identity), 1.5), 1); + assert_eq!(actual.0, original.0, "even raw retention must preserve every original provisional PNG byte"); + assert_eq!(actual.1, original.1, "identity output must preserve the original f64 PNG exactly"); + assert_eq!(actual.2.is_some(), linear_exr); + if let Some(master) = actual.2 { + assert!(master.windows(b"SolidCraft native CPU raytrace".len()).any(|w| w == b"SolidCraft native CPU raytrace")); + } + } + } +} + +#[test] +fn cpu_shared_presentation_keeps_every_real_prefix_and_worker_quantum() { + let output = creative_output(); + let first = complete_presentation(presentation_fixture(Some(7), 1, Some(output), -1.0), 1); + assert_eq!(first.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6]); + assert_eq!(first, complete_presentation(presentation_fixture(Some(7), 1, Some(output), -1.0), 16_384)); + for (samples, png) in &first.0 { + let prefix = complete_presentation(presentation_fixture(Some(*samples), 1, Some(output), -1.0), 3); + assert_eq!(&prefix.1, png, "EXR work at a final target cannot change its shared presentation"); + } + let legacy = complete_presentation(presentation_fixture(Some(7), 1, None, -1.0), 1); + assert_ne!(first.1, legacy.1, "the selected presentation must affect the actual PNG"); +} + +#[test] +fn cpu_raw_master_keeps_hdr_and_coverage_before_every_presentation_operator() { + let identity = job::OutputOptions { linear_exr: true, ..Default::default() }; + let original = complete_presentation(presentation_fixture(Some(7), 1, Some(identity), -8.0), 1); + let mut creative = creative_output(); + creative.backdrop = Some(job::finishing::Backdrop::default()); + let changed = complete_presentation(presentation_fixture(Some(7), 1, Some(creative), 8.0), 1); + assert_eq!(original.2, changed.2, "raw radiance/coverage cannot contain exposure, bloom, backdrop, tone map or photographic effects"); + let master = original.2.unwrap(); + // The one-pixel uncompressed scanline ends in its canonical A,B,G,R float channels. + let tail = &master[master.len() - 16..]; + let channel = |at| f32::from_le_bytes(tail[at..at + 4].try_into().unwrap()); + let covered = (0..7).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count() as f64; + let alpha = (covered / 7.0) as f32; + assert_eq!(channel(0), alpha); + for (actual, scale) in [(channel(12), 1.0), (channel(8), 0.5), (channel(4), 0.25)] { + assert_eq!(actual, (covered / 7.0 * 9.0 * scale) as f32); + } + assert!(channel(12) > 1.0, "raw HDR radiance must survive display clipping"); + assert_ne!(original.1, changed.1); +} + +#[test] +fn cpu_output_stages_share_cancel_and_one_cumulative_work_ceiling() { + for stage in ["exr", "bloom", "display", "photographic", "png"] { + for cancel in [false, true] { + let mut output = creative_output(); + // The final target also exercises EXR; other stages remain reachable afterward. + output.linear_exr = true; + let mut task = presentation_fixture(Some(3), 1, Some(output), 0.0); + for _ in 0..200_000 { + if task.output.first().is_some_and(|output| output.stage_name() == stage) { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + assert_eq!(task.output.first().unwrap().stage_name(), stage); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + assert!(task.take_linear_exr().is_none(), "interrupted output cannot expose a final master"); + } + } +} + +fn cpu_lens_fixture(samples: u32, lens: Option) -> ImageTask { + let fixed = fixture(1, 1, Some(true)); + let mut options = fixed.options.clone(); + options.reflections = None; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 9 }); + options.lens = lens; + let mut request = ImageRequest { raytrace: Some(options.clone()), ..fixed.request.clone() }; + // At z=0 this perspective projection has the same eight-mm image span as + // the analytic half-plane fixture. Positive pupil radius changes transport only. + request.camera.fov = 2.0 * 0.4f64.atan(); + ImageTask::new(fixed.scene.clone(), request, CancelToken::default(), options).unwrap() +} + +#[test] +fn cpu_thin_lens_rays_match_rolled_axial_focus_and_uniform_area_pupil() { + let mut request = fixture(1, 1, None).request; + request.width = 8; + request.height = 6; + for (yaw, pitch, roll) in [(0.0, 0.0, 0.0), (-0.45, 0.5, 0.7)] { + request.camera = crate::Camera { target: Vec3::new(2.0, 3.0, 4.0), distance: 12.0, fov: 0.7, yaw, pitch, roll, ..Default::default() }; + let camera = request.camera; + let (right, up, back) = camera.basis(); + let lens = job::ThinLens { aperture_radius_mm: 0.4, focus_distance_mm: 9.0 }; + for (x, y) in [(0.25, 1.5), (4.0, 3.0), (7.8, 5.7)] { + let nx = x / f64::from(request.width) * 2.0 - 1.0; + let ny = 1.0 - y / f64::from(request.height) * 2.0; + let focal = camera.eye() - back * lens.focus_distance_mm + + (right * (nx * f64::from(request.width) / f64::from(request.height)) + up * ny) + * ((camera.fov * 0.5).tan() * lens.focus_distance_mm); + for pupil in [[0.0, 0.0], [0.25, 0.25], [0.81, 0.5]] { + let disk = (right * (std::f64::consts::TAU * pupil[1]).cos() + up * (std::f64::consts::TAU * pupil[1]).sin()) + * (lens.aperture_radius_mm * pupil[0].sqrt()); + let ray = lens_primary_ray(&request, x, y, (0.1, 100.0), lens, pupil).unwrap(); + for depth in [0.0, lens.focus_distance_mm * 0.5, lens.focus_distance_mm, lens.focus_distance_mm * 2.0] { + let start_depth = (ray.origin() - camera.eye()).dot(-back); + let hit = ray.origin() + ray.direction() * ((depth - start_depth) / ray.direction().dot(-back)); + let pinhole = camera.eye() + (focal - camera.eye()) * (depth / lens.focus_distance_mm); + let expected = pinhole + disk * (1.0 - depth / lens.focus_distance_mm); + assert!(hit.dist(expected) < 1e-10, "axial depth={depth}, pupil={pupil:?}: {hit:?} != {expected:?}"); + } + } + } + } +} + +#[test] +fn cpu_disabled_lens_preserves_fixed_and_every_progressive_png_byte_and_work_unit() { + for output in [None, Some(job::OutputOptions { linear_exr: true, ..Default::default() })] { + for (samples, primary) in [(None, 1), (None, 4), (None, 16), (Some(7), 1)] { + let original = presentation_fixture(samples, primary, output, 1.5); + let mut options = original.options.clone(); + options.lens = Some(job::ThinLens { aperture_radius_mm: 0.0, focus_distance_mm: 8.0 }); + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + let zero = ImageTask::new(original.scene.clone(), request, CancelToken::default(), options).unwrap(); + assert_eq!(zero.admission.estimated_total_bytes, original.admission.estimated_total_bytes, "a zero lens needs no extra buffer"); + assert_eq!(complete_presentation(original, 1), complete_presentation(zero, 1)); + } + } +} + +#[test] +fn cpu_thin_lens_image_has_numeric_defocus_stable_prefixes_and_no_exposure_factor() { + let radius = 4.0; + let focused = Some(job::ThinLens { aperture_radius_mm: radius, focus_distance_mm: 10.0 }); + let defocused = Some(job::ThinLens { aperture_radius_mm: radius, focus_distance_mm: 20.0 }); + let pinhole = progressive_complete(cpu_lens_fixture(64, None), 1); + let sharp = progressive_complete(cpu_lens_fixture(64, focused), 1); + assert_eq!((sharp.0, sharp.1), (pinhole.0, pinhole.1), "every pupil must meet the same focused surface without an aperture-area exposure factor"); + let actual = progressive_complete(cpu_lens_fixture(64, defocused), 1); + assert_eq!(actual, progressive_complete(cpu_lens_fixture(64, defocused), 16_384)); + for (samples, png) in &actual.0 { + assert_eq!(*png, progressive_complete(cpu_lens_fixture(*samples, defocused), 3).1); + } + let task = cpu_lens_fixture(64, defocused); + let camera = task.request.camera; + let (right, up, back) = camera.basis(); + let bounds = task.scene.meshes[0].mesh.bounds(); + let covered = (0..64) + .filter(|ordinal| { + let [x, y] = progressive::variates(9, 0, *ordinal, 0); + let [u, v] = progressive::variates(9, 0, *ordinal, 0x4c454e53); + let disk = (right * (std::f64::consts::TAU * v).cos() + up * (std::f64::consts::TAU * v).sin()) * (radius * u.sqrt()); + let point = camera.eye() - back * camera.distance + + (right * (2.0 * x - 1.0) + up * (1.0 - 2.0 * y)) * camera.half_height() + + disk * (1.0 - camera.distance / 20.0); + point.x >= bounds.min.x && point.x <= bounds.max.x && point.y >= bounds.min.y && point.y <= bounds.max.y + }) + .count(); + let expected = encode8(1.0 - covered as f64 / 64.0); + let rgba = ::image::load_from_memory(&actual.1).unwrap().to_rgba8(); + assert_eq!(rgba.get_pixel(0, 0).0, [expected, expected, expected, 255]); + assert_ne!(actual.1, progressive_complete(cpu_lens_fixture(64, None), 1).1, "physical defocus must change the actual image"); +} + +#[test] +fn cpu_lens_pupil_continuations_observe_cancel_and_one_cumulative_work_budget() { + for pupil_only in [true, false] { + for cancel in [false, true] { + let mut task = cpu_lens_fixture(7, Some(job::ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 20.0 })); + for _ in 0..100_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1, "pupil generation is a separate bounded continuation"); + if if pupil_only { task.pupil_sample.is_some() } else { task.pending.is_some() } { + break; + } + } + if pupil_only { + assert!(task.pupil_sample.is_some()); + assert!(task.pending.is_none(), "the pupil continuation yields before constructing the primary ray"); + } else { + assert!(task.pending.is_some(), "the real pupil ray must have been generated"); + assert!(!task.pending.as_ref().unwrap().repeatable_primary); + assert!(task.pupil_sample.is_none()); + } + 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.pixels.is_empty()); + assert!(task.take_linear_exr().is_none()); + } + } +} + +#[test] +fn cpu_lens_admission_keeps_the_whole_pupil_outside_certified_glass() { + let scene = dielectric::tests::scene(dielectric::tests::box_body(8.0)); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 4, seed: 9 }), + lens: Some(job::ThinLens { aperture_radius_mm: 1.99, focus_distance_mm: 10.0 }), + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.distance = 10.0; + request.camera.fov = 0.7; + admit(&scene, &request, &options).unwrap(); + for radius in [2.0, 2.01, 10.0] { + let options = RaytraceOptions { lens: Some(job::ThinLens { aperture_radius_mm: radius, focus_distance_mm: 10.0 }), ..options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..request.clone() }; + assert!(admit(&scene, &request, &options).unwrap_err().message.contains("aperture sphere")); + } +} + +#[test] +fn cpu_lens_extreme_valid_physical_settings_refuse_before_ray_transport() { + let mut task = cpu_lens_fixture(4, None); + task.options.lens = Some(job::ThinLens { aperture_radius_mm: 1e7, focus_distance_mm: 1e-6 }); + task.request.raytrace = Some(task.options.clone()); + let error = admit(&task.scene, &task.request, &task.options).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert!(error.message.contains("bounded ray")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); +} + +fn alpha_fixture(samples: Option, primary: u8, transparent: bool, output: Option, exposure: f64) -> ImageTask { + let original = presentation_fixture(samples, primary, output, exposure); + let request = ImageRequest { transparent_background: transparent, ..original.request.clone() }; + ImageTask::new(original.scene, request, original.cancel, original.options).unwrap() +} +fn alpha_pixel(png: &[u8]) -> [u8; 4] { + ::image::load_from_memory(png).unwrap().to_rgba8().get_pixel(0, 0).0 +} +fn alpha_encoded_work(output: &PresentedOutput) -> u64 { + output.0.iter().map(|(_, png)| png.len() as u64).sum::() + output.1.len() as u64 +} + +#[test] +fn cpu_transparent_png_uses_analytic_straight_rgb_and_fixed_or_film_coverage() { + for primary in [4, 16] { + for exposure in [-2.0, 0.0, 1.5] { + let clear = complete_presentation(alpha_fixture(None, primary, true, None, exposure), 1); + let opaque = complete_presentation(alpha_fixture(None, primary, false, None, exposure), 1); + let exposed = 2.0f64.powf(exposure); + let rgb = [9.0, 4.5, 2.25].map(|linear| encode8(linear * exposed / (1.0 + linear * exposed))); + assert_eq!( + alpha_pixel(&clear.1), + [rgb[0], rgb[1], rgb[2], 128], + "straight RGB is the covered scene mean, never multiplied by edge alpha" + ); + assert_eq!(clear.3, opaque.3, "a background flag adds no transport or work debit"); + assert_ne!(clear.1, opaque.1); + } + } + let complete = complete_presentation(alpha_fixture(Some(16), 1, true, None, 1.5), 1); + let rgb = [9.0, 4.5, 2.25].map(|linear| { + let value = linear * 2.0f64.powf(1.5); + encode8(value / (1.0 + value)) + }); + for (samples, png) in complete.0.iter().chain(std::iter::once(&(16, complete.1.clone()))) { + let covered = (0..*samples).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let alpha = (covered as f64 / f64::from(*samples) * 255.0).round() as u8; + assert_eq!(alpha_pixel(png), if alpha == 0 { [0; 4] } else { [rgb[0], rgb[1], rgb[2], alpha] }); + } + for primary in [1, 4, 16] { + let original = fixture(primary, 1, None); + let request = ImageRequest { transparent_background: true, ..original.request.clone() }; + let task = ImageTask::new(original.scene, request, original.cancel, original.options).unwrap(); + assert_eq!(alpha_pixel(&progressive_complete(task, 1).1), [0; 4]); + } + assert!(composite_spatial_alpha(Vec3::X, 0, 4, [1, 2, 3], 0.0, true).is_err()); + assert!(composite_spatial_alpha(Vec3::ZERO, 5, 4, [1, 2, 3], 0.0, true).is_err()); + let empty = fixture(1, 1, None); + let options = RaytraceOptions { + output: Some(Box::new(job::OutputOptions { + finishing: job::finishing::Finishing { contrast: 0.5, ..Default::default() }, + ..Default::default() + })), + ..empty.options + }; + let request = ImageRequest { transparent_background: true, raytrace: Some(options.clone()), ..empty.request }; + let clear = ImageTask::new(empty.scene, request, empty.cancel, options).unwrap(); + assert_eq!( + alpha_pixel(&complete_presentation(clear, 1).1), + [0; 4], + "allowed colour finishing cannot leave lifted-black RGB in a zero-alpha pixel" + ); +} + +#[test] +fn cpu_alpha_keeps_opaque_f64_bytes_work_and_all_raw_exr_bits() { + let identity = job::OutputOptions { linear_exr: true, ..Default::default() }; + for (samples, primary) in [(None, 1), (None, 4), (None, 16), (Some(7), 1)] { + let original = complete_presentation(presentation_fixture(samples, primary, Some(identity), 1.5), 1); + let false_flag = complete_presentation(alpha_fixture(samples, primary, false, Some(identity), 1.5), 1); + assert_eq!(false_flag, original, "false stays exactly on the legacy f64 PNG/master/work path"); + let source = alpha_fixture(samples, primary, false, Some(identity), 1.5); + let transparent = alpha_fixture(samples, primary, true, Some(identity), 1.5); + assert_eq!( + source.admission.estimated_total_bytes, transparent.admission.estimated_total_bytes, + "alpha uses existing coverage/RGBA storage only" + ); + let alpha = complete_presentation(transparent, 1); + assert_eq!(alpha.2, original.2, "the scene-linear premultiplied raw master is independent of display alpha choice"); + assert_eq!( + alpha.3 - alpha_encoded_work(&alpha), + original.3 - alpha_encoded_work(&original), + "only actual encoded-byte digest work can differ with PNG content" + ); + let no_master = complete_presentation(alpha_fixture(samples, primary, true, None, 1.5), 1); + assert_eq!((alpha.0, alpha.1), (no_master.0, no_master.1), "raw retention cannot change any straight-alpha PNG prefix"); + } +} + +#[test] +fn cpu_alpha_shared_finishing_preserves_prefixes_quanta_and_raw_values() { + let output = job::OutputOptions { + tone_map: job::ToneMap::AcesFitted, + finishing: job::finishing::Finishing { rgb_gain: [1.2, 0.8, 1.1], ..Default::default() }, + linear_exr: true, + ..Default::default() + }; + let actual = complete_presentation(alpha_fixture(Some(7), 1, true, Some(output), -1.0), 1); + assert_eq!(actual, complete_presentation(alpha_fixture(Some(7), 1, true, Some(output), -1.0), 16384)); + for (samples, png) in &actual.0 { + assert_eq!(*png, complete_presentation(alpha_fixture(Some(*samples), 1, true, Some(output), -1.0), 3).1); + } + let opaque = complete_presentation(alpha_fixture(Some(7), 1, false, Some(output), -1.0), 1); + assert_eq!(actual.2, opaque.2); + assert_eq!( + actual.3 - alpha_encoded_work(&actual), + opaque.3 - alpha_encoded_work(&opaque), + "alpha adds no film, conversion or presentation work beyond actual PNG byte hashing" + ); + let coverage = (0..7).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let rgb = std::array::from_fn::<_, 3, _>(|i| { + let x: f64 = [9.0, 4.5, 2.25][i] * 0.5 * [1.2, 0.8, 1.1][i]; + encode8(((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)).clamp(0.0, 1.0)) + }); + assert_eq!(alpha_pixel(&actual.1), [rgb[0], rgb[1], rgb[2], (coverage as f64 / 7.0 * 255.0).round() as u8]); +} + +#[test] +fn cpu_alpha_presentation_rounds_six_sample_half_ties_from_exact_hit_counts() { + let covered = (0..6).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + assert_eq!(covered, 5, "the fixture must exercise the exact 5/6 alpha half tie"); + let baseline = + complete_presentation(alpha_fixture(Some(6), 1, true, Some(job::OutputOptions { linear_exr: true, ..Default::default() }), 1.5), 1); + for tone_map in [job::ToneMap::Reinhard, job::ToneMap::AcesFitted] { + for denoise in [false, true] { + for creative in [false, true] { + let mut finishing = job::finishing::Finishing::default(); + if creative { + finishing.rgb_gain = [1.2, 0.8, 1.1]; + finishing.contrast = 1.1; + finishing.saturation = 0.7; + finishing.vignette = 0.2; + finishing.looks.push(job::looks::LookLayer { kind: job::looks::LookKind::Warm, strength: 0.4, enabled: true }).unwrap(); + } + let make = |samples, retain| { + let output = job::OutputOptions { tone_map, finishing, linear_exr: retain, ..Default::default() }; + let original = alpha_fixture(Some(samples), 1, true, Some(output), 1.5); + let options = RaytraceOptions { denoise, ..original.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + ImageTask::new(original.scene, request, original.cancel, options).unwrap() + }; + let actual = complete_presentation(make(6, true), 1); + assert_eq!(actual, complete_presentation(make(6, true), 16384)); + assert_eq!(alpha_pixel(&actual.1)[3], 213, "5/6 must round upwards at exactly 212.5"); + for (samples, png) in actual.0.iter().chain(std::iter::once(&(6, actual.1.clone()))) { + let hits = (0..*samples).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let expected = (hits as f64 / f64::from(*samples) * 255.0).round() as u8; + assert_eq!(alpha_pixel(png)[3], expected, "sample{samples}, {tone_map:?}, denoise={denoise}, creative={creative}"); + assert_eq!(*png, complete_presentation(make(*samples, true), 3).1); + } + assert_eq!(actual.2, baseline.2, "presentation and denoising must preserve every raw EXR bit"); + let no_master = complete_presentation(make(6, false), 1); + assert_eq!((actual.0, actual.1), (no_master.0, no_master.1), "raw retention must not change PNG coverage"); + } + } + } +} + +#[test] +fn cpu_alpha_retains_opaque_only_effect_guards_and_cancellable_completion() { + let original = alpha_fixture(Some(3), 1, true, None, 0.0); + let creative = creative_output(); + for output in [ + job::OutputOptions { backdrop: Some(Default::default()), ..Default::default() }, + job::OutputOptions { finishing: job::finishing::Finishing { bloom: creative.finishing.bloom, ..Default::default() }, ..Default::default() }, + job::OutputOptions { + finishing: job::finishing::Finishing { photographic: creative.finishing.photographic, ..Default::default() }, + ..Default::default() + }, + ] { + let options = RaytraceOptions { output: Some(Box::new(output)), ..original.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + assert!(admit(&original.scene, &request, &options).is_err(), "alpha never silently strips opaque photographic/bloom/backdrop intent"); + } + for stage in ["exr", "display", "png"] { + for cancel in [false, true] { + let output = job::OutputOptions { tone_map: job::ToneMap::AcesFitted, linear_exr: true, ..Default::default() }; + let mut task = alpha_fixture(Some(3), 1, true, Some(output), 0.0); + for _ in 0..200000 { + if task.output.first().is_some_and(|output| output.stage_name() == stage) { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + assert_eq!(task.output.first().unwrap().stage_name(), stage); + 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!(!task.done); + assert!(task.take_linear_exr().is_none()); + } + } +} + +#[test] +fn cpu_disabled_denoise_preserves_every_png_exr_work_unit_and_buffer_admission() { + for output in [None, Some(job::OutputOptions { linear_exr: true, ..Default::default() })] { + for samples in [None, Some(5)] { + let original = presentation_fixture(samples, 1, output, 1.5); + let options: RaytraceOptions = serde_json::from_value(serde_json::json!({"denoise":false})).unwrap(); + assert!(!options.denoise); + assert!(serde_json::to_value(options).unwrap().get("denoise").is_none()); + let mut options = original.options.clone(); + options.denoise = false; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + let explicit = ImageTask::new(original.scene.clone(), request, CancelToken::default(), options).unwrap(); + assert_eq!(original.denoise.capacity(), 0); + assert_eq!(explicit.denoise.capacity(), 0); + assert_eq!(original.admission.estimated_total_bytes, explicit.admission.estimated_total_bytes); + assert_eq!(complete_presentation(original, 1), complete_presentation(explicit, 16384)); + } + } +} + +#[test] +fn cpu_alpha_and_denoise_compose_without_changing_matte_prefixes_or_raw_masters() { + let output = job::OutputOptions { linear_exr: true, ..Default::default() }; + let composed = |samples, transparent, denoise| { + let original = alpha_fixture(Some(samples), 1, transparent, Some(output), 1.5); + let options = RaytraceOptions { denoise, ..original.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + ImageTask::new(original.scene, request, original.cancel, options).unwrap() + }; + let actual = complete_presentation(composed(7, true, true), 1); + assert_eq!(actual, complete_presentation(composed(7, true, true), 16384)); + assert_eq!(actual.0.iter().map(|p| p.0).collect::>(), [1, 2, 3, 4, 5, 6]); + let rgb = [9.0, 4.5, 2.25].map(|radiance| { + let exposed = radiance * 2.0f64.powf(1.5); + encode8(exposed / (1.0 + exposed)) + }); + for (samples, png) in actual.0.iter().chain(std::iter::once(&(7, actual.1.clone()))) { + let covered = (0..*samples).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let alpha = (covered as f64 / f64::from(*samples) * 255.0).round() as u8; + assert_eq!(alpha_pixel(png), if alpha == 0 { [0; 4] } else { [rgb[0], rgb[1], rgb[2], alpha] }); + assert_eq!(*png, complete_presentation(composed(*samples, true, true), 3).1); + } + let unfiltered = complete_presentation(composed(7, true, false), 1); + let opaque = complete_presentation(composed(7, false, true), 1); + assert_eq!(actual.2, unfiltered.2, "denoising cannot enter the premultiplied raw companion"); + assert_eq!(actual.2, opaque.2, "PNG alpha choice cannot enter the premultiplied raw companion"); + assert_eq!((actual.0, actual.1), (unfiltered.0, unfiltered.1), "partial-coverage/emitter bypass retains the analytical straight matte"); + let source = composed(7, true, true); + let creative = creative_output(); + for incompatible in [ + job::OutputOptions { backdrop: Some(Default::default()), ..output }, + job::OutputOptions { finishing: job::finishing::Finishing { bloom: creative.finishing.bloom, ..Default::default() }, ..output }, + job::OutputOptions { finishing: job::finishing::Finishing { photographic: creative.finishing.photographic, ..Default::default() }, ..output }, + ] { + let options = RaytraceOptions { output: Some(Box::new(incompatible)), ..source.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + assert!(admit(&source.scene, &request, &options).is_err(), "the denoiser cannot erase an alpha-incompatible authored effect"); + } +} + +fn path_fixture(samples: u32, depth: u8, ceiling: bool) -> ImageTask { + let original = fixture(1, 1, Some(true)); + let quad = |z: f64, down: bool| Mesh { + positions: vec![Vec3::new(-1e6, -1e6, z), Vec3::new(1e6, -1e6, z), Vec3::new(1e6, 1e6, z), Vec3::new(-1e6, 1e6, z)], + normals: vec![if down { -Vec3::Z } else { Vec3::Z }; 4], + triangles: if down { vec![[0, 2, 1], [0, 3, 2]] } else { vec![[0, 1, 2], [0, 2, 3]] }, + tri_face: vec![0; 2], + ..Default::default() + }; + let mut body = original.scene.meshes[0].clone(); + body.mesh = Arc::new(quad(0.0, false)); + body.surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 1.0, 1.0).unwrap()); + let mut meshes = vec![body]; + if ceiling { + let mut emitter = meshes[0].clone(); + emitter.name = "Red ceiling".into(); + // A real camera aperture keeps the emitter out of the primary path even + // when the producer starts orthographic rays before the complete bounds. + // Four downward-facing quads surround the 1x1 mm opening at z20. + let mut ceiling = Mesh::default(); + for [x0, x1, y0, y1] in [[-1e6, -0.5, -1e6, 1e6], [0.5, 1e6, -1e6, 1e6], [-0.5, 0.5, -1e6, -0.5], [-0.5, 0.5, 0.5, 1e6]] { + let base = ceiling.positions.len() as u32; + ceiling.positions.extend([Vec3::new(x0, y0, 20.0), Vec3::new(x1, y0, 20.0), Vec3::new(x1, y1, 20.0), Vec3::new(x0, y1, 20.0)]); + ceiling.normals.extend([-Vec3::Z; 4]); + ceiling.triangles.extend([[base, base + 2, base + 1], [base, base + 3, base + 2]]); + ceiling.tri_face.extend([0; 2]); + } + emitter.mesh = Arc::new(ceiling); + emitter.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap()); + meshes.push(emitter); + } + let scene = ProductScene { bounds: meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())), meshes }; + let options = RaytraceOptions { + path: Some(job::CpuPathOptions { max_depth: depth }), + budget: job::CpuBudget::Studio, + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 9 }), + shadows: true, + lights: Some(vec![]), + environment: (!ceiling).then_some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + emissions: ceiling.then_some(vec![job::SurfaceEmission { + body_index: 1, + body: "Red ceiling".into(), + color: [1.0, 0.0, 0.0], + strength: 2.0, + sides: job::EmissionSides::Both, + }]), + ..Default::default() + }; + // This fixture's independent GGX-mixture oracles assume exactly normal view. + // StandardView::Top deliberately stops 1e-6 rad short of the pole, which + // changes reflected proposals and their MIS density at depth >= 2. + // Its 0.8x0.8 mm orthographic footprint fits inside the physical ceiling + // aperture. No private clipping override or modified producer is needed. + let camera = crate::Camera { distance: 1.0, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, ..original.request.camera }; + assert!((camera.ray(0.5, 0.5, 1.0, 1.0).1 + Vec3::Z).len() < 1e-15, "analytical normal-view fixture"); + let request = ImageRequest { camera, raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +fn path_mean(mut task: ImageTask) -> ([f64; 3], u64) { + // For a uniform one-pixel film, each completed pass is exactly one + // successful sample commit. Read that cursor, never an unpublished pixel. + assert_eq!((task.request.width, task.request.height), (1, 1)); + assert!(task.options.adaptive.is_none()); + let target = task.options.progressive.unwrap().samples_per_pixel; + for _ in 0..2_000_000 { + if task.progressive.as_ref().is_some_and(|p| p.film.samples() == target) { + let (mean, covered, samples) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!(u32::from(samples), target); + assert_eq!(covered, samples); + return (mean, task.work.used()); + } + let path_step = task.bvh.is_some() + && task.progressive.as_ref().is_some_and(|p| p.film.ready() && !p.resolving) + && task.pixel == 0 + && task.output.is_empty() + && task.encoder.is_none(); + let before = task.work.used(); + let before_count = path_step.then(|| task.progressive.as_ref().unwrap().film.samples()); + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + if path_step { + let used = task.work.used() - before; + if task.options.path.is_some() { + assert!(used <= 1, "each real path continuation consumes at most one unit"); + } else { + // Legacy pixel_one can finish its charged shade and then call + // finish_sample's charged film.add in this same continuation. + // The one-operation GI state machine does not use that route. + assert!(used <= 2, "legacy transport has at most shade plus one sample commit"); + if used == 2 { + assert_eq!(task.pixel, 1, "the extra legacy unit commits exactly pixel0"); + assert!(task.pending.is_none(), "a committed legacy sample drains its pending path"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), before_count.unwrap() + 1); + } + } + } + } + panic!("bounded path film did not complete"); +} +fn independent_lambert_scatter(ordinal: u32) -> (f64, f64) { + let [component, u] = progressive::variates(9, 0, ordinal, 0x5041_5448_3000); + let cosine = if component < 0.5 { (1.0 - u).sqrt() } else { 1.0 - 2.0 * u }; + if cosine <= 0.0 { + return (0.0, 0.0); + } + let pdf = 0.5 * cosine / std::f64::consts::PI + 0.5 / (4.0 * std::f64::consts::PI); + (cosine, pdf) +} +#[test] +fn cpu_path_real_furnace_and_colored_bounce_match_independent_per_ordinal_estimators() { + use std::f64::consts::PI; + let samples = 1024; + for depth in [1, 2] { + let mut expected = 0.0; + for ordinal in 0..samples { + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000); + let z = 1.0 - 2.0 * u; + if z > 0.0 { + let light_pdf = 1.0 / (4.0 * PI); + let bsdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + let weight = if depth == 1 { 1.0 } else { light_pdf * light_pdf / (light_pdf * light_pdf + bsdf * bsdf) }; + expected += 2.0 * z * weight; + } + if depth == 2 { + let (cosine, pdf) = independent_lambert_scatter(ordinal); + if pdf > 0.0 { + let light_pdf = 1.0 / (4.0 * PI); + expected += 0.5 * cosine / (PI * pdf) * (pdf * pdf / (pdf * pdf + light_pdf * light_pdf)); + } + } + } + expected /= f64::from(samples); + let (actual, _) = path_mean(path_fixture(samples, depth, false)); + for value in actual { + assert!((value - expected).abs() < 1e-11, "depth{depth}: {value} vs independent estimator{expected}"); + } + assert!((expected - 0.5).abs() < 0.1, "Lambert furnace expected0.5; fixed-seed bounded estimate{expected}"); + } + let receiver = |depth| { + let mut task = path_fixture(samples, depth, true); + for _ in 0..100_000 { + if task.bvh.is_some() { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + let bvh = task.bvh.as_ref().expect("actual colored-bounce BVH must be ready before lighting"); + let prepared = PreparedScene { bvh, primitives: &task.looks, source: &task.scene }; + // Read-only diagnostics use a separate budget: neither film ordinals nor + // the producer's cumulative work are consumed by these hit assertions. + let mut work = WorkBudget::new(100_000).unwrap(); + let mut secondary_hits = 0; + for ordinal in 0..samples { + let [dx, dy] = progressive::variates(9, 0, ordinal, 0); + let ray = primary_ray(&task.request, dx, dy, task.clip).unwrap(); + let aperture = ray.origin() + ray.direction() * ((20.0 - ray.origin().z) / ray.direction().z); + assert!(aperture.x.abs() < 0.5 && aperture.y.abs() < 0.5, "primary must pass through the real ceiling opening"); + let hit = bvh.closest_hit(&ray, &mut work, &task.cancel).unwrap().expect("camera must see the receiver"); + let hit = prepared.resolve_hit(ray, hit).unwrap(); + assert_eq!(hit.body_index, 0, "primary must see the receiver, never its red ceiling"); + assert_eq!(hit.body_name, "Black half"); + assert!(hit.front_face); + assert_eq!(hit.geometric_normal, Vec3::Z); + assert_eq!(hit.shading_normal, Vec3::Z); + assert_eq!(hit.position.z, 0.0); + let [component, x] = progressive::variates(9, 0, ordinal, 0x5041_5448_3000); + let [y, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_3001); + let secondary = + super::super::indirect::sample(hit.surface, hit.shading_normal, hit.oriented_geometric_normal(), -ray.direction(), [component, x, y]) + .unwrap(); + assert_eq!(secondary.is_some(), independent_lambert_scatter(ordinal).1 > 0.0, "the fixed oracle retains every null proposal"); + if let Some(secondary) = secondary { + let ray = hit.spawn(secondary.direction).unwrap(); + let second = bvh + .closest_hit(&ray, &mut work, &task.cancel) + .unwrap() + .expect("every accepted secondary must see the red ceiling outside its opening"); + let second = prepared.resolve_hit(ray, second).unwrap(); + assert_eq!(second.body_index, 1); + assert_eq!(second.body_name, "Red ceiling"); + assert!(second.front_face); + assert_eq!(second.geometric_normal, -Vec3::Z); + assert_eq!(second.shading_normal, -Vec3::Z); + assert!(second.vertices.iter().all(|vertex| vertex.z == 20.0), "the secondary hit belongs to the exact ceiling plane"); + assert!(second.position.x.abs() > 0.5 || second.position.y.abs() > 0.5); + secondary_hits += 1; + } + } + assert_eq!(secondary_hits, 771, "the fixed seed exercises the complete accepted continuation set without retries"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0, "no lighting sample was consumed by preparation or diagnostics"); + assert!(task.options.environment.is_none()); + assert!(task.options.lights.as_ref().unwrap().is_empty()); + assert!(task.options.emissions.as_ref().unwrap().iter().all(|emitter| emitter.body_index != 0)); + task + }; + let direct = path_mean(receiver(1)).0; + assert_eq!(direct, [0.0; 3], "no direct source illuminates the receiver"); + let indirect = path_mean(receiver(2)).0; + let expected = (0..samples) + .map(|ordinal| { + let (cosine, pdf) = independent_lambert_scatter(ordinal); + if pdf == 0.0 { 0.0 } else { cosine / (PI * pdf) } + }) + .sum::() + / f64::from(samples); + assert!((indirect[0] - expected).abs() < 1e-11, "actual neighbor emission must travel through diffuse continuation"); + assert_eq!(indirect[1..], [0.0, 0.0]); + assert!((expected - 1.0).abs() < 0.12); +} +#[test] +fn cpu_path_real_prefixes_quanta_admission_and_legacy_omission_are_stable() { + let output = job::OutputOptions { linear_exr: true, ..Default::default() }; + let make = |samples| { + let original = path_fixture(samples, 3, false); + let options = RaytraceOptions { output: Some(Box::new(output)), ..original.options }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, original.cancel, options).unwrap() + }; + let actual = complete_presentation(make(7), 1); + assert_eq!(actual, complete_presentation(make(7), 16384)); + for (samples, png) in &actual.0 { + assert_eq!(*png, complete_presentation(make(*samples), 3).1); + } + assert!(actual.2.is_some()); + let task = make(3); + assert_eq!(task.path.capacity(), 1); + let options = RaytraceOptions { path: None, ..task.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..task.request.clone() }; + let old = ImageTask::new(task.scene.clone(), request, CancelToken::default(), options).unwrap(); + assert_eq!(old.path.capacity(), 0); + assert_eq!(task.admission.estimated_total_bytes - old.admission.estimated_total_bytes, std::mem::size_of::() as u64); + let omitted: RaytraceOptions = serde_json::from_str("{}").unwrap(); + assert!(omitted.path.is_none()); + assert!(serde_json::to_value(&omitted).unwrap().get("path").is_none()); + assert_eq!(complete_presentation(old, 1), { + let mut wire = serde_json::to_value(&task.options).unwrap(); + wire.as_object_mut().unwrap().remove("path"); + let options: RaytraceOptions = serde_json::from_value(wire).unwrap(); + let request = ImageRequest { raytrace: Some(options.clone()), ..task.request }; + complete_presentation(ImageTask::new(task.scene, request, CancelToken::default(), options).unwrap(), 16384) + }); +} +#[test] +fn cpu_path_cancellation_and_exhaustion_never_commit_an_incomplete_camera_path() { + for stage in [ + "new", + "trace", + "emitters", + "resolve", + "effects", + "emission", + "directional", + "punctual", + "area", + "environment", + "shadow", + "scatter", + "commit", + ] { + for cancel in [false, true] { + let mut task = path_fixture(7, 3, false); + for _ in 0..200_000 { + if task.bvh.is_some() && task.path.first().is_some_and(|p| p.stage_name() == stage) { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + assert_eq!(task.path.first().unwrap().stage_name(), stage); + let before = task.work.used(); + let samples = task.progressive.as_ref().unwrap().film.samples(); + 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(), samples); + assert!(task.take_linear_exr().is_none()); + assert!(!task.done); + } + } +} + +#[test] +fn cpu_path_real_rectangular_emitter_and_blocker_have_the_analytic_lambert_mean() { + let expected = 0.5 * 4.0 / 5.0_f64.sqrt() * (1.0 / 5.0_f64.sqrt()).atan() / std::f64::consts::PI; + for direct_samples in [1, 4, 16] { + // z=2 is the exact emitter endpoint: opaque geometry wins BSDF + // distance ties, so direct visibility must include that endpoint too. + for blocker_height in [None, Some(1.0), Some(2.0)] { + let original = path_fixture(1024, 2, false); + let mut scene = original.scene; + if let Some(height) = blocker_height { + let mut occluder = scene.meshes[0].clone(); + occluder.name = "Black blocker".into(); + let mut mesh = (*occluder.mesh).clone(); + for p in &mut mesh.positions { + p.z = height; + } + occluder.mesh = Arc::new(mesh); + occluder.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap()); + scene.meshes.push(occluder); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + } + let options = RaytraceOptions { + environment: None, + area_lights: Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 2.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }]), + area_samples: Some(direct_samples), + seed: Some(81), + ..original.options + }; + let camera = crate::Camera { distance: 0.1, fov: 0.001, ..original.request.camera }; + let request = ImageRequest { camera, raytrace: Some(options.clone()), ..original.request }; + let (actual, _) = path_mean(ImageTask::new(scene, request, CancelToken::default(), options).unwrap()); + if blocker_height.is_some() { + assert_eq!(actual, [0.0; 3], "black geometry at {blocker_height:?} blocks both strategies, including endpoint ties"); + } else { + for channel in actual { + assert!((channel - expected).abs() < 0.02, "N={direct_samples}, real rectangle MIS {channel}, analytic {expected}"); + } + } + } + } +} +#[test] +fn cpu_path_refuses_mixed_transport_instead_of_erasing_selected_optical_data() { + let original = path_fixture(3, 2, false); + let reflection = + ReflectionOptions { bodies: vec![ReflectionBody { body: "Black half".into(), mode: ReflectionMode::Mirror }], samples: 1, max_bounces: 2 }; + let options = RaytraceOptions { reflections: Some(reflection.clone()), ..original.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + assert!(admit(&original.scene, &request, &options).unwrap_err().message.contains("selected reflection")); + assert_eq!(options.reflections, Some(reflection)); + for depth in [0, 17] { + assert!(RaytraceOptions { path: Some(job::CpuPathOptions { max_depth: depth }), ..original.options.clone() }.validate().is_err()); + } + assert!(RaytraceOptions { progressive: None, ..original.options.clone() }.validate().unwrap_err().message.contains("progressive")); + assert!(RaytraceOptions { shadows: false, ..original.options.clone() }.validate().unwrap_err().message.contains("shadows")); +} + +#[test] +fn cpu_path_overlapping_coplanar_emitters_refuse_without_mutating_authored_rows() { + let original = path_fixture(3, 2, false); + let first = job::RectangleLightOptions { + center_mm: [0.0, 0.0, 2.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }; + let rows: Vec<_> = (0..5).map(|index| job::RectangleLightOptions { center_mm: [f64::from(index) * 3.0, 0.0, 2.0], ..first.clone() }).collect(); + let options = RaytraceOptions { area_lights: Some(rows.clone()), ..original.options.clone() }; + let error = options.validate().unwrap_err(); + assert_eq!(error.code, job::ErrorCode::InvalidRequest); + assert!(error.message.contains("at most four rectangle lights"), "{}", error.message); + assert_eq!(options.area_lights, Some(rows), "count refusal retains every authored source"); + for center in [[0.0, 0.0, 2.0], [1.0, 0.0, 2.0]] { + let second = job::RectangleLightOptions { center_mm: center, ..first.clone() }; + let rows = vec![first.clone(), second]; + let options = RaytraceOptions { area_lights: Some(rows.clone()), ..original.options.clone() }; + let error = options.validate().unwrap_err(); + assert!(error.message.contains("overlapping")); + assert_eq!(options.area_lights, Some(rows), "refusal retains both authored sources"); + } + for center in [[2.0, 0.0, 2.0], [3.0, 0.0, 2.0], [0.0, 0.0, 3.0]] { + let options = RaytraceOptions { + area_lights: Some(vec![first.clone(), job::RectangleLightOptions { center_mm: center, ..first.clone() }]), + ..original.options.clone() + }; + assert!(options.validate().is_ok(), "disjoint or edge-adjacent supports remain valid"); + } + let opposite = job::RectangleLightOptions { edge_v_mm: [0.0, 2.0, 0.0], ..first.clone() }; + assert!( + RaytraceOptions { area_lights: Some(vec![first, opposite]), ..original.options }.validate().is_ok(), + "opposite one-sided supports illuminate disjoint hemispheres" + ); +} + +#[test] +fn cpu_path_real_hdr_source_counts_match_independent_per_ordinal_mis_and_texel_lookup() { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + use std::f64::consts::{PI, TAU}; + // Deliberately nonconstant RGBE cells: the reference selects a texel from the + // physical direction independently of Environment::sample/radiance/PDF. + let texels: [[u8; 4]; 8] = [ + [128, 32, 16, 129], + [16, 128, 32, 129], + [32, 16, 128, 129], + [64, 96, 128, 129], + [96, 64, 32, 129], + [32, 96, 64, 129], + [64, 32, 96, 129], + [128, 64, 96, 129], + ]; + let radiance = |direction: Vec3| { + let phi = direction.y.atan2(direction.x).rem_euclid(TAU); + let x = ((phi / TAU * 4.0) as usize).min(3); + let y = ((direction.z.clamp(-1.0, 1.0).acos() / PI * 2.0) as usize).min(1); + let pixel = texels[y * 4 + x]; + Vec3::new(f64::from(pixel[0]), f64::from(pixel[1]), f64::from(pixel[2])) / 128.0 + }; + let samples = 128; + for source_count in [1, 4, 16, 64] { + let side = match source_count { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + for depth in [1, 2] { + let mut expected = Vec3::ZERO; + for ordinal in 0..samples { + for source_sample in 0..source_count { + let [dx, dy] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000 + u64::from(source_sample)); + let u = ((f64::from(source_sample / side) + dx) / f64::from(side)).max(0.0_f64.next_up()).min(1.0_f64.next_down()); + let v = ((f64::from(source_sample % side) + dy) / f64::from(side)).max(0.0_f64.next_up()).min(1.0_f64.next_down()); + let z = 1.0 - 2.0 * u; + if z > 0.0 { + let phi = TAU * v; + let radius = ((1.0 - z) * (1.0 + z)).sqrt(); + let direction = Vec3::new(radius * phi.cos(), radius * phi.sin(), z); + let source_pdf = f64::from(source_count) / (4.0 * PI); + let bsdf_pdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + let weight = if depth == 1 { 1.0 } else { source_pdf * source_pdf / (source_pdf * source_pdf + bsdf_pdf * bsdf_pdf) }; + expected += radiance(direction) * (2.0 * z * weight / f64::from(source_count)); + } + } + if depth == 2 { + let (z, pdf) = independent_lambert_scatter(ordinal); + if pdf > 0.0 { + let [angle, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_3001); + let phi = TAU * angle; + let radius = (1.0 - z * z).sqrt(); + let direction = Vec3::new(radius * phi.cos(), radius * phi.sin(), z); + let source_pdf = f64::from(source_count) / (4.0 * PI); + let weight = pdf * pdf / (pdf * pdf + source_pdf * source_pdf); + expected += radiance(direction) * (0.5 * z / (PI * pdf) * weight); + } + } + } + expected = expected / f64::from(samples); + let original = path_fixture(samples, depth, false); + let options = RaytraceOptions { environment: None, ..original.options }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for pixel in texels { + bytes.extend_from_slice(&pixel); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, source_count).unwrap(); + let (actual, _) = + path_mean(ImageTask::new_with_environment(original.scene, request, CancelToken::default(), options, Some(input)).unwrap()); + for (actual, expected) in actual.into_iter().zip([expected.x, expected.y, expected.z]) { + assert!((actual - expected).abs() < 1e-11, "HDR N={source_count}, depth={depth}: {actual} vs independent {expected}"); + } + } + } +} + +#[test] +fn composed_cpu_path_alpha_and_denoise_keep_analytic_matte_all_prefixes_and_raw_master() { + let output = job::OutputOptions { linear_exr: true, ..Default::default() }; + let make = |samples, transparent, denoise, path: bool| { + let original = alpha_fixture(Some(samples), 1, transparent, Some(output), 1.5); + let options = + RaytraceOptions { path: path.then_some(job::CpuPathOptions { max_depth: 1 }), denoise, shadows: true, ..original.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + ImageTask::new(original.scene, request, original.cancel, options).unwrap() + }; + let actual = complete_presentation(make(7, true, true, true), 1); + assert_eq!(actual, complete_presentation(make(7, true, true, true), 16384)); + assert_eq!(actual.0.iter().map(|p| p.0).collect::>(), [1, 2, 3, 4, 5, 6]); + let rgb = [9.0, 4.5, 2.25].map(|radiance| { + let exposed = radiance * 2.0f64.powf(1.5); + encode8(exposed / (1.0 + exposed)) + }); + for (samples, png) in actual.0.iter().chain(std::iter::once(&(7, actual.1.clone()))) { + let covered = (0..*samples).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let alpha = (covered as f64 / f64::from(*samples) * 255.0).round() as u8; + assert_eq!(alpha_pixel(png), if alpha == 0 { [0; 4] } else { [rgb[0], rgb[1], rgb[2], alpha] }); + assert_eq!(*png, complete_presentation(make(*samples, true, true, true), 3).1); + } + let unfiltered = complete_presentation(make(7, true, false, true), 1); + let opaque = complete_presentation(make(7, false, true, true), 1); + let direct = complete_presentation(make(7, true, true, false), 1); + assert_eq!(actual.2, unfiltered.2, "filtering cannot enter the GI raw companion"); + assert_eq!(actual.2, opaque.2, "background removal cannot enter the GI raw companion"); + assert_eq!(actual.2, direct.2, "a camera-visible emitter has the same raw radiance and coverage in either transport"); + assert_eq!((actual.0, actual.1), (unfiltered.0, unfiltered.1), "the partial-coverage emitter bypass keeps the analytic straight matte"); +} + +fn composed_panel_fixture(samples: u32, denoise: bool, path: bool, panel_z: f64, front: bool) -> ImageTask { + let original = path_fixture(samples, 1, false); + let point = |x, y| { + let (origin, _) = original.request.camera.ray(x, y, 13.0, 13.0); + Vec3::new(origin.x, origin.y, panel_z) + }; + let corner = point(5.0, 2.0); + let u = point(8.0, 2.0) - corner; + let mut v = point(5.0, 11.0) - corner; + let center = corner + (u + v) * 0.5; + if (u.cross(v).z > 0.0) != front { + v = -v; + } + let array = |p: Vec3| [p.x, p.y, p.z]; + let lights = (0..4) + .map(|index| job::RectangleLightOptions { + center_mm: array(center + Vec3::X * (100.0 * f64::from(index))), + edge_u_mm: array(u), + edge_v_mm: array(v), + color: [0.5, 0.4, 0.3], + intensity: 1.0, + }) + .collect(); + let options = RaytraceOptions { + denoise, + path: path.then_some(job::CpuPathOptions { max_depth: 1 }), + area_lights: Some(lights), + area_samples: Some(1), + seed: Some(31), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + let request = ImageRequest { width: 13, height: 13, raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() +} +fn composed_panel_guides(mut task: ImageTask) -> (Vec, u64) { + for _ in 0..300_000 { + if task.denoise.first().is_some_and(|guides| guides.ready()) { + assert_eq!(task.pixel, 0); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + return (task.denoise.first().unwrap().pixels().unwrap().to_vec(), task.work.used()); + } + let guiding = task.bvh.is_some(); + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if guiding { + assert_eq!(task.work.used() - before, 1, "each guide ray/traversal/source/effect/store continuation owns one work unit"); + } + } + panic!("bounded composed guide prepass did not finish"); +} +#[test] +fn composed_path_denoise_guides_bypass_visible_analytic_emitters_before_backing_geometry() { + let (guides, work) = composed_panel_guides(composed_panel_fixture(4, true, true, 2.0, true)); + for y in 0..13 { + for x in 0..13 { + assert_eq!(guides[y * 13 + x].body == 0, (5..8).contains(&x) && (2..11).contains(&y), "guide ({x},{y})"); + } + } + let (legacy, old_work) = composed_panel_guides(composed_panel_fixture(4, true, false, 2.0, true)); + assert!(legacy.iter().all(|guide| guide.body == 1), "absent path keeps analytic lights invisible to the first-hit prepass"); + assert_eq!( + work - old_work, + 13 * 13 * 4 - 3 * 9, + "four source scans per pixel; each of the27 bypassed panel pixels skips the underlying body-guide resolution" + ); + let original = composed_panel_fixture(4, true, false, 2.0, true); + let options = RaytraceOptions { area_lights: None, area_samples: None, seed: None, ..original.options }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + let no_lights = composed_panel_guides(ImageTask::new(original.scene, request, original.cancel, options).unwrap()); + assert_eq!(no_lights.1, old_work, "legacy guide work does not scan direct-only analytic lights"); + for (z, front) in [(0.0, true), (-2.0, true), (2.0, false)] { + let (guides, _) = composed_panel_guides(composed_panel_fixture(4, true, true, z, front)); + assert!( + guides.iter().all(|guide| guide.body == 1), + "geometry wins exact ties, nearer body hits and back-facing emitter supports; z={z}, front={front}" + ); + } +} +#[test] +fn composed_path_denoise_keeps_all_foreground_emitter_pixels_prefixes_and_raw_master_exact() { + let actual = complete_presentation(composed_panel_fixture(4, true, true, 2.0, true), 1); + assert_eq!(actual, complete_presentation(composed_panel_fixture(4, true, true, 2.0, true), 16384)); + assert_eq!(actual.0.iter().map(|p| p.0).collect::>(), [1, 2, 3]); + let raw = complete_presentation(composed_panel_fixture(4, false, true, 2.0, true), 1); + assert_eq!(actual.2, raw.2, "emitter bypass and filtering cannot alter raw GI EXR radiance"); + assert_ne!(actual.1, raw.1, "the noisy diffuse backing must actually exercise the filter"); + let rgb = [0.5_f64, 0.4, 0.3].map(|radiance| encode8(radiance / (1.0 + radiance))); + for ((samples, png), (raw_samples, raw_png)) in + actual.0.iter().chain(std::iter::once(&(4, actual.1.clone()))).zip(raw.0.iter().chain(std::iter::once(&(4, raw.1.clone())))) + { + assert_eq!(samples, raw_samples); + assert_eq!(*png, complete_presentation(composed_panel_fixture(*samples, true, true, 2.0, true), 3).1); + let filtered = ::image::load_from_memory(png).unwrap().to_rgba8(); + let unfiltered = ::image::load_from_memory(raw_png).unwrap().to_rgba8(); + for y in 2..11 { + for x in 5..8 { + assert_eq!(filtered.get_pixel(x, y), unfiltered.get_pixel(x, y), "sample{samples}, panel({x},{y})"); + assert_eq!(filtered.get_pixel(x, y).0, [rgb[0], rgb[1], rgb[2], 255]); + } + } + } +} +#[test] +fn composed_path_guide_emitter_scans_cancel_and_exhaust_before_consuming_the_next_source() { + for cancel in [false, true] { + let mut task = composed_panel_fixture(4, true, true, 2.0, true); + for _ in 0..300_000 { + if task.denoise.first().is_some_and(|guide| guide.emitter_scans() == 2) { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + let guide = task.denoise.first().unwrap(); + assert_eq!(guide.emitter_scans(), 2); + assert!(!guide.ready_to_store(&task.options), "remaining emitter scans precede the actual guide store"); + assert_eq!(guide.completed_pixels(), 0); + let used = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + let guide = task.denoise.first().unwrap(); + assert_eq!(guide.emitter_scans(), 2); + assert!(!guide.ready_to_store(&task.options), "remaining emitter scans precede the actual guide store"); + assert_eq!(guide.completed_pixels(), 0); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + } +} + +// CPU aging uses the existing saved optical-layer schema, but evaluates a world +// field once before sharing one closure with transport and the first-hit guides. +fn aging_stack(layers: &[job::aging::AgingLayer]) -> Box { + let mut stack = job::aging::AgingStack::default(); + for layer in layers { + stack.push(*layer).unwrap(); + } + Box::new(stack) +} +fn solid_age() -> job::aging::AgingLayer { + job::aging::AgingLayer { + kind: job::aging::AgingKind::Dust, + strength: 1.0, + coverage: 1.0, + upward_bias: 0.0, + color_srgb: [255, 0, 0], + metallic: 0.0, + roughness: 1.0, + scale_mm: 100_000.0, + ..Default::default() + } +} +fn age_surface( + layers: &[job::aging::AgingLayer], + input: crate::surface_patterns::ShadingSurface, + point: Vec3, + outward: Vec3, + eligible: bool, +) -> crate::surface_patterns::ShadingSurface { + let stack = aging_stack(layers); + let mut task = super::super::aging::Task::default(); + task.begin(input, point, outward, 0, eligible).unwrap(); + while !task.ready() { + task.advance(&stack).unwrap(); + } + task.surface().unwrap() +} +#[test] +fn cpu_aging_all_kinds_match_independent_full_coverage_optical_values_and_keep_normals() { + let input = crate::surface_patterns::ShadingSurface { + surface: OpaqueSurface::new(Vec3::new(0.2, 0.4, 0.6), 0.7, 0.3, 1.6).unwrap(), + shading_normal: Vec3::new(0.0, 0.6, 0.8), + }; + // Independent integer hash oracle at q=(0,0,0): the two value-noise + // octaves are exact lattice values, not values from the CPU evaluator. + let hash = |cell: [u32; 3], seed: u32| { + let mut h = (cell[0] & 4095).wrapping_mul(0x8da6_b343) + ^ (cell[1] & 4095).wrapping_mul(0xd816_3841) + ^ (cell[2] & 4095).wrapping_mul(0xcb1a_b31f) + ^ seed.wrapping_mul(0x9e37_79b9); + h = (h ^ (h >> 16)).wrapping_mul(0x7feb_352d); + h = (h ^ (h >> 15)).wrapping_mul(0x846c_a68b); + f64::from((h ^ (h >> 16)) >> 8) / 16_777_216.0 + }; + let field = 0.75 * hash([0, 0, 0], 19) + 0.25 * hash([19, 7, 3], 20); + for kind in job::aging::AgingKind::ALL { + let layer = job::aging::AgingLayer { kind, ..solid_age() }; + let changed = age_surface(&[layer], input, Vec3::ZERO, Vec3::Z, true); + assert_eq!(changed.shading_normal, input.shading_normal); + assert_eq!(changed.surface.dielectric_ior(), 1.6); + if kind == job::aging::AgingKind::Scratches { + // Independent band0 line at u=0 lies outside the narrow scratch; + // this first point is an exact no-op, rather than invented wear. + let line = ((hash([0, 0, 0], 19) * 0.7).fract() - 0.5).abs(); + assert!(line >= 0.09); + assert_eq!(changed, input); + } else { + let expected = match kind { + job::aging::AgingKind::Rust | job::aging::AgingKind::Patina | job::aging::AgingKind::Grime => { + Vec3::new((0.45 + 0.7 * field).min(1.0), 0.0, 0.0) + } + job::aging::AgingKind::Fading => Vec3::new(0.6, 0.2, 0.3), + _ => Vec3::X, + }; + assert!((changed.surface.base_color() - expected).len() < 1e-15, "{kind:?}"); + assert_eq!(changed.surface.metallic(), 0.0); + assert_eq!(changed.surface.roughness(), 1.0); + } + } +} +#[test] +fn cpu_aging_uses_original_material_class_layer_order_targets_and_coat_attenuation() { + let coat = crate::clear_coat::ClearCoat::new(0.8, 0.2, 1.7).unwrap(); + let input = crate::surface_patterns::ShadingSurface { + surface: OpaqueSurface::new(Vec3::new(0.2, 0.3, 0.4), 1.0, 0.4, 1.6).unwrap().with_clear_coat(coat), + shading_normal: Vec3::Z, + }; + let first = job::aging::AgingLayer { strength: 0.25, surface_class: job::aging::SurfaceClass::Metal, ..solid_age() }; + let changed = age_surface(&[first], input, Vec3::ZERO, Vec3::Z, true); + assert!((changed.surface.base_color() - Vec3::new(0.4, 0.225, 0.3)).len() < 1e-15); + assert_eq!(changed.surface.metallic(), 0.75); + let remaining = changed.surface.clear_coat().unwrap(); + assert!((remaining.weight() - 0.6).abs() < 1e-15); + assert_eq!((remaining.roughness(), remaining.ior()), (0.2, 1.7)); + let original_class = [ + job::aging::AgingLayer { surface_class: job::aging::SurfaceClass::Metal, ..solid_age() }, + job::aging::AgingLayer { surface_class: job::aging::SurfaceClass::Dielectric, color_srgb: [0, 0, 255], ..solid_age() }, + job::aging::AgingLayer { surface_class: job::aging::SurfaceClass::Metal, color_srgb: [0, 255, 0], ..solid_age() }, + ]; + assert_eq!( + age_surface(&original_class, input, Vec3::ZERO, Vec3::Z, true).surface.base_color(), + Vec3::Y, + "class selection uses original metallic, after earlier layers lower the current value" + ); + let other = job::aging::AgingLayer { + target: Some(job::aging::BodyTarget { body_index: 1, body_name: job::aging::BodyName::new("other").unwrap() }), + ..solid_age() + }; + assert_eq!(age_surface(&[other], input, Vec3::ZERO, Vec3::Z, true), input); + assert_eq!(age_surface(&[solid_age()], input, Vec3::ZERO, Vec3::Z, false), input, "glass/stage bypass is exact"); + let down = job::aging::AgingLayer { upward_bias: 1.0, ..solid_age() }; + assert_eq!(age_surface(&[down], input, Vec3::ZERO, -Vec3::Z, true), input, "use original winding, not face-forward shading normal"); +} +#[test] +fn cpu_aging_world_coordinates_are_camera_independent_and_keep_scratch_band_identity() { + let input = crate::surface_patterns::ShadingSurface { surface: OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap(), shading_normal: Vec3::Z }; + let layer = job::aging::AgingLayer { kind: job::aging::AgingKind::Scratches, scale_mm: 2.0, ..solid_age() }; + let point = Vec3::new(0.009380418558915457, 5.75, 0.0); + let expected = age_surface(&[layer], input, point, Vec3::Z, true); + assert!(expected.surface.base_color().x > 0.1, "the anchor oracle must exercise a visible scratch"); + // Move world origin and hit together; the exact f64 millimetre frame is the + // same, even across the GPU noise-rebase boundary (which Scratch bands do not share). + let offset = Vec3::new(8192.0, 8192.0, 8192.0); + let shifted = job::aging::AgingLayer { origin_mm: [offset.x, offset.y, offset.z], ..layer }; + let moved = age_surface(&[shifted], input, point + offset, Vec3::Z, true); + assert!((moved.surface.base_color() - expected.surface.base_color()).len() < 1e-10); + let mut another = super::super::aging::Task::default(); + another.begin(input, point, Vec3::Z, 0, true).unwrap(); + another.advance(&aging_stack(&[layer])).unwrap(); + assert_eq!(another.surface().unwrap(), expected, "there is no camera argument or frame-local field origin"); +} +fn aging_image(samples: u32, path: bool, denoise: bool, layers: &[job::aging::AgingLayer]) -> ImageTask { + let original = path_fixture(samples, 2, false); + let options = RaytraceOptions { + aging: (!layers.is_empty()).then(|| aging_stack(layers)), + denoise, + path: path.then_some(job::CpuPathOptions { max_depth: 2 }), + lights: (!path) + .then(|| vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: std::f64::consts::PI }]) + .or_else(|| Some(vec![])), + environment: path.then_some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() +} +#[test] +fn cpu_aging_actual_direct_png_and_raw_master_have_analytic_lambert_response() { + let result = complete_presentation(aging_image(5, false, false, &[solid_age()]), 1); + assert_eq!(result.0.iter().map(|p| p.0).collect::>(), [1, 2, 3, 4]); + for png in result.0.iter().map(|p| &p.1).chain(std::iter::once(&result.1)) { + assert_eq!(::image::load_from_memory(png).unwrap().to_rgba8().get_pixel(0, 0).0, [encode8(0.5), 0, 0, 255]); + } + let raw = native_exr_pixels(result.2.as_deref().unwrap()); + assert_eq!(raw.get_pixel(0, 0).0, [1.0, 0.0, 0.0, 1.0]); +} +#[test] +fn cpu_aging_actual_path_uses_aged_response_pdf_and_scatter_for_every_prefix_and_quantum() { + use std::f64::consts::PI; + let samples = 64; + let actual = path_mean(aging_image(samples, true, false, &[solid_age()])).0; + let mut expected = 0.0; + for ordinal in 0..samples { + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000); + let z = 1.0 - 2.0 * u; + let light_pdf = 1.0 / (4.0 * PI); + if z > 0.0 { + let bsdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + expected += 4.0 * z * light_pdf * light_pdf / (light_pdf * light_pdf + bsdf * bsdf); + } + let (cosine, pdf) = independent_lambert_scatter(ordinal); + if pdf > 0.0 { + expected += cosine / (PI * pdf) * pdf * pdf / (pdf * pdf + light_pdf * light_pdf); + } + } + expected /= f64::from(samples); + assert!((actual[0] - expected).abs() < 1e-11); + assert_eq!(actual[1..], [0.0, 0.0]); + let layer = job::aging::AgingLayer { coverage: 0.5, ..solid_age() }; + let small = complete_presentation(aging_image(5, true, false, &[layer]), 1); + assert_eq!(small, complete_presentation(aging_image(5, true, false, &[layer]), 16384)); + for (samples, png) in &small.0 { + assert_eq!(*png, complete_presentation(aging_image(*samples, true, false, &[layer]), 3).1); + } +} +#[test] +fn cpu_aging_guides_see_the_aged_material_and_filter_never_changes_raw_intent() { + // The public constructor's minimum is0.045; it is still strictly inside + // the smooth-metal guide bypass range (<0.25), before aging changes it. + let smooth = OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 1.0, 0.045, 1.0).unwrap(); + assert_eq!(smooth.roughness(), crate::surface::MIN_ROUGHNESS); + let mut pristine = aging_image(5, true, true, &[]); + pristine.scene.meshes[0].surface = Some(smooth); + let (unaged_guides, _) = composed_panel_guides(pristine); + assert_eq!(unaged_guides.len(), 1); + assert_eq!(unaged_guides[0].body, 0, "the valid unaged smooth-metal fixture actually bypasses denoising"); + let mut task = aging_image(5, true, true, &[solid_age()]); + task.scene.meshes[0].surface = Some(smooth); + let (guides, _) = composed_panel_guides(task); + assert_eq!(guides.len(), 1); + assert_eq!(guides[0].body, 1, "aging removes smooth-metal bypass before guides are captured"); + assert_eq!(guides[0].albedo, [1.0, 0.0, 0.0]); + let filtered = complete_presentation(aging_image(5, true, true, &[solid_age()]), 1); + let raw = complete_presentation(aging_image(5, true, false, &[solid_age()]), 16384); + assert_eq!(filtered.2, raw.2, "the denoiser only sees the copied pass, never raw EXR/film"); + assert_eq!(filtered, complete_presentation(aging_image(5, true, true, &[solid_age()]), 16384)); +} +#[test] +fn cpu_aging_absent_and_inactive_layers_keep_old_png_work_and_exact_admission_deltas() { + let layer = job::aging::AgingLayer { enabled: false, ..solid_age() }; + let inactive = aging_image(5, false, false, &[layer]); + let absent = aging_image(5, false, false, &[]); + assert_eq!(inactive.aging.capacity(), 0); + assert_eq!( + inactive.admission.estimated_total_bytes - absent.admission.estimated_total_bytes, + 2 * std::mem::size_of::() as u64 + ); + assert_eq!(complete_presentation(inactive, 1), complete_presentation(absent, 16384)); + let active = aging_image(5, false, false, &[solid_age()]); + let inactive = aging_image(5, false, false, &[layer]); + assert_eq!(active.aging.capacity(), 1); + assert_eq!(active.admission.estimated_total_bytes - inactive.admission.estimated_total_bytes, super::super::aging::Task::required_bytes()); + assert_eq!( + active.options.retained_aging_bytes().unwrap(), + std::mem::size_of::() as u64, + "Record separately charges its retained options box" + ); + assert!(serde_json::to_value(RaytraceOptions::default()).unwrap().get("aging").is_none()); +} +#[test] +fn cpu_aging_cancel_and_work_exhaustion_do_not_advance_a_layer_or_commit_a_pass() { + for path in [false, true] { + for guides in [false, true] { + for cancel in [false, true] { + let mut task = aging_image(5, path, guides, &[solid_age(), solid_age(), solid_age()]); + for _ in 0..100_000 { + if task.aging.first().is_some_and(|aging| aging.started() && aging.cursor() == 1 && !aging.ready()) { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert_eq!(task.aging.first().unwrap().cursor(), 1); + let used = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work = WorkBudget::new(used).unwrap(); + task.work.charge(used, &task.cancel).unwrap(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.aging.first().unwrap().cursor(), 1); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + } + } + } +} + +#[test] +fn cpu_aging_limits_and_incompatible_authored_materials_refuse_without_dropping_intent() { + let original = aging_image(3, false, false, &[solid_age()]); + let validate = |options: RaytraceOptions| { + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + admit(&original.scene, &request, &options).unwrap_err().to_string() + }; + let mut options = original.options.clone(); + options.aging.as_mut().unwrap().get_mut(0).unwrap().target = + Some(job::aging::BodyTarget { body_index: 0, body_name: job::aging::BodyName::new("replaced").unwrap() }); + assert!(validate(options).contains("identity changed")); + let mut options = original.options.clone(); + options.aging.as_mut().unwrap().get_mut(0).unwrap().scale_mm = 0.01; + assert!(validate(options).contains("4096 repeats")); + let mut options = original.options.clone(); + options.aging.as_mut().unwrap().get_mut(0).unwrap().strength = f64::NAN; + assert!(options.validate().is_err()); + let mut options = original.options.clone(); + options.anisotropic_faces[0] = Some(job::AnisotropicFaceOptions { + body_index: 0, + body_name: original.scene.meshes[0].name.clone(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: job::AnisotropicOrientation::Zero, + roughness_x: 0.2, + roughness_y: 0.6, + }); + let before = options.clone(); + assert!(validate(options.clone()).contains("anisotropic roughness axes")); + assert_eq!(options, before); + let mut options = original.options.clone(); + options.dielectrics.push(job::DielectricOptions { + shadow_transmission: false, + subsurface: None, + body_index: 0, + body_name: original.scene.meshes[0].name.clone(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }); + options.aging.as_mut().unwrap().get_mut(0).unwrap().target = + Some(job::aging::BodyTarget { body_index: 0, body_name: job::aging::BodyName::new(&original.scene.meshes[0].name).unwrap() }); + assert!(validate(options.clone()).contains("explicit certified dielectric")); + assert!(!super::super::aging::eligible(&options, 0, &original.scene.meshes[0].name)); + assert!(!super::super::aging::eligible(&RaytraceOptions::default(), 1, "__render_stage__/floor")); + let mut metallic_scene = original.scene.clone(); + metallic_scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::X, 1.0, 0.5, 1.0).unwrap()); + let mut options = original.options.clone(); + options.reflections = Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: metallic_scene.meshes[0].name.clone(), mode: ReflectionMode::RoughSpecular }], + samples: 1, + max_bounces: 2, + }); + assert!(options.validate_environment_reflections(&metallic_scene).unwrap_err().to_string().contains("diffuse lobe introduced")); + options.aging.as_mut().unwrap().get_mut(0).unwrap().metallic = 1.0; + options.validate_environment_reflections(&metallic_scene).unwrap(); + options.aging.as_mut().unwrap().get_mut(0).unwrap().metallic = 0.0; + options.aging.as_mut().unwrap().get_mut(0).unwrap().surface_class = job::aging::SurfaceClass::Dielectric; + options.validate_environment_reflections(&metallic_scene).unwrap(); +} + +#[test] +fn cpu_aging_point_zero_two_is_preserved_before_real_path_mis_and_sharp_metal_guide_bypass() { + use std::f64::consts::PI; + let layer = job::aging::AgingLayer { roughness: 0.02, metallic: 1.0, color_srgb: [255; 3], ..solid_age() }; + let input = crate::surface_patterns::ShadingSurface { surface: OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap(), shading_normal: Vec3::Z }; + assert_eq!(age_surface(&[layer], input, Vec3::ZERO, Vec3::Z, true).surface.roughness(), 0.02); + let a2 = 0.02_f64.powi(4); + let response_pdf = |cosine: f64| { + let nh2 = (1.0 + cosine) / 2.0; + let d = (1.0 - cosine) / 2.0 + nh2 * a2; + let distribution = a2 / (PI * d * d); + let g1 = 2.0 * cosine / (cosine + (a2 + (1.0 - a2) * cosine * cosine).sqrt()); + (distribution * g1 / 4.0, 0.5 * cosine / PI + 0.5 * distribution / 4.0) + }; + let samples = 64; + let light_pdf = 1.0 / (4.0 * PI); + let mut expected = 0.0; + for ordinal in 0..samples { + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000); + let cosine = 1.0 - 2.0 * u; + if cosine > 0.0 { + let (response, pdf) = response_pdf(cosine); + expected += response / light_pdf * light_pdf * light_pdf / (light_pdf * light_pdf + pdf * pdf); + } + let [component, u] = progressive::variates(9, 0, ordinal, 0x5041_5448_3000); + let cosine = if component < 0.5 { (1.0 - u).sqrt() } else { ((1.0 - u) - a2 * u) / ((1.0 - u) + a2 * u) }; + if cosine > 0.0 { + let (response, pdf) = response_pdf(cosine); + expected += response / pdf * pdf * pdf / (pdf * pdf + light_pdf * light_pdf); + } + } + expected /= f64::from(samples); + let actual = path_mean(aging_image(samples, true, false, &[layer])).0; + for channel in actual { + assert!((channel - expected).abs() < 1e-11, "actual unclamped path MIS {channel}, independent oracle {expected}"); + } + let (guides, _) = composed_panel_guides(aging_image(5, true, true, &[layer])); + assert_eq!(guides[0].body, 0, "the guide sees the sharp aged metal, not the original diffuse body"); + let filtered = complete_presentation(aging_image(5, true, true, &[layer]), 1); + let unfiltered = complete_presentation(aging_image(5, true, false, &[layer]), 3); + assert_eq!(filtered.2, unfiltered.2, "unfiltered film remains the raw master"); + assert_eq!((filtered.0, filtered.1), (unfiltered.0, unfiltered.1), "sharp-metal guide bypass is exact"); +} +fn aging_reflection(samples: u32) -> ImageTask { + let original = aging_image(samples, false, false, &[]); + let options = RaytraceOptions { + aging: Some(aging_stack(&[job::aging::AgingLayer { roughness: 0.02, metallic: 1.0, color_srgb: [255; 3], ..solid_age() }])), + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: original.scene.meshes[0].name.clone(), mode: ReflectionMode::RoughSpecular }], + samples: 1, + max_bounces: 1, + }), + lights: Some(Vec::new()), + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() +} +#[test] +fn no_aging_legacy_direct_shade_and_film_commit_have_the_existing_two_unit_boundary() { + let samples = 3; + let mut task = aging_image(samples, false, false, &[]); + assert_eq!((task.request.width, task.request.height), (1, 1)); + assert!(task.options.adaptive.is_none()); + assert!(task.options.path.is_none() && task.options.aging.is_none() && task.options.reflections.is_none()); + let mut two_unit_commits = 0; + for _ in 0..2_000_000 { + if task.progressive.as_ref().is_some_and(|p| p.film.samples() == samples) { + let (mean, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!((u32::from(covered), u32::from(count)), (samples, samples)); + // Independent normal-incidence Lambertian reference: rho0.5, + // F0=0 at IOR1, light radiance PI, cosine1 gives0.5. + for value in mean { + assert!((value - 0.5).abs() < 1e-15); + } + assert_eq!(two_unit_commits, samples, "one pre-existing shade+film boundary per unaged primary sample"); + return; + } + let transport = task.bvh.is_some() + && task.progressive.as_ref().is_some_and(|p| p.film.ready() && !p.resolving) + && task.pixel == 0 + && task.output.is_empty() + && task.encoder.is_none(); + let count_before = transport.then(|| task.progressive.as_ref().unwrap().film.samples()); + let before = task.work.used(); + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + if transport { + let used = task.work.used() - before; + assert!(used <= 2); + if used == 2 { + two_unit_commits += 1; + assert_eq!(task.pixel, 1); + assert!(task.pending.is_none()); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), count_before.unwrap() + 1); + } + } + } + panic!("bounded unaged legacy fixture did not complete"); +} +#[test] +fn cpu_aging_point_zero_two_legacy_reflection_keeps_independent_furnace_all_prefixes_and_quanta() { + let samples = 17; + let (actual, _) = path_mean(aging_reflection(samples)); + let a2 = 0.02_f64.powi(4); + let expected = (0..samples) + .map(|ordinal| { + let [u, _] = progressive::variates(9, 0, ordinal, 0x100); + let cosine = ((1.0 - u) - a2 * u) / ((1.0 - u) + a2 * u); + if cosine <= 0.0 { 0.0 } else { 2.0 * cosine / (cosine + (a2 + (1.0 - a2) * cosine * cosine).sqrt()) } + }) + .sum::() + / f64::from(samples); + assert!((expected - 1.0).abs() < 1e-8); + for value in actual { + assert!((value - expected).abs() < 1e-12); + } + let result = complete_presentation(aging_reflection(samples), 1); + assert_eq!(result, complete_presentation(aging_reflection(samples), 16384)); + assert_eq!(result.0.len(), 16); + for (samples, png) in &result.0 { + assert_eq!(*png, complete_presentation(aging_reflection(*samples), 3).1); + } + let raw = native_exr_pixels(result.2.as_deref().unwrap()); + assert_eq!(raw.get_pixel(0, 0).0, [expected as f32, expected as f32, expected as f32, 1.0]); +} + +fn cpu_map_png(width: u32, height: u32, values: &[u8]) -> Vec { + use ::image::ImageEncoder; + let mut bytes = Vec::new(); + ::image::codecs::png::PngEncoder::new(&mut bytes).write_image(values, width, height, ::image::ExtendedColorType::Rgba8).unwrap(); + bytes +} +fn cpu_map_binding(body: usize, name: &str, color: Option>) -> job::textures::TextureBinding { + use crate::texture_input::MapRole; + job::textures::TextureBinding { + body_index: body, + body_name: name.into(), + frame: job::textures::PlanarFrame { origin: [0.0; 3], u: [1e6, 0.0, 0.0], v: [0.0, 1e6, 0.0] }, + normal_strength: 1.0, + base_color: color.map(|bytes| job::textures::TextureMap::new(bytes, MapRole::BaseColor).unwrap()), + normal: None, + roughness: None, + metallic: None, + base_color_mode: job::textures::BaseColorMode::Replace, + flip_v: false, + } +} +fn cpu_mapped_fixture(samples: u32, path: bool, guides: bool, all_roles: bool) -> ImageTask { + use crate::texture_input::MapRole; + let original = path_fixture(samples, if path { 2 } else { 1 }, false); + let mut scene = original.scene.clone(); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 1.0, if all_roles { 1.5 } else { 1.0 }).unwrap()); + let mut binding = cpu_map_binding(0, &scene.meshes[0].name, Some(cpu_map_png(1, 1, &[128, 64, 255, 255]))); + if all_roles { + binding.roughness = Some(job::textures::TextureMap::new(cpu_map_png(1, 1, &[128, 128, 128, 255]), MapRole::Roughness).unwrap()); + binding.metallic = Some(job::textures::TextureMap::new(cpu_map_png(1, 1, &[64, 64, 64, 255]), MapRole::Metallic).unwrap()); + binding.normal = Some(job::textures::TextureMap::new(cpu_map_png(1, 1, &[128, 255, 255, 255]), MapRole::NormalOpenGl).unwrap()); + } + let options = RaytraceOptions { + path: path.then_some(job::CpuPathOptions { max_depth: 2 }), + denoise: guides, + lights: Some(if path { vec![] } else { vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 3.0 }] }), + environment: path.then_some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + let request = ImageRequest { + textures: Some(Arc::new(job::textures::RuntimeTextures::new(vec![binding]).unwrap())), + raytrace: Some(options.clone()), + ..original.request + }; + ImageTask::new(scene, request, original.cancel, options).unwrap() +} +fn cpu_map_linear(byte: u8) -> f64 { + let c = f64::from(byte) / 255.0; + (if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } as f32) as f64 +} +#[test] +fn cpu_saved_map_all_roles_reach_real_direct_brdf_film_png_and_raw_master() { + use std::f64::consts::PI; + let task = cpu_mapped_fixture(4, false, false, true); + let mut raw = cpu_mapped_fixture(4, false, false, true); + let target = raw.options.progressive.unwrap().samples_per_pixel; + while raw.progressive.as_ref().unwrap().film.samples() != target { + raw.step_with_previews(1).unwrap(); + } + let (actual, coverage, samples) = raw.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!((coverage, u32::from(samples)), (4, 4)); + // Independent normal-view Cook–Torrance formula, including the symmetric + // Fresnel substrate attenuation used by the shared optical contract. + let n = Vec3::new(f64::from(128_f32 / 255.0) * 2.0 - 1.0, 1.0, 1.0).normalized().unwrap(); + let cosine = n.z; + let rough = f64::from(128_f32 / 255.0); + let metal = f64::from(64_f32 / 255.0); + let a2 = rough.powi(4); + let d = a2 / (PI * ((1.0 - cosine * cosine) + cosine * cosine * a2).powi(2)); + let visibility = 2.0 / (cosine + (a2 + (1.0 - a2) * cosine * cosine).sqrt()); + let expected: [f64; 3] = [128, 64, 255].map(|byte| { + let base = cpu_map_linear(byte); + let f0 = 0.04 * (1.0 - metal) + base * metal; + let f = f0 + (1.0 - f0) * (1.0 - cosine).powi(5); + let brdf = f0 * d * 0.25 * visibility * visibility + (1.0 - f) * (1.0 - f) * base * (1.0 - metal) / PI; + brdf * cosine * 3.0 + }); + for (a, b) in actual.into_iter().zip(expected) { + assert!((a - b).abs() < 1e-12, "mapped closure {a} != independent response {b}"); + } + let rendered = complete_presentation(task, 1); + assert_eq!(rendered, complete_presentation(cpu_mapped_fixture(4, false, false, true), 16384)); + assert!(rendered.2.is_some()); + let expected = expected.map(|v| encode8(v / (1.0 + v))); + assert_eq!(alpha_pixel(&rendered.1), [expected[0], expected[1], expected[2], 255]); + for (samples, png) in &rendered.0 { + assert_eq!(*png, complete_presentation(cpu_mapped_fixture(*samples, false, false, true), 3).1); + } +} +#[test] +fn cpu_saved_map_indirect_brdf_and_pdf_match_independent_per_ordinal_furnace() { + use std::f64::consts::PI; + let samples = 1024; + let mut value = 0.0; + for ordinal in 0..samples { + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000); + let z = 1.0 - 2.0 * u; + let lp = 1.0 / (4.0 * PI); + if z > 0.0 { + let bp = 0.5 * z / PI + 0.5 / (4.0 * PI); + value += 4.0 * z * lp * lp / (lp * lp + bp * bp); + } + let (z, pdf) = independent_lambert_scatter(ordinal); + if pdf > 0.0 { + value += z / (PI * pdf) * pdf * pdf / (pdf * pdf + lp * lp); + } + } + value /= f64::from(samples); + let (actual, _) = path_mean(cpu_mapped_fixture(samples, true, false, false)); + for (a, byte) in actual.into_iter().zip([128, 64, 255]) { + let b = cpu_map_linear(byte) * value; + assert!((a - b).abs() < 1e-11, "mapped MIS {a} != independent {b}"); + } +} +#[test] +fn cpu_saved_maps_are_applied_to_secondary_vertices_before_continuation_sampling() { + let original = path_fixture(512, 4, true); + let mapped_color = [cpu_map_linear(32), cpu_map_linear(128), cpu_map_linear(64)]; + let binding = cpu_map_binding(1, &original.scene.meshes[1].name, Some(cpu_map_png(1, 1, &[32, 128, 64, 255]))); + let resources = Arc::new(job::textures::RuntimeTextures::new(vec![binding]).unwrap()); + let mapped = ImageTask::new( + original.scene.clone(), + ImageRequest { textures: Some(resources), ..original.request.clone() }, + CancelToken::default(), + original.options.clone(), + ) + .unwrap(); + let mut explicit = original.scene.clone(); + explicit.meshes[1].surface = Some(OpaqueSurface::new(Vec3::new(mapped_color[0], mapped_color[1], mapped_color[2]), 0.0, 1.0, 1.0).unwrap()); + let reference = ImageTask::new(explicit, original.request.clone(), CancelToken::default(), original.options.clone()).unwrap(); + let actual = path_mean(mapped).0; + let expected = path_mean(reference).0; + // A constant map still evaluates the reference bilinear weights in f64; + // compare the independent explicit closure at the numerical transport scale. + for (actual, expected) in actual.into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12, "secondary mapped BRDF/PDF/proposal {actual} != explicit material {expected}"); + } + assert_ne!(actual, path_mean(original).0, "a map on a secondary opaque surface must change the actual multi-bounce result"); +} +#[test] +fn cpu_saved_map_guides_use_the_same_prepared_material_and_never_change_raw_film() { + let mut task = cpu_mapped_fixture(4, true, true, true); + for _ in 0..200_000 { + if task.denoise.first().unwrap().ready() { + break; + } + task.step_with_previews(1).unwrap(); + } + let guide = task.denoise.first().unwrap().pixels().unwrap()[0]; + assert_eq!(guide.body, 1); + assert_eq!(guide.albedo, [cpu_map_linear(128) as f32, cpu_map_linear(64) as f32, 1.0]); + let expected = Vec3::new(f64::from(128_f32 / 255.0) * 2.0 - 1.0, 1.0, 1.0).normalized().unwrap(); + assert!((Vec3::new(f64::from(guide.normal[0]), f64::from(guide.normal[1]), f64::from(guide.normal[2])) - expected).len() < 1e-7); + let filtered = complete_presentation(cpu_mapped_fixture(4, true, true, true), 1); + let raw = complete_presentation(cpu_mapped_fixture(4, true, false, true), 16384); + assert_eq!(filtered.2, raw.2, "guide capture/filtering cannot change raw mapped radiance"); + assert_eq!(filtered, complete_presentation(cpu_mapped_fixture(4, true, true, true), 16384)); +} +#[test] +fn cpu_saved_map_cache_and_hit_continuations_cancel_or_exhaust_before_next_mutation() { + for during_hit in [false, true] { + for cancel in [false, true] { + let mut task = cpu_mapped_fixture(4, true, false, true); + for _ in 0..200_000 { + let cache = task.maps.first().unwrap(); + if (!during_hit && cache.preparation_phase() == Some("linear")) || (during_hit && cache.hit_role() == Some(1)) { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + let before = task.work.used(); + let before_maps = task.maps.first().unwrap().prepared_maps(); + let role = task.maps.first().unwrap().hit_role(); + 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.maps.first().unwrap().prepared_maps(), before_maps); + assert_eq!(task.maps.first().unwrap().hit_role(), role); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + assert!(!task.done); + } + } +} + +#[test] +fn cpu_map_cache_bills_actual_source_capacity_pixels_and_one_peak_decoder_and_deduplicates_roles() { + use crate::job::textures::cpu_cache::CpuTextureCache; + let original = cpu_mapped_fixture(4, true, false, true); + let resources = original.request.textures.as_ref().unwrap(); + let bytes = CpuTextureCache::required_bytes(resources, &original.scene, &original.options).unwrap(); + let mut plain_request = original.request.clone(); + plain_request.textures = None; + let plain = ImageTask::new(original.scene.clone(), plain_request, CancelToken::default(), original.options.clone()).unwrap(); + assert_eq!(plain.maps.capacity(), 0, "omitted maps create no cache/decoder/hit heap slot"); + assert_eq!(original.admission.estimated_total_bytes - plain.admission.estimated_total_bytes, bytes); + assert_eq!(original.admission.preparation_bytes - plain.admission.preparation_bytes, bytes); + let mut clone = original.scene.clone(); + let mut body = clone.meshes[0].clone(); + body.name = "same maps second body".into(); + clone.meshes.push(body); + let first = resources.bindings()[0].clone(); + let mut second = first.clone(); + second.body_index = 1; + second.body_name = clone.meshes[1].name.clone(); + let shared = Arc::new(job::textures::RuntimeTextures::new(vec![first, second]).unwrap()); + assert_eq!(shared.summary().linear_pixel_bytes, resources.summary().linear_pixel_bytes); + assert_eq!(shared.summary().encoded_bytes, resources.summary().encoded_bytes); + let shared_bytes = CpuTextureCache::required_bytes(&shared, &clone, &original.options).unwrap(); + assert!(shared_bytes > bytes, "actual binding/name/map metadata capacities are still admitted"); + assert!(shared_bytes - bytes < 64 * 1024, "shared pixels and codec workspace cannot be charged twice"); + // Independently count unique source+role rows from the authored resources; + // two bodies share the same four maps and must not double the progress target. + let mut sources = std::collections::BTreeSet::new(); + let mut unique_rows = 0_u64; + for binding in shared.bindings() { + for map in [&binding.base_color, &binding.roughness, &binding.metallic, &binding.normal].into_iter().flatten() { + if sources.insert(map.identity()) { + unique_rows += u64::from(map.dimensions()[1]); + } + } + } + let mut cache = CpuTextureCache::new(shared, &CancelToken::default()).unwrap(); + let mut work = 0; + while !cache.ready() { + cache + .prepare_one(&CancelToken::default(), &mut |units| { + assert_eq!(units, 1); + work += units; + Ok(()) + }) + .unwrap(); + } + assert_eq!(cache.prepared_maps(), 4, "source+role identity shares actual owned normalized pixels"); + assert_eq!(cache.preparation_rows(), (unique_rows, unique_rows), "real shared-map preparation reaches its unique decoded-row target"); + assert!(work > 0); + let no_maps = complete_presentation(plain, 1); + let mut reference = cpu_mapped_fixture(4, true, false, true); + reference.request.textures = None; + let reference = ImageTask::new(reference.scene, reference.request, reference.cancel, reference.options).unwrap(); + assert_eq!(no_maps, complete_presentation(reference, 16384), "no-map PNG/raw/work stays on the ordinary producer for every quantum"); +} +#[test] +fn cpu_map_active_producer_refuses_legacy_selected_optics_without_erasing_any_intent() { + let original = cpu_mapped_fixture(4, true, false, false); + let mut options = original.options.clone(); + options.path = None; + options.reflections = Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: original.scene.meshes[0].name.clone(), mode: ReflectionMode::Mirror }], + samples: 1, + max_bounces: 2, + }); + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + let before = serde_json::to_value(&options).unwrap(); + assert!(admit(&original.scene, &request, &options).unwrap_err().message.contains("CPU surface maps")); + assert_eq!(serde_json::to_value(&options).unwrap(), before); + assert!(request.textures.is_some()); + let mut legacy = options.clone(); + legacy.reflections = None; + let plain = ImageRequest { raytrace: Some(legacy.clone()), textures: None, ..request }; + assert!(admit(&original.scene, &plain, &legacy).is_ok()); +} +#[test] +fn cpu_map_spatial_pixels_use_actual_world_coordinates_for_every_jittered_prefix() { + let make = |samples| { + let original = path_fixture(samples, 1, false); + let mut scene = original.scene; + let mut mesh = (*scene.meshes[0].mesh).clone(); + for point in &mut mesh.positions { + point.x = point.x.signum() * 10.0; + point.y = point.y.signum() * 10.0; + } + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap()); + let mut binding = cpu_map_binding(0, &scene.meshes[0].name, Some(cpu_map_png(2, 1, &[0, 0, 0, 255, 255, 0, 0, 255]))); + binding.frame.u = [1.0, 0.0, 0.0]; + binding.frame.v = [0.0, 1.0, 0.0]; + let options = RaytraceOptions { + path: None, + environment: None, + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: std::f64::consts::PI }]), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + // Keep this coordinate/jitter oracle magnified under the native mip + // policy; minification has its own independent physical-wood regressions. + let camera = crate::Camera { distance: 0.5, ..original.request.camera }; + let request = ImageRequest { + camera, + textures: Some(Arc::new(job::textures::RuntimeTextures::new(vec![binding]).unwrap())), + raytrace: Some(options.clone()), + ..original.request + }; + ImageTask::new(scene, request, original.cancel, options).unwrap() + }; + let camera = make(1).request.camera; + // Independent ray/plane witness: unit planar U/V and a 2x1 texture turn + // these axis-aligned world-pixel spans into a diagonal texel differential. + // Its largest scale is 0.8 texel, strictly below the magnification boundary. + assert_eq!(camera.fov, 0.0); + let plane_hit = |x, y| { + let (origin, direction) = camera.ray(x, y, 1.0, 1.0); + origin + direction * (-origin.z / direction.z) + }; + let centre = plane_hit(0.5, 0.5); + let du = plane_hit(1.5, 0.5) - centre; + let dv = plane_hit(0.5, 1.5) - centre; + assert!((du - Vec3::X * 0.4).len() < 1e-12); + assert!((dv + Vec3::Y * 0.4).len() < 1e-12); + let largest_texel_span = (du.x.abs() * 2.0).max(dv.y.abs()); + assert!(largest_texel_span < 1.0, "the independent LOD0 oracle must remain physically magnified"); + let expected = |count: u32| { + let mut mean = 0.0; + for ordinal in 0..count { + let [dx, dy] = progressive::variates(9, 0, ordinal, 0); + let (origin, direction) = camera.ray(dx, dy, 1.0, 1.0); + let point = origin + direction * (-origin.z / direction.z); + let x = point.x.rem_euclid(1.0) * 2.0 - 0.5; + let low = x.floor(); + let t = x - low; + let first = if (low as i64).rem_euclid(2) == 0 { 0.0 } else { 1.0 }; + mean += first * (1.0 - t) + (1.0 - first) * t; + } + mean /= f64::from(count); + [encode8(mean / (1.0 + mean)), 0, 0, 255] + }; + let prefixes: Vec<_> = (1..=8).map(expected).collect(); + assert!(prefixes.windows(2).any(|pair| pair[0] != pair[1]), "actual jittered world coordinates must change the prefix mean"); + let fixed_centre = [encode8(0.5 / 1.5), 0, 0, 255]; + assert!(prefixes.iter().any(|pixel| *pixel != fixed_centre), "a constant-centre lookup must not satisfy the coordinate oracle"); + let result = complete_presentation(make(8), 1); + assert_eq!(result, complete_presentation(make(8), 16384)); + for (samples, png) in result.0.iter().chain(std::iter::once(&(8, result.1.clone()))) { + assert_eq!(alpha_pixel(png), expected(*samples), "actual mapped world-point mean at prefix{samples}"); + assert_eq!(*png, complete_presentation(make(*samples), 3).1); + } +} + +#[test] +fn cpu_saved_maps_keep_explicit_fixed_spatial_sampling_and_all_primary_counts_usable() { + let expected = complete_presentation(cpu_mapped_fixture(1, false, false, true), 1); + for primary_samples in [1, 4, 16] { + let make = || { + let original = cpu_mapped_fixture(1, false, false, true); + let options = RaytraceOptions { progressive: None, primary_samples, ..original.options }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, original.cancel, options).unwrap() + }; + let intent = make(); + assert!(intent.options.progressive.is_none()); + assert_eq!(intent.options.primary_samples, primary_samples); + let actual = complete_presentation(intent, 1); + assert!(actual.0.is_empty()); + assert_eq!( + (actual.1.clone(), actual.2.clone()), + (expected.1.clone(), expected.2.clone()), + "constant mapped radiance must not depend on an authored spatial count" + ); + assert_eq!(actual, complete_presentation(make(), 16384)); + } +} + +fn composed_map_aging_fixture(samples: u32, path: bool, guides: bool, explicit: bool, half_plane: bool) -> ImageTask { + use crate::texture_input::MapRole; + let original = path_fixture(samples, 2, false); + let mut scene = original.scene.clone(); + let mapped_base = Vec3::new(cpu_map_linear(128), cpu_map_linear(64), cpu_map_linear(192)); + let final_base = (mapped_base + Vec3::new(1.0, 0.0, 0.0)) * 0.5; + let mapped_normal = Vec3::new(f64::from(128_f32 / 255.0) * 2.0 - 1.0, f64::from(128_f32 / 255.0) * 2.0 - 1.0, 1.0).normalized().unwrap(); + let mesh = Arc::make_mut(&mut scene.meshes[0].mesh); + if half_plane { + for point in &mut mesh.positions { + if point.x < 0.0 { + point.x = 0.0; + } + } + } + if explicit { + mesh.normals.fill(mapped_normal); + } + scene.bounds = mesh.bounds(); + // The original dielectric must become metal through its map BEFORE the + // Metal-only aging layer classifies it; the final layer returns a dielectric. + scene.meshes[0].surface = Some(if explicit { + OpaqueSurface::new(final_base, 0.0, 0.35, 1.0).unwrap() + } else { + OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 1.0, 1.0).unwrap() + }); + let layer = job::aging::AgingLayer { + kind: job::aging::AgingKind::Fading, + surface_class: job::aging::SurfaceClass::Metal, + roughness: 0.35, + ..solid_age() + }; + let options = RaytraceOptions { + aging: (!explicit).then(|| aging_stack(&[layer])), + path: path.then_some(job::CpuPathOptions { max_depth: 2 }), + denoise: guides, + environment: path.then_some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + lights: Some(if path { + vec![] + } else { + vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: std::f64::consts::PI }] + }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + let textures = (!explicit).then(|| { + let mut binding = cpu_map_binding(0, &scene.meshes[0].name, Some(cpu_map_png(1, 1, &[128, 64, 192, 255]))); + binding.roughness = Some(job::textures::TextureMap::new(cpu_map_png(1, 1, &[128, 128, 128, 255]), MapRole::Roughness).unwrap()); + binding.metallic = Some(job::textures::TextureMap::new(cpu_map_png(1, 1, &[255; 4]), MapRole::Metallic).unwrap()); + binding.normal = Some(job::textures::TextureMap::new(cpu_map_png(1, 1, &[128, 128, 255, 255]), MapRole::NormalOpenGl).unwrap()); + Arc::new(job::textures::RuntimeTextures::new(vec![binding]).unwrap()) + }); + let mut camera = original.request.camera; + if half_plane { + camera.target.x = 0.1; + } + let request = ImageRequest { textures, raytrace: Some(options.clone()), camera, transparent_background: true, ..original.request }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} + +#[test] +fn composed_cpu_maps_precede_aging_classification_and_share_exact_material_with_direct_path_and_guides() { + let final_base = [(cpu_map_linear(128) + 1.0) * 0.5, cpu_map_linear(64) * 0.5, cpu_map_linear(192) * 0.5]; + let normal = Vec3::new(f64::from(128_f32 / 255.0) * 2.0 - 1.0, f64::from(128_f32 / 255.0) * 2.0 - 1.0, 1.0).normalized().unwrap(); + for path in [false, true] { + let mut mapped = composed_map_aging_fixture(8, path, false, false, false); + // Stop before the first light sample so these assertions inspect the + // actual shared cached closure, not a separately recomputed material. + for _ in 0..200_000 { + if mapped.aging.first().unwrap().ready() { + break; + } + assert!(matches!(mapped.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + let before_age = mapped.maps.first().unwrap().surface().unwrap(); + assert_eq!(before_age.surface.metallic(), 1.0); + assert_eq!(before_age.surface.roughness(), f64::from(128_f32 / 255.0)); + let aged = mapped.aging.first().unwrap().surface().unwrap(); + assert_eq!(aged.surface.metallic(), 0.0, "Metal class is captured after map resolution"); + assert_eq!(aged.surface.roughness(), 0.35, "the roughness map cannot overwrite the later authored aging layer"); + for (actual, expected) in [aged.surface.base_color().x, aged.surface.base_color().y, aged.surface.base_color().z].into_iter().zip(final_base) + { + assert!((actual - expected).abs() < 1e-15); + } + assert!((aged.shading_normal - normal).len() < 1e-15, "aging preserves the complete mapped normal"); + let actual = path_mean(mapped).0; + let reference = path_mean(composed_map_aging_fixture(8, path, false, true, false)).0; + for (actual, expected) in actual.into_iter().zip(reference) { + assert!((actual - expected).abs() < 1e-12, "mapped then aged BRDF/PDF/proposal {actual} != explicit closure {expected}"); + } + if !path { + // IOR1, nonmetallic Fading layer: diffuse BRDF = colour/pi; + // normal-view pi-strength source contributes colour * mapped N.z. + for (actual, color) in actual.into_iter().zip(final_base) { + assert!((actual - color * normal.z).abs() < 1e-12); + } + } + let (guides, _) = composed_panel_guides(composed_map_aging_fixture(8, path, true, false, false)); + assert_eq!(guides.len(), 1); + assert_eq!(guides[0].body, 1, "the final dielectric must not retain the mapped smooth-metal guide classification"); + assert_eq!(guides[0].albedo, final_base.map(|v| v as f32)); + for (actual, expected) in guides[0].normal.into_iter().zip([normal.x, normal.y, normal.z]) { + assert!((f64::from(actual) - expected).abs() < 1e-7); + } + } +} + +#[test] +fn composed_cpu_maps_and_aging_keep_alpha_all_prefixes_raw_master_quanta_and_denoise_intent() { + for path in [false, true] { + for guides in [false, true] { + let actual = complete_presentation(composed_map_aging_fixture(8, path, guides, false, true), 1); + assert_eq!(actual, complete_presentation(composed_map_aging_fixture(8, path, guides, false, true), 16384)); + let reference = complete_presentation(composed_map_aging_fixture(8, path, guides, true, true), 3); + assert_eq!(actual.0, reference.0, "every mapped+aged PNG prefix equals the independently authored closure"); + assert_eq!(actual.1, reference.1); + assert_eq!(actual.2, reference.2); + let unfiltered = complete_presentation(composed_map_aging_fixture(8, path, false, false, true), 3); + assert_eq!(actual.2, unfiltered.2, "map/aging guide evaluation and denoise never change raw EXR"); + let camera = composed_map_aging_fixture(1, path, false, false, true).request.camera; + let mut covered = 0_u32; + for ordinal in 0..8 { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let (origin, direction) = camera.ray(x, y, 1.0, 1.0); + let position = origin + direction * (-origin.z / direction.z); + covered += u32::from(position.x >= 0.0); + let png = if ordinal == 7 { &actual.1 } else { &actual.0[ordinal as usize].1 }; + assert_eq!(alpha_pixel(png)[3], ((covered * 510 + ordinal + 1) / (2 * (ordinal + 1))) as u8); + assert_eq!(*png, complete_presentation(composed_map_aging_fixture(ordinal + 1, path, guides, false, true), 3).1); + } + assert!(covered > 0 && covered < 8, "the fixture exercises a real partial-coverage matte"); + let raw = native_exr_pixels(actual.2.as_deref().unwrap()); + assert_eq!(raw.get_pixel(0, 0).0[3], covered as f32 / 8.0); + } + } +} + +#[test] +fn composed_cpu_map_and_aging_reservations_add_and_cancel_before_the_first_aging_layer() { + let task = composed_map_aging_fixture(4, false, false, false, false); + let mut bare_options = task.options.clone(); + bare_options.aging = None; + let bare_request = ImageRequest { textures: None, raytrace: Some(bare_options.clone()), ..task.request.clone() }; + let bare = admit(&task.scene, &bare_request, &bare_options).unwrap(); + let map_bytes = + job::textures::cpu_cache::CpuTextureCache::required_bytes(task.request.textures.as_ref().unwrap(), &task.scene, &task.options).unwrap(); + assert_eq!( + task.admission.estimated_total_bytes - bare.estimated_total_bytes, + map_bytes + 2 * std::mem::size_of::() as u64 + super::super::aging::Task::required_bytes() + ); + assert_eq!((task.maps.capacity(), task.aging.capacity()), (1, 1)); + for path in [false, true] { + for guides in [false, true] { + for cancel in [false, true] { + let mut task = composed_map_aging_fixture(4, path, guides, false, false); + for _ in 0..200_000 { + if task.maps.first().unwrap().hit_ready() && !task.aging.first().unwrap().started() { + break; + } + task.step_with_previews(1).unwrap(); + } + assert_eq!(task.maps.first().unwrap().hit_role(), Some(4)); + assert!(!task.aging.first().unwrap().started(), "a final map role must yield before any aging mutation"); + let used = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(!task.aging.first().unwrap().started()); + assert_eq!(task.maps.first().unwrap().hit_role(), Some(4)); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + } + } + } +} + +mod adaptive_cpu_images { + use super::*; + use crate::job::adaptive::{AdaptiveSampling, SamplingReport}; + + fn policy() -> AdaptiveSampling { + AdaptiveSampling { pilot_samples: 16, min_samples: 16, relative_error: 0.0, absolute_error: 0.2, coverage_error: 0.1 } + } + fn adaptive_fixture(denoise: bool, path: bool, lens: bool) -> ImageTask { + let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + if lens { + camera.fov = 35.0_f64.to_radians(); + } + let point = |x, y| { + let (o, d) = camera.ray(x, y, 3.0, 1.0); + o + d * (-o.z / d.z) + }; + let mesh = Arc::new(Mesh { + positions: vec![point(0.0, 0.0), point(1.5, 0.0), point(1.5, 1.0), point(0.0, 1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + let bounds = mesh.bounds(); + let scene = ProductScene { + bounds, + meshes: vec![ProductMesh { + transmission: None, + name: "Adaptive analytic half-plane".into(), + mesh, + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }], + }; + let options = RaytraceOptions { + adaptive: Some(Box::new(policy())), + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 48, seed: 9 }), + denoise, + path: path.then_some(job::CpuPathOptions { max_depth: 1 }), + shadows: path, + lens: lens.then_some(job::ThinLens { aperture_radius_mm: 0.01, focus_distance_mm: 10.0 }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + emissions: Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Adaptive analytic half-plane".into(), + color: [1.0, 0.5, 0.25], + strength: 4.0, + sides: job::EmissionSides::Both, + }]), + lights: Some(Vec::new()), + ..Default::default() + }; + let request = ImageRequest { + width: 3, + height: 1, + camera, + transparent_background: true, + raytrace: Some(options.clone()), + integrator: job::Integrator::Raytrace, + ..fixture(1, 1, None).request + }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() + } + fn finish(mut task: ImageTask, quantum: usize) -> (PresentedOutput, SamplingReport) { + let mut previews = Vec::new(); + for _ in 0..500_000 { + match task.step_with_previews(quantum).unwrap() { + ImagePoll::Pending(progress) => assert!(progress.done <= progress.total), + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.take_linear_exr().is_none()); + assert!(task.sampling_report().is_none(), "pilots and unfinished production are not a final sampling report"); + previews.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + let report = task.sampling_report().expect("adaptive final report survives release of the working film"); + let exr = task.take_linear_exr(); + assert!(task.take_linear_exr().is_none()); + assert!(task.progressive.is_none(), "working film is released before final transfer"); + return ((previews, png, exr, task.work.used()), report); + } + } + } + panic!("bounded adaptive image did not finish"); + } + fn hits(pixel: u64, seed: u32, count: u32) -> u32 { + match pixel { + 0 => count, + 1 => (0..count).filter(|n| progressive::variates(seed, pixel, *n, 0)[0] < 0.5).count() as u32, + _ => 0, + } + } + fn alpha(covered: u32, samples: u32) -> u8 { + ((covered * 510 + samples) / (samples * 2)) as u8 + } + fn allocation() -> [u32; 3] { + // Independent Bernoulli sample variance, including premultiplied HDR RGB. + let covered = f64::from(hits(1, 9 ^ 0xa511_e9b3, 16)); + let fraction = covered / 16.0; + let variance = 16.0 / 15.0 * fraction * (1.0 - fraction); + let estimate = ((variance.sqrt() * 4.0 / 0.2).min(48.0_f64.sqrt()).powi(2).ceil() as u32).clamp(16, 48); + [16, estimate, 16] + } + #[test] + fn actual_adaptive_png_prefixes_discard_pilots_and_use_heterogeneous_exact_counts_for_raw_and_alpha() { + let (actual, report) = finish(adaptive_fixture(false, false, false), 1); + assert_eq!((actual.clone(), report.clone()), finish(adaptive_fixture(false, false, false), 16384)); + assert_eq!(actual.0.iter().map(|p| p.0).collect::>(), (1..64).collect::>()); + let counts = allocation(); + assert_eq!(counts, [16, 48, 16], "independent pilot variance selects different real per-pixel production budgets"); + assert_eq!((report.minimum_production_samples, report.maximum_production_samples), (16, 48)); + assert_eq!((report.production_samples, report.primary_path_evaluations), (80, 128)); + assert_eq!((report.pilot_samples_per_pixel, report.pixels_at_cap, report.transmission_strata), (16, 1, 1)); + for (absolute, png) in actual.0.iter().chain(std::iter::once(&(64, actual.1.clone()))) { + let pilot = *absolute <= 16; + let ordinal = if pilot { *absolute } else { *absolute - 16 }; + let seed = if pilot { 9 ^ 0xa511_e9b3 } else { 9 }; + let image = ::image::load_from_memory(png).unwrap().to_rgba8(); + for (pixel, &count) in counts.iter().enumerate() { + let n = if pilot { ordinal } else { ordinal.min(count) }; + let covered = hits(pixel as u64, seed, n); + let expected_rgb = if covered == 0 { [0; 3] } else { [4.0_f64, 2.0, 1.0].map(|r| encode8(r / (1.0 + r))) }; + assert_eq!( + image.get_pixel(pixel as u32, 0).0, + [expected_rgb[0], expected_rgb[1], expected_rgb[2], alpha(covered, n)], + "absolute pass {absolute}, pixel {pixel}" + ); + } + } + let exr = actual.2.unwrap(); + let tail = &exr[exr.len() - 3 * 16..]; + let channel = + |channel: usize, pixel: usize| f32::from_le_bytes(tail[(channel * 3 + pixel) * 4..(channel * 3 + pixel + 1) * 4].try_into().unwrap()); + for (pixel, &count) in counts.iter().enumerate() { + let coverage = f64::from(hits(pixel as u64, 9, count)) / f64::from(count); + for (c, scale) in [1.0, 1.0, 2.0, 4.0].into_iter().enumerate() { + assert_eq!(channel(c, pixel), (coverage * scale) as f32, "raw A,B,G,R are normalized by this pixel's production count"); + } + } + let production = hits(1, 9, 48); + let leaked_pilots = hits(1, 9 ^ 0xa511_e9b3, 16) + production; + assert_ne!(f64::from(production) / 48.0, f64::from(leaked_pilots) / 64.0, "the fixture distinguishes incorrect pilot leakage"); + } + #[test] + fn adaptive_shared_output_denoise_and_opaque_path_keep_raw_and_exact_alpha() { + let original = finish(adaptive_fixture(false, false, false), 1); + let denoised = finish(adaptive_fixture(true, false, false), 3); + assert_eq!(original.0.2, denoised.0.2, "the filter cannot change per-pixel-normalized raw production radiance"); + assert_eq!(original.0.0, denoised.0.0, "emission and partial matte are genuine filter bypasses at every pilot/production pass"); + assert_eq!(original.0.1, denoised.0.1); + let path = finish(adaptive_fixture(true, true, false), 4); + assert_eq!( + (original.0.0, original.0.1, original.0.2, original.1), + (path.0.0, path.0.1, path.0.2, path.1), + "depth-one opaque GI must consume the same adaptive primary identity and exact count plane" + ); + let lens = finish(adaptive_fixture(true, true, true), 4); + assert_eq!( + lens, + finish(adaptive_fixture(true, true, true), 1), + "actual positive aperture, guides and path transport remain independent of quantum" + ); + assert!(lens.0.2.is_some()); + } + #[test] + fn adaptive_reset_stopped_pixels_resolve_and_finishing_obey_one_work_ceiling_and_cancel() { + for point in ["reset", "stopped", "resolve", "output"] { + for cancel in [false, true] { + let mut task = adaptive_fixture(true, false, false); + for _ in 0..500_000 { + let p = task.progressive.as_ref().unwrap(); + let reached = match point { + "reset" => p.film.resetting() && p.film.reset_progress() == 1, + "stopped" => { + task.pixel == 0 + && !p.resolving + && !p.film.resetting() + && p.film.samples() == 33 + && task.output.is_empty() + && task.encoder.is_none() + } + "resolve" => p.resolving && p.resolve_pixel == 1, + _ => !task.output.is_empty(), + }; + if reached { + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + let p = task.progressive.as_ref().unwrap(); + let before = (p.film.samples(), p.film.reset_progress(), p.resolve_pixel, task.pixel); + let work = task.work.used(); + assert!(work > 0); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = work; + } + assert_eq!( + task.step_with_previews(1).err().unwrap().code, + if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }, + "{point}" + ); + let p = task.progressive.as_ref().unwrap(); + assert_eq!( + (p.film.samples(), p.film.reset_progress(), p.resolve_pixel, task.pixel), + before, + "{point}: debit/cancel must precede mutation" + ); + assert_eq!(task.work.used(), work); + assert!(task.take_linear_exr().is_none()); + assert!(task.sampling_report().is_none()); + } + } + } + #[test] + fn adaptive_last_pilot_is_finished_and_published_before_reset_can_begin() { + for stop in ["advance", "cancel", "work"] { + let mut task = adaptive_fixture(false, false, false); + let pilot = policy().pilot_samples; + let count = task.request.width as usize * task.request.height as usize; + let mut prefixes = Vec::new(); + for _ in 0..500_000 { + let p = task.progressive.as_ref().unwrap(); + if p.film.samples() == pilot && task.pixel == count && !p.resolving { + break; + } + match task.step_with_previews(1).unwrap() { + ImagePoll::Preview { samples_per_pixel, .. } => prefixes.push(samples_per_pixel), + ImagePoll::Pending(_) => {} + ImagePoll::Complete(_) => { + panic!("production cannot finish before all pilots are handed off") + } + } + } + assert_eq!(prefixes, (1..pilot).collect::>()); + assert_eq!(task.pixel, count); + assert!(task.progressive.as_ref().unwrap().film.pilot_complete()); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + let p = task.progressive.as_ref().unwrap(); + assert!(p.resolving, "the final pilot must resolve rather than reset at the pixel boundary"); + assert!(!p.film.resetting()); + assert_eq!(p.film.samples(), pilot); + assert_eq!(p.film.counts().unwrap().unwrap().pixel(0).unwrap().samples(), pilot as u16); + for _ in 0..500_000 { + match task.step_with_previews(1).unwrap() { + ImagePoll::Preview { samples_per_pixel, .. } => { + assert_eq!(samples_per_pixel, pilot, "the last pilot is published exactly once"); + prefixes.push(samples_per_pixel); + break; + } + ImagePoll::Pending(_) => {} + ImagePoll::Complete(_) => { + panic!("pilot output cannot lend the final image/master") + } + } + } + assert_eq!(prefixes, (1..=pilot).collect::>()); + assert_eq!(task.pixel, 0, "only completed PNG handoff opens the reset boundary"); + assert!(task.output.is_empty() && task.encoder.is_none()); + assert!(task.take_linear_exr().is_none() && task.sampling_report().is_none()); + let p = task.progressive.as_ref().unwrap(); + assert!(p.film.pilot_complete() && !p.film.resetting()); + let frozen: Vec<_> = (0..count) + .map(|pixel| { + let counts = p.film.counts().unwrap().unwrap().pixel(pixel).unwrap(); + (counts.samples(), counts.covered()) + }) + .collect(); + let work = task.work.used(); + if stop != "advance" { + if stop == "cancel" { + task.cancel.cancel(); + } else { + task.work.limit = work; + } + assert_eq!( + task.step_with_previews(1).err().unwrap().code, + if stop == "cancel" { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded } + ); + let p = task.progressive.as_ref().unwrap(); + assert!(p.film.pilot_complete() && !p.film.resetting()); + assert_eq!(task.pixel, 0); + assert_eq!(task.work.used(), work); + for (pixel, before) in frozen.iter().enumerate() { + let counts = p.film.counts().unwrap().unwrap().pixel(pixel).unwrap(); + assert_eq!((counts.samples(), counts.covered()), *before, "failed reset cannot discard any pilot yet"); + } + continue; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.progressive.as_ref().unwrap().film.resetting()); + assert!(task.progressive.as_ref().unwrap().film.counts().is_err(), "incomplete/reset counts must remain unavailable"); + assert_eq!(task.work.used(), work + 1, "begin reset keeps its prepaid work debit"); + for _ in 0..500_000 { + match task.step_with_previews(1).unwrap() { + ImagePoll::Preview { samples_per_pixel, .. } => { + assert_eq!(samples_per_pixel, pilot + 1); + break; + } + ImagePoll::Pending(_) => {} + ImagePoll::Complete(_) => panic!("first production pass cannot be the final"), + } + } + let p = task.progressive.as_ref().unwrap(); + assert_eq!(p.film.samples(), pilot + 1); + for pixel in 0..count { + let counts = p.film.counts().unwrap().unwrap().pixel(pixel).unwrap(); + assert_eq!(counts.samples(), 1, "independent production must discard all pilot counts"); + } + assert_eq!(p.film.counts().unwrap().unwrap().pixel(0).unwrap().covered(), 1); + assert!(task.take_linear_exr().is_none() && task.sampling_report().is_none()); + } + } + #[test] + fn ordinary_camera_film_keeps_its_original_storage_rng_and_debits_when_adaptive_is_absent() { + let task = progressive_fixture(8, 9, Some(true), 0.0); + assert!(matches!(task.progressive.as_ref().unwrap().film, super::super::super::progressive::CameraFilm::Uniform(_))); + assert_eq!(task.sampling.capacity(), 0); + assert_eq!(task.options.retained_adaptive_bytes().unwrap(), 0); + let (previews, png, work) = progressive_complete(task, 1); + assert_eq!((previews.clone(), png.clone(), work), progressive_complete(progressive_fixture(8, 9, Some(true), 0.0), 16384)); + for (n, prefix) in previews { + assert_eq!(prefix, progressive_complete(progressive_fixture(n, 9, Some(true), 0.0), 3).1); + } + assert!(std::mem::size_of::() <= 4096); + } +} + +mod composed_adaptive_map_aging_tests { + use super::*; + use crate::job::adaptive::{AdaptiveSampling, SamplingReport}; + #[derive(Debug, PartialEq)] + struct GuideFacts { + body: u32, + albedo: [f32; 3], + normal: [f32; 3], + } + #[derive(Debug, PartialEq)] + struct Completed { + previews: Vec<(u32, Vec)>, + png: Vec, + exr: Vec, + report: SamplingReport, + means: Vec<[f64; 3]>, + counts: Vec<(u16, u16)>, + guides: Vec, + work: u64, + } + fn fixture(path: bool, guides: bool, explicit: bool, adaptive: bool) -> ImageTask { + let original = composed_map_aging_fixture(32, path, guides, explicit, true); + let options = RaytraceOptions { + adaptive: adaptive.then(|| { + Box::new(AdaptiveSampling { pilot_samples: 16, min_samples: 16, relative_error: 0.0, absolute_error: 0.2, coverage_error: 0.01 }) + }), + ..original.options + }; + let request = ImageRequest { width: 3, height: 1, raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + } + fn finish(mut task: ImageTask, quantum: usize) -> Completed { + let target = task.options.preview_target().unwrap(); + let mut previews = Vec::new(); + let mut means = Vec::new(); + let mut counts = Vec::new(); + let mut guides = Vec::new(); + for _ in 0..1_000_000 { + if guides.is_empty() && task.denoise.first().is_some_and(|g| g.ready()) { + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0, "complete deterministic map/aging guides precede all pilot samples"); + guides = task + .denoise + .first() + .unwrap() + .pixels() + .unwrap() + .iter() + .map(|g| GuideFacts { body: g.body, albedo: g.albedo, normal: g.normal }) + .collect(); + } + if means.is_empty() && task.progressive.as_ref().is_some_and(|p| p.film.samples() == target) { + for index in 0..3 { + let (mean, covered, samples) = task.progressive.as_ref().unwrap().film.pixel(index).unwrap(); + means.push(mean); + counts.push((covered, samples)); + } + } + match task.step_with_previews(quantum).unwrap() { + ImagePoll::Pending(progress) => assert!(progress.done <= progress.total), + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.take_linear_exr().is_none()); + previews.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + return Completed { + previews, + png, + exr: task.take_linear_exr().unwrap(), + report: task.sampling_report().unwrap(), + means, + counts, + guides, + work: task.work.used(), + }; + } + } + } + panic!("bounded combined adaptive map/aging fixture did not finish"); + } + fn covered(camera: crate::Camera, pixel: usize, seed: u32, samples: u32) -> u32 { + (0..samples) + .filter(|ordinal| { + let [x, y] = progressive::variates(seed, pixel as u64, *ordinal, 0); + let (origin, direction) = camera.ray(pixel as f64 + x, y, 3.0, 1.0); + (origin + direction * (-origin.z / direction.z)).x >= 0.0 + }) + .count() as u32 + } + #[test] + fn combined_adaptive_maps_aging_direct_has_independent_heterogeneous_counts_alpha_raw_and_final_guide_closure() { + let camera = fixture(false, true, false, true).request.camera; + let actual = finish(fixture(false, true, false, true), 1); + assert_eq!(actual, finish(fixture(false, true, false, true), 16384)); + assert_eq!(actual.previews.iter().map(|p| p.0).collect::>(), (1..48).collect::>()); + assert_eq!(actual.counts.iter().map(|p| p.1).collect::>(), [16, 32, 16]); + assert_eq!((actual.report.production_samples, actual.report.primary_path_evaluations), (64, 112)); + assert_eq!((actual.report.minimum_production_samples, actual.report.maximum_production_samples, actual.report.pixels_at_cap), (16, 32, 1)); + let base = [(cpu_map_linear(128) + 1.0) * 0.5, cpu_map_linear(64) * 0.5, cpu_map_linear(192) * 0.5]; + let normal = Vec3::new(f64::from(128_f32 / 255.0) * 2.0 - 1.0, f64::from(128_f32 / 255.0) * 2.0 - 1.0, 1.0).normalized().unwrap(); + assert_eq!(actual.guides.iter().map(|g| g.body).collect::>(), [0, 1, 1]); + for g in actual.guides.iter().filter(|g| g.body != 0) { + assert_eq!(g.albedo, base.map(|v| v as f32)); + for (v, n) in g.normal.into_iter().zip([normal.x, normal.y, normal.z]) { + assert!((f64::from(v) - n).abs() < 1e-7); + } + } + for (absolute, png) in actual.previews.iter().chain(std::iter::once(&(48, actual.png.clone()))) { + let pilot = *absolute <= 16; + let pass = if pilot { *absolute } else { *absolute - 16 }; + let seed = if pilot { 9 ^ 0xa511_e9b3 } else { 9 }; + let image = ::image::load_from_memory(png).unwrap().to_rgba8(); + for pixel in 0..3 { + let samples = if pilot { pass } else { pass.min(u32::from(actual.counts[pixel].1)) }; + let hits = covered(camera, pixel, seed, samples); + assert_eq!( + image.get_pixel(pixel as u32, 0).0[3], + ((hits * 510 + samples) / (samples * 2)) as u8, + "pass{absolute}, pixel{pixel}: exact own-count alpha" + ); + } + } + let raw = native_exr_pixels(&actual.exr); + for pixel in 0..3 { + let samples = u32::from(actual.counts[pixel].1); + let hits = covered(camera, pixel, 9, samples); + assert_eq!(u32::from(actual.counts[pixel].0), hits); + let coverage = f64::from(hits) / f64::from(samples); + assert_eq!(raw.get_pixel(pixel as u32, 0).0[3], coverage as f32); + for (channel, color) in base.into_iter().enumerate() { + assert!( + (actual.means[pixel][channel] - color * normal.z * coverage).abs() < 1e-12, + "independent normal-view Lambert oracle after maps then fading" + ); + assert_eq!( + raw.get_pixel(pixel as u32, 0).0[channel], + (color * normal.z * coverage) as f32, + "raw uses each production denominator before PNG quantization" + ); + } + } + let pilot = covered(camera, 1, 9 ^ 0xa511_e9b3, 16); + let production = covered(camera, 1, 9, 32); + assert_ne!(f64::from(production) / 32.0, f64::from(pilot + production) / 48.0, "fixture detects pilot leakage"); + let reference = finish(fixture(false, true, true, true), 3); + assert_eq!( + (actual.previews, actual.png, actual.exr, actual.report, actual.counts), + (reference.previews, reference.png, reference.exr, reference.report, reference.counts), + "complete mapped-then-aged output equals independently authored closure" + ); + } + #[test] + fn combined_adaptive_maps_aging_gi_filter_and_unfiltered_raw_keep_all_prefixes_and_pilot_discard() { + for path in [false, true] { + let actual = finish(fixture(path, true, false, true), 1); + assert_eq!(actual, finish(fixture(path, true, false, true), 16384)); + let reference = finish(fixture(path, true, true, true), 3); + assert_eq!( + (actual.previews.clone(), actual.png.clone(), actual.exr.clone(), actual.report.clone(), actual.counts.clone()), + (reference.previews, reference.png, reference.exr, reference.report, reference.counts) + ); + let unfiltered = finish(fixture(path, false, false, true), 3); + assert_eq!(actual.exr, unfiltered.exr, "guides/filter must not alter normalized adaptive raw GI radiance"); + assert_eq!(actual.report, unfiltered.report, "guide preparation cannot contribute pilots or production samples"); + assert_eq!(actual.counts, unfiltered.counts); + } + let adaptive = finish(fixture(false, false, false, true), 1); + let ordinary = complete_presentation(fixture(false, false, false, false), 3); + assert_eq!( + adaptive.exr, + ordinary.2.unwrap(), + "constant full-covered pixels and independently allocated partial pixels match the original production stream, never pilot+production averaging" + ); + } + #[test] + fn combined_adaptive_maps_aging_bytes_add_to_existing_leases_and_cancel_before_production_aging_mutates() { + let task = fixture(false, false, false, true); + let mut plain = task.options.clone(); + plain.adaptive = None; + let request = ImageRequest { raytrace: Some(plain.clone()), ..task.request.clone() }; + let baseline = admit(&task.scene, &request, &plain).unwrap(); + let progressive = task.options.progressive.unwrap(); + let film_delta = crate::film::adaptive::AdaptiveCameraFilm::required_bytes( + 3, + 1, + progressive, + *task.options.adaptive.as_deref().unwrap(), + task.options.budget, + ) + .unwrap() + - crate::film::primary::PrimaryFilm::required_bytes(3, 1, progressive, task.options.budget).unwrap(); + let extra = film_delta + 2 * std::mem::size_of::() as u64 + std::mem::size_of::() as u64; + assert_eq!( + task.admission.estimated_total_bytes - baseline.estimated_total_bytes, + extra, + "maps+aging resources remain additive; no hidden count or snapshot plane" + ); + assert_eq!(task.admission.preparation_bytes - baseline.preparation_bytes, extra); + assert_eq!((task.maps.capacity(), task.aging.capacity(), task.sampling.capacity()), (1, 1, 1)); + for path in [false, true] { + for guides in [false, true] { + for cancel in [false, true] { + let mut task = fixture(path, guides, false, true); + let mut reached = false; + for _ in 0..1_000_000 { + let film = &task.progressive.as_ref().unwrap().film; + if film.samples() >= 16 + && !film.resetting() + && task.maps.first().unwrap().hit_ready() + && !task.aging.first().unwrap().started() + { + reached = true; + break; + } + assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_))); + } + assert!(reached, "stop after a production map role, not an earlier pilot/guide state"); + assert_eq!(task.maps.first().unwrap().hit_role(), Some(4)); + let used = task.work.used(); + let samples = task.progressive.as_ref().unwrap().film.samples(); + let pixel = task.pixel; + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(!task.aging.first().unwrap().started()); + assert_eq!(task.maps.first().unwrap().hit_role(), Some(4)); + assert_eq!((task.progressive.as_ref().unwrap().film.samples(), task.pixel), (samples, pixel)); + assert!(task.take_linear_exr().is_none()); + assert!(task.sampling_report().is_none()); + } + } + } + } +} + +fn cpu_general_glass_fixture(samples: u32, nested: bool, ior: f64) -> ImageTask { + let outer = dielectric::tests::box_body(2.0); + let mut meshes = vec![outer]; + if nested { + let mut inner = dielectric::tests::box_body(1.0); + inner.name = "Inner glass".into(); + for p in &mut Arc::make_mut(&mut inner.mesh).positions { + p.x *= 0.5; + p.y *= 0.5; + p.z += 0.5; + } + meshes.push(inner); + } + let scene = ProductScene { bounds: meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())), meshes }; + let dielectrics = scene + .meshes + .iter() + .enumerate() + .map(|(body_index, body)| job::DielectricOptions { + body_index, + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedMesh, + ior, + absorption_per_mm: if body_index == 0 { [0.1, 0.2, 0.0] } else { [0.3, 0.0, 0.4] }, + thickness_mm: 0.0, + shadow_transmission: false, + subsurface: None, + }) + .collect(); + let options = RaytraceOptions { + path: Some(job::CpuPathOptions { max_depth: 16 }), + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 9 }), + budget: job::CpuBudget::Studio, + dielectrics, + lights: Some(vec![]), + shadows: true, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera = crate::Camera { distance: 1.0, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, ..request.camera }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +#[test] +fn cpu_general_glass_nested_index_matched_media_have_independent_physical_beer_lengths_and_raw_master() { + let task = cpu_general_glass_fixture(8, true, 1.0); + let (actual, _) = path_mean(task); + // Two outer segments of0.5mm replace, not add to, the1mm inner medium. + let expected = [(-0.4_f64).exp(), (-0.2_f64).exp(), (-0.4_f64).exp()]; + for (a, e) in actual.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "{a} vs physical nested Beer{e}"); + } + let output = complete_presentation(cpu_general_glass_fixture(8, true, 1.0), 1); + assert_eq!(output, complete_presentation(cpu_general_glass_fixture(8, true, 1.0), 16384)); + for (samples, png) in &output.0 { + assert_eq!(*png, complete_presentation(cpu_general_glass_fixture(*samples, true, 1.0), 3).1); + } + let raw = native_exr_pixels(output.2.as_deref().unwrap()); + assert_eq!(raw.get_pixel(0, 0).0, [expected[0] as f32, expected[1] as f32, expected[2] as f32, 1.0]); +} +#[test] +fn cpu_general_glass_fresnel_delta_prefixes_match_an_independent_normal_slab_counter_estimator() { + let samples = 64; + let mut expected = [0.0; 3]; + for ordinal in 0..samples { + let mut inside = false; + let mut throughput = [1.0; 3]; + let mut result = [0.0; 3]; + for depth in 0..15_u64 { + if inside { + for (t, sigma) in throughput.iter_mut().zip([0.1_f64, 0.2, 0.0]) { + *t *= (-sigma * 2.0).exp(); + } + } + let [branch, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_4000 + depth * 0x10000); + if branch < 0.04 { + if !inside { + result = throughput; + break; + } + } else if inside { + for t in &mut throughput { + *t *= 9.0 / 4.0; + } + result = throughput; + break; + } else { + for t in &mut throughput { + *t *= 4.0 / 9.0; + } + inside = true; + } + } + for (sum, value) in expected.iter_mut().zip(result) { + *sum += value / f64::from(samples); + } + } + let (actual, _) = path_mean(cpu_general_glass_fixture(samples, false, 1.5)); + for (a, e) in actual.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "actual film{a} vs independent Fresnel/Beer path{e}"); + } + let output = complete_presentation(cpu_general_glass_fixture(samples, false, 1.5), 1); + assert_eq!(output, complete_presentation(cpu_general_glass_fixture(samples, false, 1.5), 16384)); + for (samples, png) in &output.0 { + assert_eq!(*png, complete_presentation(cpu_general_glass_fixture(*samples, false, 1.5), 7).1); + } +} +#[test] +fn cpu_general_closed_octahedron_is_consumed_by_real_path_film_instead_of_the_box_preview() { + let base = cpu_general_glass_fixture(4, false, 1.0); + let mut scene = base.scene.clone(); + let p = vec![Vec3::X, -Vec3::X, Vec3::Y, -Vec3::Y, Vec3::Z, -Vec3::Z]; + let mut triangles = vec![]; + let ring = [0, 2, 1, 3]; + for i in 0..4 { + let a = ring[i]; + let b = ring[(i + 1) % 4]; + triangles.extend([[a, b, 4], [b, a, 5]]); + } + scene.meshes[0].mesh = Arc::new(Mesh { positions: p, triangles, ..Default::default() }); + scene.bounds = scene.meshes[0].mesh.bounds(); + let mut options = base.options.clone(); + options.dielectrics[0].absorption_per_mm = [0.0; 3]; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + assert!(dielectric::certify(&scene, &dielectric::tests::input(job::DielectricBoundary::ClosedBox)).is_err()); + assert_eq!(path_mean(ImageTask::new(scene, request, CancelToken::default(), options).unwrap()).0, [1.0; 3]); +} +#[test] +fn cpu_general_glass_preparation_is_cancellable_prepaid_and_never_exports_a_partial_boundary() { + for cancel in [false, true] { + let mut task = cpu_general_glass_fixture(4, true, 1.0); + let weak = Arc::downgrade(&task.scene.meshes[0].mesh); + let bytes = super::super::glass_mesh::Task::required_bytes(&task.scene, &task.options).unwrap(); + assert!(bytes > 0 && task.admission.preparation_bytes >= bytes); + while task.work.used() < 100 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(task.glass.first().is_some_and(|g| !g.ready())); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + if cancel { + task.cancel.cancel(); + } else { + task.work = WorkBudget::new(1).unwrap(); + task.step_with_previews(1).unwrap(); + } + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, if cancel { job::ErrorCode::Cancelled } else { job::ErrorCode::LimitExceeded }); + assert!(task.take_linear_exr().is_none()); + drop(task); + assert!(weak.upgrade().is_none()); + } +} + +#[test] +fn cpu_general_glass_delta_reaches_real_hdr_and_area_emitter_without_losing_their_pdf_mass() { + let expected_beer = [(-0.2_f64).exp(), (-0.4_f64).exp(), 1.0]; + for area in [false, true] { + let base = cpu_general_glass_fixture(4, false, 1.0); + let mut options = base.options.clone(); + options.environment = None; + if area { + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, -2.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, 2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + } + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let input = if area { + None + } else { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + Some(crate::lighting::environment_input::EnvironmentInput::new(crate::lighting::HdrSource::new(bytes).unwrap(), 0.0, 1.0, 16).unwrap()) + }; + let task = ImageTask::new_with_environment(base.scene.clone(), request, CancelToken::default(), options, input).unwrap(); + let output = complete_presentation(task, 1); + let raw = native_exr_pixels(output.2.as_deref().unwrap()); + let scale = if area { 2.0 } else { 1.0 }; + assert_eq!( + raw.get_pixel(0, 0).0, + [(expected_beer[0] * scale) as f32, (expected_beer[1] * scale * 0.5) as f32, (expected_beer[2] * scale * 0.25) as f32, 1.0] + ); + } +} +fn cpu_glass_vertical_sheet_fixture(samples: u32, depth: u8) -> ImageTask { + let base = path_fixture(samples, depth, false); + let mut scene = base.scene.clone(); + // Keep the opaque receiver compact so the independent primary point does not + // inherit cancellation from a million-millimetre numerical test plane. + for p in &mut Arc::make_mut(&mut scene.meshes[0].mesh).positions { + p.x *= 0.0001; + p.y *= 0.0001; + } + let sheet = ProductMesh { + transmission: None, + name: "Vertical sheet".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(2.0, -10.0, 1.0), Vec3::new(2.0, -10.0, 5.0), Vec3::new(2.0, 10.0, 5.0), Vec3::new(2.0, 10.0, 1.0)], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: vec![], + }; + scene.meshes.push(sheet); + 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 { + body_index: 1, + body_name: "Vertical sheet".into(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + shadow_transmission: true, + subsurface: None, + }]; + options.output = Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +#[test] +fn cpu_glass_thin_ordered_visibility_and_bsdf_chains_match_independent_sample_count_mis() { + use std::f64::consts::{PI, TAU}; + let samples = 128; + let sheet_probability = |cosine: f64| { + let ct = (1.0 - (1.0 - cosine * cosine) / 2.25).sqrt(); + let fs = ((cosine - 1.5 * ct) / (cosine + 1.5 * ct)).powi(2); + let fp = ((1.5 * cosine - ct) / (1.5 * cosine + ct)).powi(2); + let r = 0.5 * (2.0 * fs / (1.0 + fs) + 2.0 * fp / (1.0 + fp)); + (r, 1.0 - r) + }; + let hit_sheet = |p: Vec3, d: Vec3| { + if d.x <= 0.0 { + return false; + } + let t = (2.0 - p.x) / d.x; + let q = p + d * t; + t > 0.0 && q.y >= -10.0 && q.y <= 10.0 && q.z >= 1.0 && q.z <= 5.0 + }; + for source_count in [1_u32, 4, 16, 64] { + for depth in [2, 3] { + let mut task = cpu_glass_vertical_sheet_fixture(samples, depth); + if source_count > 1 { + let mut options = task.options.clone(); + options.environment = None; + let request = ImageRequest { raytrace: Some(options.clone()), ..task.request.clone() }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 128, 128, 129]); + } + let environment = crate::lighting::environment_input::EnvironmentInput::new( + crate::lighting::HdrSource::new(bytes).unwrap(), + 0.0, + 1.0, + source_count, + ) + .unwrap(); + task = ImageTask::new_with_environment(task.scene.clone(), request, CancelToken::default(), options, Some(environment)).unwrap(); + } + while task.bvh.is_none() { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + let prepared = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: &task.scene }; + let mut diagnostic = WorkBudget::new(100_000).unwrap(); + let mut expected = 0.0; + let mut transmitted = 0; + let mut reflected = 0; + let mut connected = 0; + for ordinal in 0..samples { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let ray = primary_ray(&task.request, x, y, task.clip).unwrap(); + let hit = prepared.resolve_hit(ray, prepared.bvh.closest_hit(&ray, &mut diagnostic, &task.cancel).unwrap().unwrap()).unwrap(); + assert_eq!(hit.body_index, 0, "primary must see the opaque receiver, not the optical test panel"); + assert_eq!(hit.geometric_normal, Vec3::Z); + let p = hit.position; + let light_pdf = f64::from(source_count) / (4.0 * PI); + let side = match source_count { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + for source_sample in 0..source_count { + let [u, v] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000 + u64::from(source_sample)); + let u = ((f64::from(source_sample / side) + u) / f64::from(side)).max(0.0_f64.next_up()).min(1.0_f64.next_down()); + let v = ((f64::from(source_sample % side) + v) / f64::from(side)).max(0.0_f64.next_up()).min(1.0_f64.next_down()); + assert!(u > 0.0 && u < 1.0 && v > 0.0 && v < 1.0); + let z = 1.0 - 2.0 * u; + let r = (1.0 - z * z).sqrt(); + let light = Vec3::new(r * (TAU * v).cos(), r * (TAU * v).sin(), z); + if z > 0.0 { + let bsdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + let t = if hit_sheet(p, light) { + connected += 1; + sheet_probability(light.x).1 + } else { + 1.0 + }; + let competitor = if depth == 2 && t != 1.0 { 0.0 } else { bsdf * t }; + expected += + 2.0 * z * t * (light_pdf * light_pdf / (light_pdf * light_pdf + competitor * competitor)) / f64::from(source_count); + } + } + let [component, u] = progressive::variates(9, 0, ordinal, 0x5041_5448_3000); + let [v, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_3001); + let z = if component < 0.5 { (1.0 - u).sqrt() } else { 1.0 - 2.0 * u }; + if z <= 0.0 { + continue; + } + let r = (1.0 - z * z).sqrt(); + let direction = Vec3::new(r * (TAU * v).cos(), r * (TAU * v).sin(), z); + let pdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + let weight = if hit_sheet(p, direction) { + if depth == 2 { + continue; + } + let (reflection, transmission) = sheet_probability(direction.x); + let [branch, _] = progressive::variates(9, 0, ordinal, 0x5041_5449_4000); + if branch < reflection { + reflected += 1; + 1.0 + } else { + transmitted += 1; + (pdf * transmission).powi(2) / ((pdf * transmission).powi(2) + light_pdf * light_pdf) + } + } else { + pdf * pdf / (pdf * pdf + light_pdf * light_pdf) + }; + expected += 0.5 * z / (PI * pdf) * weight; + } + assert!(connected > 0, "real NEE connections must cross the sheet"); + if depth == 3 { + assert!(transmitted > 0 && reflected > 0, "both actual dielectric branches need fixed-seed coverage"); + } + expected /= f64::from(samples); + let (actual, _) = path_mean(task); + for a in actual { + assert!((a - expected).abs() < 1e-11, "depth{depth}: actual{a} vs independent sheet/BSDF/NEE{expected}"); + } + } + } +} + +#[test] +fn cpu_general_glass_keeps_an_opaque_surface_at_its_exit_instead_of_skipping_the_contact() { + let base = cpu_general_glass_fixture(4, false, 1.0); + let mut scene = base.scene.clone(); + let receiver = ProductMesh { + transmission: None, + name: "Opaque contact".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]], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap()), + faces: vec![], + }; + scene.meshes.push(receiver); + let mut options = base.options.clone(); + options.environment = None; + options.emissions = Some(vec![job::SurfaceEmission { + body_index: 1, + body: "Opaque contact".into(), + color: [1.0, 0.5, 0.25], + strength: 2.0, + sides: job::EmissionSides::Both, + }]); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mean = path_mean(ImageTask::new(scene, request, CancelToken::default(), options).unwrap()).0; + let expected = [2.0 * (-0.2_f64).exp(), (-0.4_f64).exp(), 0.5]; + for (a, e) in mean.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "opaque material at glass exit: {a} vs Beer-scaled emission{e}"); + } +} + +#[test] +fn cpu_general_glass_adaptive_pilots_keep_production_fresnel_ordinals_raw_and_filtered_matte_identical() { + let build = |adaptive: bool, pilot_seed: bool| { + let base = cpu_general_glass_fixture(16, false, 2.5); + let mut options = base.options.clone(); + options.denoise = true; + if adaptive { + options.adaptive = Some(Box::new(job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })); + } + if pilot_seed { + options.progressive.as_mut().unwrap().seed ^= 0xa511_e9b3; + } + let request = ImageRequest { transparent_background: true, raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + let reference = complete_presentation(build(false, false), 1); + let pilot = complete_presentation(build(false, true), 1); + assert_ne!(reference.2, pilot.2, "the real Fresnel/Beer fixture must distinguish independent pilot radiance"); + let run = |quantum| { + let mut task = build(true, false); + let mut previews = 0; + for _ in 0..2_000_000 { + match task.step_with_previews(quantum).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { .. } => { + previews += 1; + assert!(task.take_linear_exr().is_none()); + } + ImagePoll::Complete(png) => { + let raw = task.take_linear_exr().unwrap(); + let report = task.sampling_report().unwrap(); + return (png, raw, previews, report, task.work.used()); + } + } + } + panic!("bounded adaptive glass producer did not complete") + }; + let actual = run(1); + assert_eq!(actual, run(16384)); + assert_eq!(actual.0, reference.1); + assert_eq!(actual.1, reference.2.unwrap()); + assert_eq!(actual.2, 31); + assert_eq!((actual.3.production_samples, actual.3.primary_path_evaluations, actual.3.pilot_samples_per_pixel), (16, 32, 16)); + let mut cancelled = build(true, false); + let mut saw_preview = false; + for _ in 0..200_000 { + if matches!(cancelled.step_with_previews(1).unwrap(), ImagePoll::Preview { .. }) { + saw_preview = true; + break; + } + } + assert!(saw_preview, "cancel must interrupt actual glass sampling after a completed pilot image"); + assert!(cancelled.take_linear_exr().is_none()); + cancelled.cancel.cancel(); + assert_eq!(cancelled.step_with_previews(1).err().unwrap().code, job::ErrorCode::Cancelled); + assert!(cancelled.take_linear_exr().is_none()); +} + +fn cpu_inside_glass_fixture(samples: u32, nested: bool, endpoint: u8, lens: Option) -> ImageTask { + let base = cpu_general_glass_fixture(samples, nested, 1.0); + let mut scene = base.scene.clone(); + let mut options = base.options.clone(); + options.lens = lens; + if endpoint != 0 { + let z = if endpoint == 1 { 0.75 } else { 0.6 }; + let body = scene.meshes.len(); + scene.meshes.push(ProductMesh { + transmission: None, + name: "Inside opaque".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-3.0, -3.0, z), Vec3::new(3.0, -3.0, z), Vec3::new(3.0, 3.0, z), Vec3::new(-3.0, 3.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap()), + faces: vec![], + }); + options.environment = None; + if endpoint == 1 { + options.emissions = Some(vec![job::SurfaceEmission { + body_index: body, + body: "Inside opaque".into(), + color: [1.0, 0.5, 0.25], + strength: 2.0, + sides: job::EmissionSides::Both, + }]); + } else { + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 0.75], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, 2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + } + } + let camera = crate::Camera { + target: Vec3::new(0.0, 0.0, 0.5), + distance: 0.5, + fov: 0.6, + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + roll: 0.0, + ..base.request.camera + }; + let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +fn inside_master_pixel(master: &[u8]) -> [f32; 4] { + assert_eq!(&master[..4], &[0x76, 0x2f, 0x31, 0x01]); + // Every caller owns a1x1 native, uncompressed, FLOAT A/B/G/R master. + let tail = &master[master.len() - 16..]; + let f = |i| f32::from_le_bytes(tail[i..i + 4].try_into().unwrap()); + [f(12), f(8), f(4), f(0)] +} +#[test] +fn cpu_inside_glass_starts_beer_at_the_physical_eye_before_opaque_or_analytic_emission() { + let samples = 16; + for nested in [false, true] { + for endpoint in [0, 1, 2] { + let mut task = cpu_inside_glass_fixture(samples, nested, endpoint, None); + let camera = task.request.camera; + while task.bvh.is_none() { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + if endpoint != 0 { + let prepared = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: &task.scene }; + let mut diagnostic = WorkBudget::new(100_000).unwrap(); + let ray = primary_ray(&task.request, 0.5, 0.5, task.clip).unwrap(); + let hit = prepared.resolve_hit(ray, prepared.bvh.closest_hit(&ray, &mut diagnostic, &task.cancel).unwrap().unwrap()).unwrap(); + assert_eq!( + hit.body_name, "Inside opaque", + "the closest geometry must precede the Glass exit, so first-hit medium guessing cannot prove this case" + ); + assert_eq!(hit.position.z, if endpoint == 1 { 0.75 } else { 0.6 }); + } + let mut expected = [0.0; 3]; + for ordinal in 0..samples { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let d = camera.ray(x, y, 1.0, 1.0).1; + let cosine = -d.z; + assert!(cosine > 0.9); + for (channel, sum) in expected.iter_mut().enumerate() { + let outer = [0.1_f64, 0.2, 0.0][channel]; + let inner = if nested { [0.3_f64, 0.0, 0.4][channel] } else { outer }; + let optical = if endpoint == 0 { if nested { 0.5 * (outer + inner) } else { outer } } else { 0.25 * inner }; + let radiance = if endpoint == 0 { 1.0 } else { [2.0, 1.0, 0.5][channel] }; + *sum += radiance * (-optical / cosine).exp() / f64::from(samples); + } + } + let actual = path_mean(task).0; + for (a, e) in actual.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "nested={nested} endpoint={endpoint}: physical-eye Beer {a} vs{e}"); + } + } + } +} +#[test] +fn cpu_inside_glass_hdr_png_prefixes_quanta_raw_and_independent_production_are_stable() { + let build = |samples| { + let base = cpu_inside_glass_fixture(samples, true, 0, None); + let mut options = base.options.clone(); + options.environment = None; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + let input = crate::lighting::environment_input::EnvironmentInput::new(crate::lighting::HdrSource::new(bytes).unwrap(), 0.0, 1.0, 16).unwrap(); + ImageTask::new_with_environment(base.scene.clone(), request, CancelToken::default(), options, Some(input)).unwrap() + }; + let actual = complete_presentation(build(7), 1); + assert_eq!(actual, complete_presentation(build(7), 16384)); + for (n, png) in &actual.0 { + assert_eq!(*png, complete_presentation(build(*n), 3).1); + } + let camera = build(7).request.camera; + let mut expected = [0.0; 3]; + for ordinal in 0..7 { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let c = -camera.ray(x, y, 1.0, 1.0).1.z; + for (channel, sum) in expected.iter_mut().enumerate() { + *sum += [1.0, 0.5, 0.25][channel] * (-[0.2_f64, 0.1, 0.2][channel] / c).exp() / 7.0; + } + } + assert_eq!(inside_master_pixel(actual.2.as_deref().unwrap()), [expected[0] as f32, expected[1] as f32, expected[2] as f32, 1.0]); +} +#[test] +fn cpu_inside_glass_total_internal_reflection_retains_the_initial_medium_until_the_finite_depth_limit() { + let base = cpu_inside_glass_fixture(16, false, 0, None); + let mut options = base.options.clone(); + options.dielectrics[0].ior = 1.5; + options.dielectrics[0].absorption_per_mm = [0.0; 3]; + let mut camera = base.request.camera; + camera.fov = 0.2; + camera.yaw = std::f64::consts::FRAC_PI_4; + camera.pitch = (1.0 / 3.0_f64.sqrt()).asin(); + camera.distance = 0.25; + camera.target = Vec3::new(0.0, 0.0, 1.0) - camera.back() * camera.distance; + for ordinal in 0..16 { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let d = camera.ray(x, y, 1.0, 1.0).1; + assert!( + [d.x, d.y, d.z].into_iter().all(|v| v.abs() < (1.0 - 1.0 / 2.25_f64).sqrt()), + "all axis-face encounters are analytically above the critical angle" + ); + } + let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() }; + assert_eq!(path_mean(ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap()).0, [0.0; 3]); +} +#[test] +fn cpu_inside_glass_refuses_actual_near_clip_crossings_for_eye_and_pupil_without_publishing_a_frame() { + for lens in [None, Some(job::ThinLens { aperture_radius_mm: 0.1, focus_distance_mm: 2.0 })] { + let base = cpu_inside_glass_fixture(4, false, 0, lens); + let mut request = base.request.clone(); + let eye = Vec3::new(0.0, 0.0, 0.0005); + request.camera.target = eye - request.camera.back() * request.camera.distance; + let mut task = ImageTask::new(base.scene.clone(), request, CancelToken::default(), base.options.clone()).unwrap(); + let mut failure = None; + for _ in 0..100_000 { + match task.step_with_previews(1) { + Err(e) => { + failure = Some(e); + break; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("near crossing must not publish any prefix or master"), + } + } + let error = failure.expect("actual near-clip crossing must terminate"); + assert!(error.message.contains("near clipping"), "{error}"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + } +} +#[test] +fn cpu_inside_glass_origin_state_is_prepaid_reused_and_cancelled_before_partial_medium_use() { + let mut task = cpu_inside_glass_fixture(4, true, 1, None); + let with_preparation = task.admission.preparation_bytes; + let with_total = task.admission.estimated_total_bytes; + let mut plain = task.options.clone(); + plain.dielectrics = vec![]; + let request = ImageRequest { raytrace: Some(plain.clone()), ..task.request.clone() }; + let without = admit(&task.scene, &request, &plain).unwrap(); + let expected = task.options.retained_dielectric_bytes().unwrap() + + task.request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + + super::super::glass_mesh::Task::required_bytes(&task.scene, &task.options).unwrap() + + std::mem::size_of::() as u64 + + super::super::origin::Task::required_bytes(); + assert_eq!(with_preparation - without.preparation_bytes, expected); + assert_eq!(with_total - without.estimated_total_bytes, expected); + let mut origin_steps = 0; + for _ in 0..100_000 { + let classifying = task.path.first().is_some_and(|s| s.stage_name() == "origin"); + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if classifying { + assert_eq!(task.work.used() - before, 1); + origin_steps += 1; + } + if origin_steps >= 5 { + break; + } + } + assert!(origin_steps >= 5); + let info = task.path.first().unwrap().origin_slot_info(); + assert_eq!((info.0, info.1), (1, 1)); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + task.cancel.cancel(); + assert_eq!(task.step_with_previews(1).err().unwrap().code, job::ErrorCode::Cancelled); + assert_eq!(task.path.first().unwrap().origin_slot_info(), info); + assert!(task.take_linear_exr().is_none()); + let mut outside = cpu_general_glass_fixture(4, false, 1.0); + while outside.progressive.as_ref().unwrap().film.samples() == 0 { + outside.step_with_previews(1).unwrap(); + } + assert_eq!(outside.path.first().unwrap().origin_slot_info(), (0, 0, false), "established outside/orthographic origins allocate no classifier"); +} + +fn cpu_mixed_pupil_glass_fixture(samples: u32, boundary: bool) -> ImageTask { + let lens = job::ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 2.0 }; + let base = cpu_inside_glass_fixture(samples, false, 0, Some(lens)); + let mut scene = base.scene.clone(); + let mut camera = base.request.camera; + camera.target.x = 0.25; + let right = if boundary { + let [u, v] = progressive::variates(9, 0, 0, 0x4c454e53); + let (r, up, _) = camera.basis(); + (camera.eye() + (r * (std::f64::consts::TAU * v).cos() + up * (std::f64::consts::TAU * v).sin()) * (lens.aperture_radius_mm * u.sqrt())).x + } else { + 0.0 + }; + for p in &mut Arc::make_mut(&mut scene.meshes[0].mesh).positions { + p.x = if p.x > 0.0 { right } else { right - 10.0 }; + } + scene.bounds = scene.meshes[0].mesh.bounds(); + let request = ImageRequest { camera, transparent_background: true, raytrace: Some(base.options.clone()), ..base.request.clone() }; + ImageTask::new(scene, request, CancelToken::default(), base.options.clone()).unwrap() +} +#[test] +fn cpu_glass_lens_classifies_each_real_pupil_and_keeps_analytic_coverage_beer_prefixes_and_raw() { + let samples = 16; + let mut task = cpu_mixed_pupil_glass_fixture(samples, false); + let camera = task.request.camera; + let lens = task.options.lens.unwrap(); + let (right, up, back) = camera.basis(); + let mut expected = [0.0; 3]; + let mut hits = 0; + let mut inside = 0; + let mut outside = 0; + for ordinal in 0..samples { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let [u, v] = progressive::variates(9, 0, ordinal, 0x4c454e53); + let displacement = + (right * (std::f64::consts::TAU * v).cos() + up * (std::f64::consts::TAU * v).sin()) * (lens.aperture_radius_mm * u.sqrt()); + let origin = camera.eye() + displacement; + let pinhole = camera.ray(x, y, 1.0, 1.0).1; + let aimed = pinhole * (lens.focus_distance_mm / pinhole.dot(-back)) - displacement; + let direction = aimed / aimed.len(); + if origin.x < 0.0 { + inside += 1; + } else { + outside += 1; + } + let mut enter = f64::NEG_INFINITY; + let mut exit = f64::INFINITY; + for (p, d, lo, hi) in [(origin.x, direction.x, -10.0, 0.0), (origin.y, direction.y, -10.0, 10.0), (origin.z, direction.z, 0.0, 2.0)] { + if d == 0.0 { + if p < lo || p > hi { + exit = f64::NEG_INFINITY; + break; + } + } else { + let a = (lo - p) / d; + let b = (hi - p) / d; + enter = enter.max(a.min(b)); + exit = exit.min(a.max(b)); + } + } + let start = enter.max(0.0); + if exit > start { + if enter > 0.0 { + assert!(enter > 0.01, "outside pupil must not cross a boundary in its clipped near segment"); + } + assert!(exit > 0.01); + hits += 1; + let length = exit - start; + for (sum, sigma) in expected.iter_mut().zip([0.1_f64, 0.2, 0.0]) { + *sum += (-sigma * length).exp() / f64::from(samples); + } + } + } + assert!(inside > 0 && outside > 0 && hits < samples, "the real aperture must exercise both initial media and genuine misses"); + while task.progressive.as_ref().unwrap().film.samples() != samples { + task.step_with_previews(1).unwrap(); + } + let (mean, covered, n) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!((u32::from(covered), u32::from(n)), (hits, samples)); + for (a, e) in mean.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "per-pupil analytic Beer{a} vs{e}"); + } + let actual = complete_presentation(cpu_mixed_pupil_glass_fixture(samples, false), 1); + assert_eq!(actual, complete_presentation(cpu_mixed_pupil_glass_fixture(samples, false), 16384)); + for (n, png) in &actual.0 { + assert_eq!(*png, complete_presentation(cpu_mixed_pupil_glass_fixture(*n, false), 3).1); + } + assert_eq!( + inside_master_pixel(actual.2.as_deref().unwrap()), + [expected[0] as f32, expected[1] as f32, expected[2] as f32, hits as f32 / samples as f32] + ); +} +#[test] +fn cpu_glass_lens_refuses_an_actual_pupil_on_a_boundary_instead_of_guessing_air() { + let mut task = cpu_mixed_pupil_glass_fixture(4, true); + let mut failure = None; + for _ in 0..100_000 { + match task.step_with_previews(1) { + Err(e) => { + failure = Some(e); + break; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("a boundary pupil must not publish an image"), + } + } + assert!(failure.expect("exact pupil contact must terminate").message.contains("exactly on")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); +} + +#[test] +fn cpu_inside_glass_adaptive_reuses_the_origin_slot_but_discards_pilot_medium_and_lens_samples() { + let build = |adaptive: bool, pilot: bool| { + let base = cpu_mixed_pupil_glass_fixture(16, false); + let mut options = base.options.clone(); + if adaptive { + options.adaptive = Some(Box::new(job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })); + } + if pilot { + options.progressive.as_mut().unwrap().seed ^= 0xa511_e9b3; + } + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + let reference = complete_presentation(build(false, false), 1); + let pilot = complete_presentation(build(false, true), 1); + assert_ne!(reference.2, pilot.2, "the physical pupil fixture must expose pilot leakage"); + let actual = complete_presentation(build(true, false), 1); + assert_eq!(actual, complete_presentation(build(true, false), 16384)); + assert_eq!(actual.0.len(), 31); + assert_eq!(actual.1, reference.1); + assert_eq!(actual.2, reference.2); +} +#[test] +fn cpu_inside_glass_origin_slot_keeps_exact_capacity_and_no_sample_commit_on_work_exhaustion() { + let mut task = cpu_inside_glass_fixture(4, true, 0, None); + for _ in 0..100_000 { + if task.path.first().is_some_and(|s| s.stage_name() == "origin" && !s.origin_slot_info().2) { + break; + } + task.step_with_previews(1).unwrap(); + } + assert_eq!(task.path.first().unwrap().origin_slot_info(), (1, 1, false)); + let before = task.work.used(); + task.work.limit = before; + assert_eq!(task.step_with_previews(1).err().unwrap().code, job::ErrorCode::LimitExceeded); + assert_eq!(task.work.used(), before); + assert_eq!(task.path.first().unwrap().origin_slot_info(), (1, 1, false)); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + let mut reused = cpu_inside_glass_fixture(4, true, 0, None); + let eye = reused.request.camera.eye(); + let mut seeded = false; + for pass in 1..=2 { + while reused.progressive.as_ref().unwrap().film.samples() < pass { + reused.step_with_previews(1).unwrap(); + if !seeded && reused.path.first().is_some_and(|s| s.stage_name() == "trace") { + let (chain, len, start) = reused.path.first().unwrap().initial_medium().unwrap(); + assert_eq!((len, &chain[..len]), (2, &[0_usize, 1][..])); + assert_eq!(start, eye); + seeded = true; + } + } + assert_eq!(reused.path.first().unwrap().origin_slot_info(), (0, 1, false), "completed samples reuse exactly one prepaid slot"); + } + assert!(seeded, "the classified initial medium must be visible before any first-hit lighting"); +} + +fn cpu_subsurface_fixture(samples: u32, nested: bool, endpoint: u8, depth: u8, rates: [f64; 2], g: f64, lens: Option) -> ImageTask { + let base = cpu_inside_glass_fixture(samples, nested, endpoint, lens); + let mut options = base.options.clone(); + options.path = Some(job::CpuPathOptions { max_depth: depth }); + for (index, input) in options.dielectrics.iter_mut().enumerate() { + input.subsurface = Some(crate::transmission::subsurface::Subsurface { scattering_per_mm: rates[index], anisotropy: g }); + } + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() +} +#[test] +fn cpu_subsurface_first_vertex_has_independent_analog_survival_and_physical_eye_pupil_beer() { + let samples = 64; + for lens in [None, Some(job::ThinLens { aperture_radius_mm: 0.1, focus_distance_mm: 2.0 })] { + for endpoint in [1, 2] { + let build = || cpu_subsurface_fixture(samples, false, endpoint, 1, [2.0, 0.0], 0.4, lens); + let camera = build().request.camera; + let (right, up, back) = camera.basis(); + let mut expected = [0.0; 3]; + let (mut collisions, mut survivors) = (0, 0); + for ordinal in 0..samples { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let mut origin = camera.eye(); + let mut direction = camera.ray(x, y, 1.0, 1.0).1; + if let Some(lens) = lens { + let [u, v] = progressive::variates(9, 0, ordinal, 0x4c454e53); + let displacement = + (right * (std::f64::consts::TAU * v).cos() + up * (std::f64::consts::TAU * v).sin()) * (lens.aperture_radius_mm * u.sqrt()); + origin += displacement; + let aimed = direction * (lens.focus_distance_mm / direction.dot(-back)) - displacement; + direction = aimed / aimed.len(); + } + let length = (0.75 - origin.z) / direction.z; + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_5000); + // Direct CDF survival decision, independent of free_flight(). + if u < -(-2.0 * length).exp_m1() { + collisions += 1; + continue; + } + survivors += 1; + for (channel, sum) in expected.iter_mut().enumerate() { + *sum += [2.0, 1.0, 0.5][channel] * (-[0.1_f64, 0.2, 0.0][channel] * length).exp() / f64::from(samples); + } + } + assert!(collisions > 0 && survivors > 0); + for (a, e) in path_mean(build()).0.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "physical origin survival/Beer: {a} vs{e}"); + } + let output = complete_presentation(build(), 1); + assert_eq!( + native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0, + [expected[0] as f32, expected[1] as f32, expected[2] as f32, 1.0] + ); + } + } +} +#[test] +fn cpu_nested_subsurface_uses_each_current_collision_rate_and_absorption_to_the_finite_depth_endpoint() { + let samples = 64; + let build = || cpu_subsurface_fixture(samples, true, 0, 3, [1.3, 0.8], -0.6, None); + let camera = build().request.camera; + let mut expected = [0.0; 3]; + let mut surviving = 0; + for ordinal in 0..samples { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let distance = 0.5 / -camera.ray(x, y, 1.0, 1.0).1.z; + let [inner, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_5000); + let [outer, _] = progressive::variates(9, 0, ordinal, 0x5041_5449_5000); + if inner < -(-0.8 * distance).exp_m1() || outer < -(-1.3 * distance).exp_m1() { + continue; + } + surviving += 1; + // A collision plus both interfaces cannot escape in three vertices. + for (channel, sum) in expected.iter_mut().enumerate() { + *sum += (-[0.4_f64, 0.2, 0.4][channel] * distance).exp() / f64::from(samples); + } + } + assert!(surviving > 0 && surviving < samples); + for (a, e) in path_mean(build()).0.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "nested analog/Beer/depth: {a} vs{e}"); + } +} + +fn independent_single_box_subsurface(task: &ImageTask, environment: &impl Fn(Vec3) -> Vec3) -> [f64; 3] { + let samples = task.options.progressive.unwrap().samples_per_pixel; + let input = &task.options.dielectrics[0]; + let scattering = input.subsurface.unwrap(); + let camera = task.request.camera; + let depth = task.options.path.unwrap().max_depth; + let mut expected = Vec3::ZERO; + for ordinal in 0..samples { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let mut point = camera.eye(); + let mut direction = camera.ray(x, y, 1.0, 1.0).1; + let mut weight = Vec3::new(1.0, 1.0, 1.0); + for vertex in 0..depth { + let mut distance = f64::INFINITY; + for (p, d, lo, hi) in [(point.x, direction.x, -10.0, 10.0), (point.y, direction.y, -10.0, 10.0), (point.z, direction.z, 0.0, 2.0)] { + if d != 0.0 { + distance = distance.min(((if d > 0.0 { hi } else { lo }) - p) / d); + } + } + assert!(distance > 0.0 && distance.is_finite()); + let domain = 0x5041_5448_0000 + u64::from(vertex) * 0x10000; + let [u, _] = progressive::variates(9, 0, ordinal, domain + 0x5000); + // Independent exp inverse and exact analytic slab exit, not traversal. + let u = if u == 0.0 { 2.0_f64.powi(-54) } else { u }; + let travel = -(1.0 - u).ln() / scattering.scattering_per_mm; + let length = travel.min(distance); + weight = Vec3::new( + weight.x * (-input.absorption_per_mm[0] * length).exp(), + weight.y * (-input.absorption_per_mm[1] * length).exp(), + weight.z * (-input.absorption_per_mm[2] * length).exp(), + ); + if travel >= distance { + if vertex + 1 < depth { + let light = environment(direction); + expected += Vec3::new(weight.x * light.x, weight.y * light.y, weight.z * light.z); + } + break; + } + if vertex + 1 == depth { + break; + } + point += direction * travel; + let [u, v] = progressive::variates(9, 0, ordinal, domain + 0x5001); + let g = scattering.anisotropy; + let cosine = if g == 0.0 { + 2.0 * u - 1.0 + } else { + let q = (1.0 - g * g) / (1.0 - g + 2.0 * g * u); + (1.0 + g * g - q * q) / (2.0 * g) + }; + let radius = (1.0 - cosine * cosine).max(0.0).sqrt(); + let axis = if direction.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z }; + let tangent = axis.cross(direction); + let tangent = tangent / tangent.len(); + let other = direction.cross(tangent); + direction = + tangent * (radius * (std::f64::consts::TAU * v).cos()) + other * (radius * (std::f64::consts::TAU * v).sin()) + direction * cosine; + direction = direction / direction.len(); + } + } + expected = expected / f64::from(samples); + [expected.x, expected.y, expected.z] +} +#[test] +fn cpu_subsurface_hg_walk_and_beer_match_an_independent_per_ordinal_slab_oracle() { + for g in [-0.6, 0.0, 0.6] { + let build = || cpu_subsurface_fixture(64, false, 0, 16, [1.0, 0.0], g, None); + let expected = independent_single_box_subsurface(&build(), &|_| Vec3::new(1.0, 1.0, 1.0)); + for (a, e) in path_mean(build()).0.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "g{g}: independent free-flight/HG/Beer{a} vs{e}"); + } + } +} +#[test] +fn cpu_subsurface_inactive_some_preserves_original_radiance_work_every_png_prefix_and_raw_bits() { + let build = |present| { + let base = cpu_inside_glass_fixture(8, true, 0, None); + let mut options = base.options.clone(); + if present { + for input in &mut options.dielectrics { + input.subsurface = Some(crate::transmission::subsurface::Subsurface { scattering_per_mm: 0.0, anisotropy: 0.95 }); + } + } + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + assert_eq!(path_mean(build(false)), path_mean(build(true)), "inactive fields add no transport work or random dimension"); + assert_eq!(complete_presentation(build(false), 1), complete_presentation(build(true), 1)); + assert_eq!(build(false).admission.estimated_total_bytes, build(true).admission.estimated_total_bytes); + let inactive = build(true); + let mut options = inactive.options.clone(); + for input in &mut options.dielectrics { + input.subsurface.as_mut().unwrap().scattering_per_mm = 0.3; + } + let request = ImageRequest { raytrace: Some(options.clone()), ..inactive.request.clone() }; + let active = ImageTask::new(inactive.scene.clone(), request, CancelToken::default(), options).unwrap(); + assert_eq!( + serde_json::to_value(active.admission).unwrap(), + serde_json::to_value(inactive.admission).unwrap(), + "active events reuse the prepaid classifier and single path slot, not a new image plane" + ); +} +#[test] +fn cpu_subsurface_white_furnace_keeps_unit_radiance_without_absorption_or_unfinished_paths() { + let base = cpu_subsurface_fixture(32, false, 0, 16, [0.1, 0.0], 0.0, None); + let mut options = base.options.clone(); + options.dielectrics[0].absorption_per_mm = [0.0; 3]; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mut task = ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap(); + let mut scattered = false; + while task.progressive.as_ref().unwrap().film.samples() < 32 { + scattered |= task.path.first().is_some_and(|state| state.stage_name() == "medium_scatter"); + task.step_with_previews(1).unwrap(); + } + assert!(scattered, "the white furnace must include a real collision, not only inactive/no-event paths"); + assert_eq!(task.progressive.as_ref().unwrap().film.pixel(0).unwrap().0, [1.0; 3]); +} +#[test] +fn cpu_subsurface_prefixes_quanta_alpha_finishing_and_adaptive_production_keep_the_raw_walk_exact() { + let build = |samples, adaptive, pilot, finishing| { + let base = cpu_subsurface_fixture(samples, false, 0, 16, [1.0, 0.0], 0.3, None); + let mut options = base.options.clone(); + if adaptive { + options.adaptive = Some(Box::new(job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })); + } + if pilot { + options.progressive.as_mut().unwrap().seed ^= 0xa511_e9b3; + } + if finishing { + options.output.as_mut().unwrap().finishing.saturation = 0.2; + } + let request = ImageRequest { transparent_background: true, raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + let output = complete_presentation(build(8, false, false, false), 1); + assert_eq!(output, complete_presentation(build(8, false, false, false), 16384)); + for (n, png) in &output.0 { + assert_eq!(*png, complete_presentation(build(*n, false, false, false), 3).1); + } + assert_eq!(native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0[3], 1.0); + let finished = complete_presentation(build(8, false, false, true), 1); + assert_ne!(finished.1, output.1); + assert_eq!(finished.2, output.2, "finishing cannot rewrite raw scattering radiance"); + let reference = complete_presentation(build(16, false, false, false), 1); + assert_ne!(reference.2, complete_presentation(build(16, false, true, false), 1).2, "actual fixture must expose pilot leakage"); + let adaptive = complete_presentation(build(16, true, false, false), 1); + assert_eq!(adaptive, complete_presentation(build(16, true, false, false), 16384)); + assert_eq!(adaptive.0.len(), 31); + assert_eq!(adaptive.1, reference.1); + assert_eq!(adaptive.2, reference.2); +} +#[test] +fn cpu_subsurface_collision_classification_yields_one_debit_and_cancels_or_exhausts_before_any_film_commit() { + let build = || cpu_subsurface_fixture(4, false, 0, 16, [100.0, 0.0], 0.0, None); + for cancel in [false, true] { + let mut task = build(); + let mut decision = false; + for _ in 0..100_000 { + let phase = task.path.first().map(|p| p.stage_name()); + if phase == Some("medium_origin") { + break; + } + let before = task.work.used(); + task.step_with_previews(1).unwrap(); + if phase == Some("medium") { + decision = true; + assert_eq!(task.work.used() - before, 1); + } + } + assert!(decision); + assert_eq!(task.path[0].stage_name(), "medium_origin"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + for _ in 0..5 { + let before = task.work.used(); + task.step_with_previews(1).unwrap(); + assert_eq!(task.work.used() - before, 1); + } + assert_eq!(task.path[0].origin_slot_info().1, 1); + 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 { job::ErrorCode::Cancelled } else { job::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()); + } +} + +fn cpu_subsurface_contained_light_fixture(source_samples: u32) -> ImageTask { + let base = cpu_subsurface_fixture(8, false, 1, 4, [0.1, 0.0], 0.2, None); + let mut scene = base.scene.clone(); + scene.meshes.last_mut().unwrap().surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 1.0, 1.0).unwrap()); + let mut options = base.options.clone(); + options.emissions = None; + options.area_samples = Some(source_samples); + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 1.25], + edge_u_mm: [4.0, 0.0, 0.0], + edge_v_mm: [0.0, -4.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }]); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +#[test] +fn cpu_subsurface_contained_nee_has_analytic_scattering_survival_and_matching_sample_count_mis() { + for samples in [1, 4, 16, 64] { + let mut task = cpu_subsurface_contained_light_fixture(samples); + let receiver = task.scene.meshes.len() - 1; + let mut range_steps = 0; + let mut was_range = false; + let mut last_range = None; + let mut discoveries = std::collections::BTreeSet::new(); + for _ in 0..100_000 { + if task.path.first().is_some_and(|p| { + p.stage_name() == "shadow_beer" + && p.shadow_probe().is_some_and(|p| p.endpoint.is_some()) + && p.surface_source().is_some_and(|(_, _, hit)| task.looks[hit.primitive_index].body_index == receiver) + }) { + break; + } + let range = task.path.first().is_some_and(|p| p.stage_name() == "medium_surface"); + if range && !was_range { + let (depth, _, hit) = task.path[0].surface_source().unwrap(); + let key = (task.progressive.as_ref().unwrap().film.samples(), depth, hit.primitive_index); + assert!(discoveries.insert(key), "a captured source hit discovers its physical range only once"); + last_range = Some(key); + range_steps = 0; + } + let before = task.work.used(); + task.step_with_previews(1).unwrap(); + if range { + range_steps += 1; + assert_eq!(task.work.used() - before, 1); + } + was_range = range; + } + assert!( + range_steps > 0 && range_steps <= task.scene.meshes.last().unwrap().mesh.triangles.len() + 2, + "physical source ranges are discovered cooperatively once per hit" + ); + assert_eq!(task.path[0].stage_name(), "shadow_beer"); + let (depth, incident, hit) = task.path[0].surface_source().unwrap(); + assert_eq!(last_range, Some((task.progressive.as_ref().unwrap().film.samples(), depth, hit.primitive_index))); + let prepared = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: &task.scene }; + let captured_source = prepared.resolve_hit(incident, hit).unwrap(); + assert_eq!(captured_source.body_index, receiver); + assert!(captured_source.vertices.iter().all(|vertex| vertex.z == 0.75), "the chosen captured receiver is the intended plane"); + let before = task.path[0].shadow_probe().unwrap(); + assert_eq!( + before.from, captured_source.position, + "source equality uses the actual reconstructed hit, not a guessed decimal plane coordinate" + ); + assert_eq!(before.ray_origin, Some(before.from), "SSS light visibility must start on the actual physical surface, not a finite offset"); + let length = before.from.dist(before.endpoint.unwrap()); + assert_eq!(before.probability, 1.0); + let survival = (-0.1 * length).exp(); + let expected = + Vec3::new(before.contribution.x * (-0.2 * length).exp(), before.contribution.y * (-0.3 * length).exp(), before.contribution.z * survival); + task.step_with_previews(1).unwrap(); + assert_eq!(task.path[0].stage_name(), "shadow_emitters", "the contained connection must have no boundary or opaque blocker"); + let after = task.path[0].shadow_probe().unwrap(); + assert!((after.probability - survival).abs() < 1e-15); + assert!((after.contribution - expected).len() < 1e-12); + for _ in 0..16 { + if task.path[0].stage_name() == "add" { + break; + } + task.step_with_previews(1).unwrap(); + } + assert_eq!(task.path[0].stage_name(), "add"); + let [light, bsdf] = after.mis.unwrap(); + let weight = light * light / (light * light + (bsdf * survival).powi(2)); + let expected = before.radiance + expected * weight; + task.step_with_previews(1).unwrap(); + assert!( + (task.path[0].shadow_probe().unwrap().radiance - expected).len() < 1e-12, + "sourceN={samples}: contained MIS must include analog survival" + ); + } +} +#[test] +fn cpu_subsurface_sampled_no_collision_endpoint_carries_the_same_survival_density_without_double_attenuation() { + let mut task = cpu_subsurface_contained_light_fixture(16); + let mut witnessed = false; + for _ in 0..200_000 { + if let Some(state) = task.path.first().filter(|p| p.stage_name() == "medium") { + let probe = state.medium_probe().unwrap(); + if probe.depth > 0 + && !probe.delta + && let Some(endpoint) = probe.emitter + { + let length = probe.from.dist(endpoint); + let ordinal = task.progressive.as_ref().unwrap().film.samples(); + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_5000 + u64::from(probe.depth) * 0x10000); + if u >= -(-0.1 * length).exp_m1() { + task.step_with_previews(1).unwrap(); + assert_eq!(task.path[0].stage_name(), "resolve"); + let after = task.path[0].medium_probe().unwrap(); + assert_eq!(after.ray_origin, Some(probe.from), "SSS BSDF travel must share the physical source line"); + assert_eq!(after.throughput, probe.throughput, "analog survival cannot be multiplied into sampled throughput a second time"); + assert!((after.pdf - probe.pdf * (-0.1 * length).exp()).abs() < 1e-15); + witnessed = true; + break; + } + } + } + task.step_with_previews(1).unwrap(); + } + assert!(witnessed, "a real BSDF continuation must reach the contained analytic emitter without a collision"); +} + +#[test] +fn cpu_subsurface_refuses_an_unrepresentable_actual_collision_instead_of_moving_its_source_boundary() { + let base = cpu_subsurface_fixture(1, false, 0, 16, [100.0, 0.0], 0.0, None); + let offset = Vec3::new(1e12 - 100.0, 1e12 - 100.0, 1e12 - 100.0); + let mut scene = base.scene.clone(); + for mesh in &mut scene.meshes { + for position in &mut Arc::make_mut(&mut mesh.mesh).positions { + *position += offset; + } + } + scene.bounds = scene.meshes[0].mesh.bounds(); + let seed = (0..100_000) + .find(|seed| { + let [u, _] = progressive::variates(*seed, 0, 0, 0x5041_5448_5000); + let flight = -(1.0 - u).ln() / 100.0; + flight > 0.0 && flight < 0.00001 + }) + .expect("fixed finite seed search must exercise sub-ULP flight"); + let mut options = base.options.clone(); + options.progressive.as_mut().unwrap().seed = seed; + let mut camera = base.request.camera; + camera.target += offset; + let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() }; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut failure = None; + for _ in 0..100_000 { + match task.step_with_previews(1) { + Err(error) => { + failure = Some(error); + break; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("an unrepresentable collision cannot publish an image"), + } + } + assert!(failure.expect("precision refusal must terminate").message.contains("not representable")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); +} + +#[test] +fn cpu_subsurface_real_nonconstant_hdr_matches_independent_walk_escape_texels_and_all_png_prefixes() { + use std::f64::consts::{PI, TAU}; + let texels: [[u8; 4]; 8] = [ + [128, 32, 16, 129], + [16, 128, 32, 129], + [32, 16, 128, 129], + [64, 96, 128, 129], + [96, 64, 32, 129], + [32, 96, 64, 129], + [64, 32, 96, 129], + [128, 64, 96, 129], + ]; + let environment = |direction: Vec3| { + let column = ((direction.y.atan2(direction.x).rem_euclid(TAU) * 4.0 / TAU) as usize).min(3); + let row = ((direction.z.clamp(-1.0, 1.0).acos() * 2.0 / PI) as usize).min(1); + let pixel = texels[row * 4 + column]; + Vec3::new(f64::from(pixel[0]), f64::from(pixel[1]), f64::from(pixel[2])) / 128.0 + }; + let build = |samples| { + let base = cpu_subsurface_fixture(samples, false, 0, 16, [1.0, 0.0], -0.6, None); + let options = RaytraceOptions { environment: None, ..base.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for pixel in texels { + bytes.extend_from_slice(&pixel); + } + let hdr = crate::lighting::environment_input::EnvironmentInput::new(crate::lighting::HdrSource::new(bytes).unwrap(), 0.0, 1.0, 16).unwrap(); + ImageTask::new_with_environment(base.scene.clone(), request, CancelToken::default(), options, Some(hdr)).unwrap() + }; + let expected = independent_single_box_subsurface(&build(64), &environment); + for (actual, expected) in path_mean(build(64)).0.into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12, "independent HG/slab/nonconstant HDR{actual} vs{expected}"); + } + let output = complete_presentation(build(7), 1); + assert_eq!(output, complete_presentation(build(7), 16384)); + for (samples, png) in &output.0 { + assert_eq!(*png, complete_presentation(build(*samples), 3).1); + } + let expected = independent_single_box_subsurface(&build(7), &environment); + assert_eq!(native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0, [expected[0] as f32, expected[1] as f32, expected[2] as f32, 1.0]); +} + +fn cpu_volume_fixture(samples: u32, depth: u8, perspective: bool, opaque: bool, volume: Option) -> ImageTask { + let base = fixture(1, 1, Some(true)); + let body = ProductMesh { + name: "Volume receiver".into(), + transmission: None, + 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]], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.0).unwrap()), + faces: vec![], + }; + let scene = + if opaque { ProductScene { bounds: body.mesh.bounds(), meshes: vec![body] } } else { ProductScene { bounds: Aabb3::EMPTY, meshes: vec![] } }; + let camera = crate::Camera { + target: Vec3::ZERO, + distance: 3.0, + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + roll: 0.0, + fov: if perspective { 0.3 } else { 0.0 }, + ..base.request.camera + }; + let options = RaytraceOptions { + volume, + path: Some(job::CpuPathOptions { max_depth: depth }), + budget: job::CpuBudget::Studio, + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 9 }), + lights: Some(vec![]), + shadows: true, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..Default::default() + }; + let request = ImageRequest { + camera, + integrator: job::Integrator::Raytrace, + width: 1, + height: 1, + raytrace: Some(options.clone()), + transparent_background: true, + ..base.request + }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} +fn volume_slab() -> job::volume::HomogeneousVolume { + job::volume::HomogeneousVolume { + min_mm: [-10.0, -10.0, 0.0], + max_mm: [10.0, 10.0, 2.0], + extinction_per_mm: 0.5, + scattering_albedo: [0.8, 0.6, 0.4], + anisotropy: 0.0, + } +} +fn volume_mean(mut task: ImageTask) -> ([f64; 3], u16, u16, u64) { + let target = task.options.progressive.unwrap().samples_per_pixel; + for _ in 0..2_000_000 { + if task.progressive.as_ref().is_some_and(|p| p.film.samples() == target) { + let (rgb, covered, samples) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + return (rgb, covered, samples, task.work.used()); + } + let bounded = task.bvh.is_some() + && task.progressive.as_ref().is_some_and(|p| p.film.ready() && !p.resolving) + && task.output.is_empty() + && task.encoder.is_none(); + let before = task.work.used(); + task.step_with_previews(1).unwrap(); + if bounded { + assert!(task.work.used() - before <= 1, "every real Atmosphere continuation has one prepaid debit"); + } + } + panic!("bounded Atmosphere fixture did not complete"); +} +fn independent_volume_segment(v: job::volume::HomogeneousVolume, p: Vec3, d: Vec3, limit: f64) -> [f64; 2] { + let mut a = 0.0_f64; + let mut b = limit; + for (axis, (p, d)) in [(p.x, d.x), (p.y, d.y), (p.z, d.z)].into_iter().enumerate() { + if d == 0.0 { + if p < v.min_mm[axis] || p > v.max_mm[axis] { + return [0.0; 2]; + } + } else { + let x = (v.min_mm[axis] - p) / d; + let y = (v.max_mm[axis] - p) / d; + a = a.max(x.min(y)); + b = b.min(x.max(y)); + } + } + if a < b { [a, b] } else { [0.0; 2] } +} +// The real fixture is the finite square [-10,10]^2 at z0, not an +// infinite half-space. Grazing source/continuation rays may miss its edge. +fn independent_volume_blocker(point: Vec3, direction: Vec3) -> Option { + if direction.z >= 0.0 || point.z <= 0.0 { + return None; + } + let distance = -point.z / direction.z; + let plane = point + direction * distance; + (plane.x.abs() <= 10.0 && plane.y.abs() <= 10.0).then_some(distance) +} +fn independent_volume_walk(samples: u32, depth: u8, v: job::volume::HomogeneousVolume, blocker: bool) -> ([f64; 3], u16) { + independent_volume_environment(samples, depth, v, blocker, 1, &|_| Vec3::new(1.0, 1.0, 1.0)) +} +fn independent_volume_environment( + samples: u32, + depth: u8, + v: job::volume::HomogeneousVolume, + blocker: bool, + count: u32, + environment: &impl Fn(Vec3) -> Vec3, +) -> ([f64; 3], u16) { + independent_volume_celestial(samples, depth, v, blocker, count, environment, false) +} +fn independent_volume_celestial( + samples: u32, + depth: u8, + v: job::volume::HomogeneousVolume, + blocker: bool, + count: u32, + environment: &impl Fn(Vec3) -> Vec3, + sun: bool, +) -> ([f64; 3], u16) { + use std::f64::consts::{PI, TAU}; + let phase = |incoming: Vec3, d: Vec3| { + let c = incoming.dot(d).clamp(-1.0, 1.0); + (1.0 - v.anisotropy * v.anisotropy) / (4.0 * PI * (1.0 + v.anisotropy * v.anisotropy - 2.0 * v.anisotropy * c).powf(1.5)) + }; + let power = |a: f64, b: f64| a * a / (a * a + b * b); + let mut sum = Vec3::ZERO; + let mut covered = 0; + let camera = cpu_volume_fixture(1, depth, false, blocker, Some(v)).request.camera; + for ordinal in 0..samples { + let [dx, dy] = progressive::variates(9, 0, ordinal, 0); + let (point, d) = camera.ray(dx, dy, 1.0, 1.0); + // Its exact orthographic line is unchanged; this slab is before the empty + // scene near plane, so optical transport starts at z2, not scene bounds. + let mut point = point + d * ((2.0 - point.z) / d.z); + let mut direction = d; + let mut weight = Vec3::new(1.0, 1.0, 1.0); + let mut previous_pdf = 0.0; + let mut foreground = blocker; + for vertex in 0..depth { + let endpoint = if blocker { independent_volume_blocker(point, direction).unwrap_or(1e12) } else { 1e12 }; + let [entry, exit] = independent_volume_segment(v, point, direction, endpoint); + let domain = 0x5041_5448_0000 + u64::from(vertex) * 0x10000; + let [u, _] = progressive::variates(9, 0, ordinal, domain + 0x6000); + let u = if u == 0.0 { 2.0_f64.powi(-54) } else { u }; + let travel = -(1.0 - u).ln() / v.extinction_per_mm; + let survival = (-v.extinction_per_mm * (exit - entry)).exp(); + if entry >= exit || travel >= exit - entry { + if vertex > 0 && endpoint == 1e12 { + let li = environment(direction); + sum += + Vec3::new(weight.x * li.x, weight.y * li.y, weight.z * li.z) * power(previous_pdf * survival, f64::from(count) / (4.0 * PI)); + if sun && direction.z >= 0.7_f64.cos() { + let omega = 4.0 * PI * (0.7_f64 * 0.5).sin().powi(2); + sum += Vec3::new(weight.x * 2.0, weight.y * 3.0, weight.z * 5.0) * power(previous_pdf * survival, 1.0 / omega); + } + } + break; + } + foreground = true; + point += direction * (entry + travel); + weight = Vec3::new(weight.x * v.scattering_albedo[0], weight.y * v.scattering_albedo[1], weight.z * v.scattering_albedo[2]); + if weight == Vec3::ZERO { + break; + } + let side = match count { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + for source in 0..count { + let [u, t] = progressive::variates(9, 0, ordinal, domain + 0x2000 + u64::from(source)); + let u = ((f64::from(source / side) + u) / f64::from(side)).max(0.0_f64.next_up()).min(1.0_f64.next_down()); + let t = ((f64::from(source % side) + t) / f64::from(side)).max(0.0_f64.next_up()).min(1.0_f64.next_down()); + let z = 1.0 - 2.0 * u; + let r = ((1.0 - z) * (1.0 + z)).sqrt(); + let light = Vec3::new(r * (TAU * t).cos(), r * (TAU * t).sin(), z); + let phase_pdf = phase(direction, light); + let [a, b] = independent_volume_segment(v, point, light, 1e12); + let tr = (-v.extinction_per_mm * (b - a)).exp(); + if !(blocker && independent_volume_blocker(point, light).is_some()) { + let mis = if vertex + 1 == depth { 1.0 } else { power(f64::from(count) / (4.0 * PI), phase_pdf * tr) }; + let li = environment(light); + sum += Vec3::new(weight.x * li.x, weight.y * li.y, weight.z * li.z) * (phase_pdf * (4.0 * PI) * tr * mis / f64::from(count)); + } + } + if sun { + let omega = 4.0 * PI * (0.7_f64 * 0.5).sin().powi(2); + let [u, t] = progressive::variates(9, 0, ordinal, domain + 0x7000); + let z = 1.0 - u * omega / (2.0 * PI); + let radius = ((1.0 - z) * (1.0 + z)).sqrt(); + let light = Vec3::new(radius * (TAU * t).cos(), radius * (TAU * t).sin(), z); + let density = phase(direction, light); + let [a, b] = independent_volume_segment(v, point, light, 1e12); + let tr = (-v.extinction_per_mm * (b - a)).exp(); + let mis = if vertex + 1 == depth { 1.0 } else { power(1.0 / omega, density * tr) }; + sum += Vec3::new(weight.x * 2.0, weight.y * 3.0, weight.z * 5.0) * (density * omega * tr * mis); + } + if vertex + 1 == depth { + break; + } + let [u, t] = progressive::variates(9, 0, ordinal, domain + 0x6001); + let g = v.anisotropy; + let c = if g == 0.0 { + 2.0 * u - 1.0 + } else { + let q = (1.0 - g * g) / (1.0 - g + 2.0 * g * u); + (1.0 + g * g - q * q) / (2.0 * g) + }; + let r = (1.0 - c * c).max(0.0).sqrt(); + let axis = if direction.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z }; + let tangent = axis.cross(direction); + let tangent = tangent / tangent.len(); + let next = tangent * (r * (TAU * t).cos()) + direction.cross(tangent) * (r * (TAU * t).sin()) + direction * c; + let next = next / next.len(); + previous_pdf = phase(direction, next); + direction = next; + } + covered += u16::from(foreground); + } + sum = sum / f64::from(samples); + ([sum.x, sum.y, sum.z], covered) +} +#[test] +fn cpu_volume_none_and_authored_zero_keep_original_pixels_rng_work_and_heap_owners() { + for path in [None, Some(job::CpuPathOptions { max_depth: 4 })] { + let build = |zero: bool| { + let base = + cpu_volume_fixture(7, 4, false, true, zero.then(|| job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..volume_slab() })); + let options = RaytraceOptions { path, ..base.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + if path.is_some() { + assert_eq!(volume_mean(build(false)), volume_mean(build(true))); + } + assert_eq!( + complete_presentation(build(false), 1), + complete_presentation(build(true), 1), + "legacy and Path prefixes, RAW and every cumulative work unit stay identical" + ); + assert_eq!(serde_json::to_value(build(false).admission).unwrap(), serde_json::to_value(build(true).admission).unwrap()); + assert_eq!(build(false).options.retained_bytes().unwrap(), build(true).options.retained_bytes().unwrap()); + assert_eq!(serde_json::to_value(&build(true).options).unwrap()["volume"]["extinction_per_mm"], 0.0); + } +} + +#[test] +fn cpu_volume_single_and_multiple_scatter_match_independent_hg_slab_nee_escape_and_blocker_oracles() { + let grazing = Vec3::new(0.7252901844548614, -0.6841978696212823, -0.0763375630940093); + let source = Vec3::new(-0.7543915972220849, -1.1230912621927815, 1.4665695089641722); + assert!(independent_volume_blocker(source, grazing).is_none(), "fixed-seed ordinal5 crosses the z0 plane beyond the finite square"); + assert_eq!(independent_volume_blocker(Vec3::new(0.0, 0.0, 1.0), -Vec3::Z), Some(1.0)); + for g in [-0.6, 0.0, 0.6] { + for depth in [1, 2, 16] { + for blocker in [false, true] { + let v = job::volume::HomogeneousVolume { anisotropy: g, ..volume_slab() }; + let expected = independent_volume_walk(64, depth, v, blocker); + let (actual, covered, samples, _) = volume_mean(cpu_volume_fixture(64, depth, false, blocker, Some(v))); + assert_eq!((covered, samples), (expected.1, 64)); + for (a, e) in actual.into_iter().zip(expected.0) { + assert!((a - e).abs() < 1e-12, "g{g},depth{depth},blocker{blocker}: independent HG/slab/MIS {a} vs{e}"); + } + } + } + } +} +#[test] +fn cpu_volume_orthographic_union_and_physical_eye_pupil_absorption_keep_model_and_camera_unchanged() { + for perspective in [false, true] { + for lens in [None, Some(job::ThinLens { aperture_radius_mm: 0.1, focus_distance_mm: 3.0 })] { + if !perspective && lens.is_some() { + continue; + } + let original = cpu_volume_fixture(128, 1, perspective, true, None); + let initial = primary_ray(&original.request, 0.5, 0.5, original.clip).unwrap(); + let max_z = initial.origin().z.max(original.request.camera.eye().z) + 2.0; + let v = job::volume::HomogeneousVolume { + min_mm: [-10.0, -10.0, -2.0], + max_mm: [10.0, 10.0, max_z], + extinction_per_mm: 1.0 / max_z, + scattering_albedo: [0.0; 3], + ..volume_slab() + }; + let mut options = original.options.clone(); + options.volume = Some(v); + options.lens = lens; + options.environment = None; + options.emissions = Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Volume receiver".into(), + color: [1.0, 0.5, 0.25], + strength: 2.0, + sides: job::EmissionSides::Both, + }]); + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + let make = || ImageTask::new(original.scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); + let mut survivors = 0; + for ordinal in 0..128 { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let camera = request.camera; + let (right, up, back) = camera.basis(); + let (mut source, mut d) = camera.ray(x, y, 1.0, 1.0); + if perspective { + source = camera.eye(); + if let Some(lens) = lens { + let [u, t] = progressive::variates(9, 0, ordinal, 0x4c454e53); + let offset = (right * (std::f64::consts::TAU * t).cos() + up * (std::f64::consts::TAU * t).sin()) + * (lens.aperture_radius_mm * u.sqrt()); + source += offset; + let aimed = d * (lens.focus_distance_mm / d.dot(-back)) - offset; + d = aimed / aimed.len(); + } + } else { + source += d * ((max_z - source.z) / d.z); + } + let length = -source.z / d.z; + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_6000); + survivors += u32::from(u >= -(-v.extinction_per_mm * length).exp_m1()); + } + assert!(survivors > 0 && survivors < 128); + let actual = volume_mean(make()); + let p = f64::from(survivors) / 128.0; + assert_eq!(actual.0, [2.0 * p, p, 0.5 * p]); + assert_eq!((actual.1, actual.2), (128, 128)); + assert_eq!(make().request.camera, original.request.camera); + assert_eq!(make().scene.bounds, original.scene.bounds); + assert!( + Arc::ptr_eq(&make().scene.meshes[0].mesh, &original.scene.meshes[0].mesh), + "constructing Atmosphere must retain the exact captured immutable geometry" + ); + let mut probe = make(); + while probe.path.first().is_none_or(|p| p.stage_name() != "volume") { + probe.step_with_previews(1).unwrap(); + } + assert!( + Arc::ptr_eq(&probe.scene.meshes[0].mesh, &original.scene.meshes[0].mesh), + "actual fog preparation and traversal must keep the same captured geometry" + ); + let p = probe.path[0].volume_probe().unwrap(); + assert_eq!(p.source, p.ray.unwrap().origin()); + if !perspective { + assert!(p.source.z > initial.origin().z, "foreground fog beyond the original model near plane must be included"); + } else if lens.is_none() { + assert_eq!(p.source, request.camera.eye()); + assert!(p.ray.unwrap().interval()[0] > 0.0, "the model retains its near interval while optical length starts at the eye"); + } + } + } +} +#[test] +fn cpu_volume_empty_scene_alpha_prefixes_raw_quanta_finishing_and_adaptive_use_the_same_film() { + let build = |samples, adaptive, pilot, finish| { + let base = cpu_volume_fixture(samples, 4, false, false, Some(volume_slab())); + let mut options = base.options.clone(); + if adaptive { + options.adaptive = Some(Box::new(job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })); + } + if pilot { + options.progressive.as_mut().unwrap().seed ^= 0xa511_e9b3; + } + if finish { + options.output.as_mut().unwrap().finishing.saturation = 0.2; + } + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + let output = complete_presentation(build(7, false, false, false), 1); + assert_eq!(output, complete_presentation(build(7, false, false, false), 16384)); + for (n, png) in &output.0 { + assert_eq!(*png, complete_presentation(build(*n, false, false, false), 3).1); + } + let expected = independent_volume_walk(7, 4, volume_slab(), false); + let alpha = f64::from(expected.1) / 7.0; + assert_eq!( + native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0, + [expected.0[0] as f32, expected.0[1] as f32, expected.0[2] as f32, alpha as f32] + ); + assert_eq!(alpha_pixel(&output.1)[3], (alpha * 255.0).round() as u8); + let finished = complete_presentation(build(7, false, false, true), 1); + assert_ne!(finished.1, output.1); + assert_eq!(finished.2, output.2); + let reference = complete_presentation(build(16, false, false, false), 1); + let adaptive = complete_presentation(build(16, true, false, false), 1); + assert_eq!(adaptive, complete_presentation(build(16, true, false, false), 16384)); + assert_eq!(adaptive.0.len(), 31); + assert_eq!(adaptive.1, reference.1); + assert_eq!(adaptive.2, reference.2); + assert_ne!(reference.2, complete_presentation(build(16, false, true, false), 1).2, "actual pilot seed must expose leakage"); +} +#[test] +fn cpu_volume_decision_and_visibility_yield_and_cancel_before_film_publication() { + for phase in ["volume", "volume_shadow"] { + for cancel in [false, true] { + let mut task = cpu_volume_fixture(4, 4, false, false, Some(job::volume::HomogeneousVolume { extinction_per_mm: 100.0, ..volume_slab() })); + for _ in 0..100_000 { + if task.path.first().is_some_and(|s| s.stage_name() == phase) { + break; + } + task.step_with_previews(1).unwrap(); + } + assert_eq!(task.path[0].stage_name(), phase); + 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 { job::ErrorCode::Cancelled } else { job::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_volume_opaque_connections_keep_exact_physical_sources_and_survival_in_the_deferred_mis_density() { + let base = cpu_volume_fixture(128, 2, false, true, Some(job::volume::HomogeneousVolume { scattering_albedo: [0.0; 3], ..volume_slab() })); + let mut scene = base.scene.clone(); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 1.0, 1.0).unwrap()); + let mut task = ImageTask::new(scene, base.request.clone(), CancelToken::default(), base.options.clone()).unwrap(); + let mut ranges = 0; + let mut connections = 0; + for _ in 0..2_000_000 { + if task.progressive.as_ref().unwrap().film.samples() == 128 { + break; + } + if task.path.first().is_some_and(|s| s.stage_name() == "volume_surface") { + let before = task.work.used(); + task.step_with_previews(1).unwrap(); + assert_eq!(task.work.used() - before, 1); + ranges += 1; + continue; + } + if task.path.first().is_some_and(|s| s.stage_name() == "volume_shadow") { + let before = task.path[0].volume_probe().unwrap(); + if before.incoming.is_none() { + assert_eq!(before.depth, 0); + assert_eq!(before.throughput, Vec3::new(1.0, 1.0, 1.0)); + let ray = before.shadow.unwrap(); + assert_eq!(ray.origin(), before.source, "no normal offset may shorten the optical connection"); + assert_eq!(before.source.z, 0.0); + let [a, b] = independent_volume_segment(volume_slab(), before.source, ray.direction(), ray.interval()[1]); + let survival = (-0.5 * (b - a)).exp(); + let used = task.work.used(); + task.step_with_previews(1).unwrap(); + assert_eq!(task.work.used() - used, 1); + let attenuated = task.path[0].volume_probe().unwrap(); + assert_eq!(attenuated.survival, survival); + assert_eq!(attenuated.contribution, before.contribution * survival); + while task.path[0].stage_name() != "add" { + task.step_with_previews(1).unwrap(); + } + let [light, bsdf] = task.path[0].volume_probe().unwrap().mis.unwrap(); + let weight = light * light / (light * light + (bsdf * survival).powi(2)); + task.step_with_previews(1).unwrap(); + let after = task.path[0].volume_probe().unwrap(); + assert!((after.radiance - (before.radiance + attenuated.contribution * weight)).len() < 1e-14); + connections += 1; + continue; + } + } + task.step_with_previews(1).unwrap(); + } + assert!(ranges > 0 && connections > 0, "actual opaque paths must exercise the range walk and nonzero physical connection"); +} +#[test] +fn cpu_volume_integrates_real_perspective_near_prefix_before_the_unchanged_model_interval() { + let base = cpu_volume_fixture(64, 1, true, true, None); + let eye = base.request.camera.eye(); + let near = base.clip.0; + assert!(near > 0.0 && near < 0.01); + let v = job::volume::HomogeneousVolume { + min_mm: [-10.0, -10.0, eye.z - near * 0.75], + max_mm: [10.0, 10.0, eye.z], + extinction_per_mm: 1000.0, + scattering_albedo: [0.0; 3], + ..volume_slab() + }; + let mut options = base.options.clone(); + options.volume = Some(v); + options.environment = None; + options.emissions = Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Volume receiver".into(), + color: [1.0; 3], + strength: 1.0, + sides: job::EmissionSides::Both, + }]); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mut expected = 0.0; + let mut collisions = 0; + for ordinal in 0..64 { + let [x, y] = progressive::variates(9, 0, ordinal, 0); + let d = request.camera.ray(x, y, 1.0, 1.0).1; + let length = (eye.z - v.min_mm[2]) / (-d.z); + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_6000); + if u < -(-v.extinction_per_mm * length).exp_m1() { + collisions += 1; + } else { + expected += 1.0 / 64.0; + } + } + assert!(collisions > 0 && collisions < 64); + let task = ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap(); + let mean = volume_mean(task); + assert_eq!(mean.0, [expected; 3]); + assert_eq!((mean.1, mean.2), (64, 64), "collisions before the old near plane remain visible foreground"); +} + +#[test] +fn cpu_volume_finite_rectangle_connections_match_independent_phase_survival_and_source_count_mis() { + use std::f64::consts::PI; + for samples in [1, 4, 16, 64] { + let base = cpu_volume_fixture( + 4, + 4, + false, + false, + Some(job::volume::HomogeneousVolume { extinction_per_mm: 100.0, anisotropy: 0.3, ..volume_slab() }), + ); + let mut options = base.options.clone(); + options.environment = None; + options.area_samples = Some(samples); + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 4.0], + edge_u_mm: [1.0, 0.0, 0.0], + edge_v_mm: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mut task = ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap(); + let mut observed = 0; + for _ in 0..100_000 { + if task.path.first().is_some_and(|s| s.stage_name() == "volume_shadow") { + let before = task.path[0].volume_probe().unwrap(); + if let Some(incoming) = before.incoming { + let ray = before.shadow.unwrap(); + assert_eq!(ray.origin(), before.source); + let length = ray.interval()[1]; + let light = f64::from(samples) * length * length / ray.direction().z; + let c = incoming.dot(ray.direction()); + let phase = (1.0 - 0.3_f64.powi(2)) / (4.0 * PI * (1.0 + 0.3_f64.powi(2) - 0.6 * c).powf(1.5)); + let [actual_light, actual_phase] = before.mis.unwrap(); + assert!((actual_light - light).abs() < light * 1e-12); + assert!((actual_phase - phase).abs() < 1e-14); + let v = job::volume::HomogeneousVolume { extinction_per_mm: 100.0, ..volume_slab() }; + let [a, b] = independent_volume_segment(v, before.source, ray.direction(), length); + let survival = (-100.0 * (b - a)).exp(); + task.step_with_previews(1).unwrap(); + let shadow = task.path[0].volume_probe().unwrap(); + assert_eq!(shadow.survival, survival); + assert_eq!(shadow.contribution, before.contribution * survival); + while task.path[0].stage_name() != "add" { + task.step_with_previews(1).unwrap(); + } + let competing = phase * survival; + let weight = light * light / (light * light + competing * competing); + task.step_with_previews(1).unwrap(); + let after = task.path[0].volume_probe().unwrap(); + assert!((after.radiance - (before.radiance + shadow.contribution * weight)).len() < 1e-13); + observed += 1; + if observed == samples { + break; + } + } + } + task.step_with_previews(1).unwrap(); + } + assert_eq!(observed, samples, "every source sample must traverse the real bounded physical visibility path"); + } +} +#[test] +fn cpu_volume_white_furnace_energy_matches_the_independent_finite_walk_and_analytic_primary_coverage() { + let volume = job::volume::HomogeneousVolume { scattering_albedo: [1.0; 3], ..volume_slab() }; + let expected = independent_volume_walk(128, 16, volume, false); + let actual = volume_mean(cpu_volume_fixture(128, 16, false, false, Some(volume))); + for (a, e) in actual.0.into_iter().zip(expected.0) { + assert!((a - e).abs() < 1e-12, "unit-albedo white furnace {a} vs independent {e}"); + } + let collisions = (0..128).filter(|n| progressive::variates(9, 0, *n, 0x5041_5448_6000)[0] < 1.0 - (-1.0_f64).exp()).count(); + assert_eq!(actual.1, collisions as u16); + assert!(actual.0.iter().all(|a| *a > 0.0)); + assert_eq!(actual.0[0], actual.0[1]); + assert_eq!(actual.0[1], actual.0[2]); +} + +#[test] +fn cpu_volume_nonconstant_hdr_nee_and_escape_match_independent_texels_and_source_count_densities() { + use std::f64::consts::{PI, TAU}; + let texels: [[u8; 4]; 8] = [ + [128, 32, 16, 129], + [16, 128, 32, 129], + [32, 16, 128, 129], + [64, 96, 128, 129], + [96, 64, 32, 129], + [32, 96, 64, 129], + [64, 32, 96, 129], + [128, 64, 96, 129], + ]; + let environment = |d: Vec3| { + let x = ((d.y.atan2(d.x).rem_euclid(TAU) * 4.0 / TAU) as usize).min(3); + let y = ((d.z.clamp(-1.0, 1.0).acos() * 2.0 / PI) as usize).min(1); + let p = texels[y * 4 + x]; + Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])) / 128.0 + }; + let build = |samples, depth, count| { + let base = cpu_volume_fixture(samples, depth, false, false, Some(volume_slab())); + let options = RaytraceOptions { environment: None, ..base.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for texel in texels { + bytes.extend_from_slice(&texel); + } + let input = + crate::lighting::environment_input::EnvironmentInput::new(crate::lighting::HdrSource::new(bytes).unwrap(), 0.0, 1.0, count).unwrap(); + ImageTask::new_with_environment(base.scene.clone(), request, CancelToken::default(), options, Some(input)).unwrap() + }; + for depth in [1, 2] { + for count in [1, 4, 16, 64] { + let expected = independent_volume_environment(32, depth, volume_slab(), false, count, &environment); + let actual = volume_mean(build(32, depth, count)); + assert_eq!(actual.1, expected.1); + for (a, e) in actual.0.into_iter().zip(expected.0) { + assert!((a - e).abs() < 1e-12, "real HDR depth{depth},N{count}: {a} vs independent {e}"); + } + } + } + let output = complete_presentation(build(7, 2, 16), 1); + assert_eq!(output, complete_presentation(build(7, 2, 16), 16384)); + for (n, png) in &output.0 { + assert_eq!(*png, complete_presentation(build(*n, 2, 16), 3).1); + } + let (expected, covered) = independent_volume_environment(7, 2, volume_slab(), false, 16, &environment); + assert_eq!( + native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0, + [expected[0] as f32, expected[1] as f32, expected[2] as f32, (f64::from(covered) / 7.0) as f32] + ); +} + +fn celestial_fixture(samples: u32, depth: u8, sun: bool, sky: bool) -> ImageTask { + let original = path_fixture(samples, depth, false); + let options = RaytraceOptions { + environment: None, + sun: sun.then(|| Box::new(job::Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.7, radiance: [2.0, 3.0, 5.0] })), + sky: sky.then(|| { + Box::new(job::CpuSky { + gradient: crate::lighting::environment::SkyGradient { + zenith: [0.25, 0.5, 1.0], + horizon: [0.75, 0.5, 0.25], + ground: [0.125, 0.25, 0.5], + }, + rotation_rad: 0.731, + intensity: 1.75, + }) + }), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() +} +fn independent_sky(direction: Vec3) -> Vec3 { + use std::f64::consts::PI; + let y = ((direction.z.clamp(-1.0, 1.0).acos() / PI * 256.0) as u32).min(255); + let z = (PI * (f64::from(y) + 0.5) / 256.0).cos(); + let t = z.abs().sqrt() as f32; + let horizon = [0.75_f32, 0.5, 0.25]; + let endpoint = if z >= 0.0 { [0.25_f32, 0.5, 1.0] } else { [0.125_f32, 0.25, 0.5] }; + let rgb: [f64; 3] = std::array::from_fn(|i| f64::from(horizon[i] * (1.0 - t) + endpoint[i] * t) * 1.75); + Vec3::new(rgb[0], rgb[1], rgb[2]) +} +fn independent_celestial_mean(samples: u32, depth: u8, sun: bool, sky: bool) -> [f64; 3] { + use std::f64::consts::{PI, TAU}; + let mut result = Vec3::ZERO; + let angle = 4.0 * PI * (0.7_f64 * 0.5).sin().powi(2); + let sun_radiance = Vec3::new(2.0, 3.0, 5.0); + let power = |a: f64, b: f64| a * a / (a * a + b * b); + for ordinal in 0..samples { + if sky { + let [u, v] = progressive::variates(9, 0, ordinal, 0x5041_5448_2000); + let z = 1.0 - 2.0 * u; + if z > 0.0 { + let r = (1.0 - z * z).sqrt(); + let d = Vec3::new(r * (TAU * v).cos(), r * (TAU * v).sin(), z); + let bsdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + result += independent_sky(d) * (2.0 * z * if depth == 1 { 1.0 } else { power(1.0 / (4.0 * PI), bsdf) }); + } + } + if sun { + let [u, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_7000); + let z = 1.0 - u * angle / (2.0 * PI); + let bsdf = 0.5 * z / PI + 0.5 / (4.0 * PI); + result += sun_radiance * (0.5 * z / PI * angle * if depth == 1 { 1.0 } else { power(1.0 / angle, bsdf) }); + } + if depth == 2 { + let (z, pdf) = independent_lambert_scatter(ordinal); + if pdf > 0.0 { + let [v, _] = progressive::variates(9, 0, ordinal, 0x5041_5448_3001); + let r = (1.0 - z * z).sqrt(); + let d = Vec3::new(r * (TAU * v).cos(), r * (TAU * v).sin(), z); + if sky { + result += independent_sky(d) * (0.5 * z / (PI * pdf) * power(pdf, 1.0 / (4.0 * PI))); + } + if sun && z >= 0.7_f64.cos() { + result += sun_radiance * (0.5 * z / (PI * pdf) * power(pdf, 1.0 / angle)); + } + } + } + } + result = result / f64::from(samples); + [result.x, result.y, result.z] +} +#[test] +fn cpu_sun_sky_real_path_matches_independent_per_ordinal_nee_and_escape_mis() { + for samples in [1, 7, 128] { + for depth in [1, 2] { + for (sun, sky) in [(true, false), (false, true), (true, true)] { + let expected = independent_celestial_mean(samples, depth, sun, sky); + let (actual, _) = path_mean(celestial_fixture(samples, depth, sun, sky)); + for (actual, expected) in actual.into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-11, "N={samples}, depth={depth}, Sun={sun}, Sky={sky}: {actual} != {expected}"); + } + } + } + } +} +#[test] +fn cpu_sun_cap_and_sky_rows_keep_shared_domain_and_independent_energy() { + use std::f64::consts::{PI, TAU}; + let sun = job::Sun { direction: [0.0, 0.0, 2.0], angular_radius_rad: 0.7, radiance: [2.0, 3.0, 5.0] }; + let omega = 2.0 * PI * (1.0 - 0.7_f64.cos()); + assert!((sun.solid_angle() - omega).abs() < 1e-15); + let mut cosine = 0.0; + for i in 0..4096 { + let u = [(f64::from(i) + 0.5) / 4096.0, (f64::from((i * 2371) % 4096) + 0.5) / 4096.0]; + let sample = super::super::celestial::sample(sun, u).unwrap(); + assert!((sample.direction.len() - 1.0).abs() < 1e-15); + assert!(sample.direction.z > 0.7_f64.cos()); + assert!((sample.pdf - 1.0 / omega).abs() < 1e-14); + cosine += sample.direction.z; + } + assert!((cosine / 4096.0 - (1.0 + 0.7_f64.cos()) / 2.0).abs() < 1e-14); + let task = celestial_fixture(1, 1, false, true); + let sky = *task.options.sky.as_deref().unwrap(); + let mut energy = Vec3::ZERO; + for row in 0..256 { + let z = (PI * (f64::from(row) + 0.5) / 256.0).cos(); + let radius = (1.0 - z * z).sqrt(); + let d = Vec3::new(radius, 0.0, z); + let expected = independent_sky(d); + assert_eq!(sky.radiance(d).unwrap(), expected); + assert_eq!( + job::CpuSky { rotation_rad: sky.rotation_rad + 7.0, ..sky } + .radiance(Vec3::new(radius * (TAU / 3.0).cos(), radius * (TAU / 3.0).sin(), z)) + .unwrap(), + expected + ); + if row < 128 { + let top = (PI * f64::from(row) / 256.0).cos(); + let bottom = (PI * f64::from(row + 1) / 256.0).cos(); + energy += expected * (0.5 * (top * top - bottom * bottom)); + } + } + // Analytic continuous gradient: albedo0.5 times cosine-weighted hemisphere. + let analytic = Vec3::new(0.75 * 0.5 + (0.25 - 0.75) * 0.4, 0.5 * 0.5, 0.25 * 0.5 + (1.0 - 0.25) * 0.4) * 1.75; + assert!((energy - analytic).len() < 0.0001, "finite GPU row policy converges to independent gradient energy"); + assert!(super::super::celestial::sample(sun, [1.0, 0.5]).is_err()); + assert_eq!(super::super::celestial::pdf(sun, -Vec3::Z).unwrap(), 0.0); +} +#[test] +fn cpu_celestial_prefixes_raw_ownership_quanta_and_memory_are_exact() { + let make = |samples, denoise| { + let original = celestial_fixture(samples, 2, true, true); + let options = + RaytraceOptions { denoise, output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), ..original.options }; + let request = ImageRequest { transparent_background: true, raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + let a = complete_presentation(make(7, true), 1); + let b = complete_presentation(make(7, true), 16384); + assert_eq!(a, b, "all immutable checkpoints/RAW/work are independent of pump quantum"); + assert_eq!(a.0.iter().map(|p| p.0).collect::>(), [1, 2, 3, 4, 5, 6]); + for (samples, png) in &a.0 { + assert_eq!(*png, complete_presentation(make(*samples, true), 3).1); + } + let expected = independent_celestial_mean(7, 2, true, true).map(|v| v as f32); + assert_eq!(native_exr_pixels(a.2.as_ref().unwrap()).get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 1.0]); + assert_eq!(a.2, complete_presentation(make(7, false), 1).2, "denoise never alters raw celestial radiance"); + let original = celestial_fixture(3, 1, false, false); + let base = admit(&original.scene, &original.request, &original.options).unwrap(); + let mut options = original.options.clone(); + options.sun = Some(Box::new(job::Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.7, radiance: [2.0, 3.0, 5.0] })); + options.sky = Some(Box::new(job::CpuSky::default())); + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + let extra = admit(&original.scene, &request, &options).unwrap(); + let boxes = (std::mem::size_of::() + std::mem::size_of::()) as u64; + assert_eq!(extra.preparation_bytes - base.preparation_bytes, 2 * boxes, "producer and captured request own separate, prepaid boxes"); + assert_eq!(options.retained_bytes().unwrap() - original.options.retained_bytes().unwrap(), boxes); + assert_eq!(original.options.retained_celestial_bytes().unwrap(), 0); + let wire = serde_json::to_value(RaytraceOptions::default()).unwrap(); + assert!(wire.get("sun").is_none() && wire.get("sky").is_none()); +} +#[test] +fn cpu_sun_continuation_cancel_and_work_refuse_before_mutation() { + for cancel in [false, true] { + let mut task = celestial_fixture(3, 2, true, true); + for _ in 0..100_000 { + if task.path.first().is_some_and(|p| p.stage_name() == "sun") { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert_eq!(task.path.first().unwrap().stage_name(), "sun"); + let before = (task.work.used(), task.pixel, task.progressive.as_ref().unwrap().film.samples()); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!((task.work.used(), task.pixel, task.progressive.as_ref().unwrap().film.samples()), before); + assert!(task.take_linear_exr().is_none()); + } +} + +#[test] +fn cpu_celestial_lens_adaptive_and_nested_glass_keep_complete_radiance_and_raw() { + let make = |adaptive: bool, lens: bool| { + let original = celestial_fixture(16, 1, true, true); + let options = RaytraceOptions { + adaptive: adaptive.then(|| Box::new(job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() })), + lens: lens.then_some(job::ThinLens { aperture_radius_mm: 0.01, focus_distance_mm: 1.0 }), + denoise: true, + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + let camera = crate::Camera { fov: 0.001, ..original.request.camera }; + let request = ImageRequest { camera, transparent_background: true, raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + let reference = complete_presentation(make(false, false), 1); + let pupil = complete_presentation(make(false, true), 1); + assert_eq!( + (reference.1.clone(), reference.2.clone()), + (pupil.1, pupil.2), + "a focused, fully covered Lambert receiver has no aperture exposure factor" + ); + let mut task = make(true, true); + let mut previews = Vec::new(); + let (png, raw, report) = loop { + match task.step_with_previews(1).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { samples_per_pixel, png } => { + previews.push((samples_per_pixel, png)); + assert!(task.take_linear_exr().is_none()); + } + ImagePoll::Complete(png) => break (png, task.take_linear_exr().unwrap(), task.sampling_report().unwrap()), + } + }; + assert_eq!(previews.iter().map(|p| p.0).collect::>(), (1..32).collect::>()); + assert_eq!(png, reference.1); + assert_eq!(Some(raw), reference.2, "pilot Sun/Sky samples must never leak into production RAW"); + assert_eq!((report.pilot_samples_per_pixel, report.production_samples, report.primary_path_evaluations), (16, 16, 32)); + let original = cpu_general_glass_fixture(8, true, 1.0); + let options = RaytraceOptions { + environment: None, + sun: Some(Box::new(job::Sun { direction: [0.0, 0.0, -1.0], angular_radius_rad: 0.7, radiance: [0.25, 0.5, 0.75] })), + sky: Some(Box::new(job::CpuSky { + gradient: crate::lighting::environment::SkyGradient { zenith: [1.0, 2.0, 3.0], horizon: [1.0, 2.0, 3.0], ground: [1.0, 2.0, 3.0] }, + rotation_rad: 1.75, + intensity: 1.0, + })), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + let actual = path_mean(ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap()).0; + let expected = [1.25 * (-0.4_f64).exp(), 2.5 * (-0.2_f64).exp(), 3.75 * (-0.4_f64).exp()]; + for (a, e) in actual.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "nested delta escape sees both emitters after physical Beer: {a} vs {e}"); + } +} +#[test] +fn cpu_hdr_and_finite_sun_are_additive_without_sky_or_default_source_substitution() { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + let make = |sun| { + let original = celestial_fixture(32, 2, sun, false); + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.731, 1.0, 4).unwrap(); + ImageTask::new_with_environment(original.scene, original.request, CancelToken::default(), original.options, Some(input)).unwrap() + }; + let base = path_mean(make(false)).0; + let combined = path_mean(make(true)).0; + let sun = independent_celestial_mean(32, 2, true, false); + for i in 0..3 { + assert!((combined[i] - base[i] - sun[i]).abs() < 1e-11, "HDR source and Sun retain independent proposals/escape MIS"); + } +} + +#[test] +fn cpu_celestial_maps_then_aging_feed_the_same_brdf_pdf_and_guides() { + let make = |explicit, half| { + let original = composed_map_aging_fixture(16, true, true, explicit, half); + let source = celestial_fixture(16, 2, true, true); + let options = RaytraceOptions { environment: None, sun: source.options.sun, sky: source.options.sky, ..original.options }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + for half in [false, true] { + let actual = complete_presentation(make(false, half), 1); + let expected = complete_presentation(make(true, half), 1); + assert_eq!( + (actual.0, actual.1, actual.2), + (expected.0, expected.1, expected.2), + "Sun/Sky use the composed mapped/aged material, shading normal and exact matte in every pass" + ); + } +} + +#[test] +fn cpu_sun_sampler_pdf_support_agrees_at_shared_radius_limits_and_oblique_axes() { + for direction in [[0.0, 0.0, 1.0], [0.2, -0.3, 0.9], [1.0, 1.0, 1.0]] { + for radius in [0.001, std::f64::consts::FRAC_PI_2] { + let sun = job::Sun { direction, angular_radius_rad: radius, radiance: [1.0; 3] }; + for u in [0.0, 0.5, 1.0_f64.next_down()] { + let sample = super::super::celestial::sample(sun, [u, 0.731]).unwrap(); + assert_eq!(super::super::celestial::pdf(sun, sample.direction).unwrap(), sample.pdf, "axis={direction:?},radius={radius},u={u}"); + assert_eq!(super::super::celestial::radiance(sun, sample.direction).unwrap(), Vec3::new(1.0, 1.0, 1.0)); + } + } + } + let mut options = celestial_fixture(3, 2, true, false).options; + options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]); + assert!(options.validate().unwrap_err().message.contains("eight")); + options.lights.as_mut().unwrap().pop(); + assert!(options.validate().is_ok()); + options.sun.as_mut().unwrap().angular_radius_rad = 0.0; + assert!(options.validate().is_err(), "zero radius stays an explicit hard source, never a widened finite cap"); +} + +#[test] +fn cpu_uniform_sky_preserves_the_existing_constant_environment_pixels_and_work() { + let make = |sky: bool| { + let original = path_fixture(7, 2, false); + let options = RaytraceOptions { + environment: if sky { None } else { original.options.environment }, + sky: sky.then(|| { + Box::new(job::CpuSky { + gradient: crate::lighting::environment::SkyGradient { zenith: [1.0; 3], horizon: [1.0; 3], ground: [1.0; 3] }, + rotation_rad: 0.731, + intensity: 1.0, + }) + }), + output: Some(Box::new(job::OutputOptions { linear_exr: true, ..Default::default() })), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + assert_eq!( + complete_presentation(make(false), 1), + complete_presentation(make(true), 1), + "uniformSky adds no hidden pass/RNG/work and uses the same existing constant-environment target" + ); +} + +#[test] +fn cpu_finite_sun_real_opaque_visibility_keeps_the_camera_aperture_separate() { + let make = |blocked| { + let original = path_fixture(16, 1, blocked); + let options = RaytraceOptions { + environment: None, + emissions: None, + sun: Some(Box::new(job::Sun { direction: [1.0, 0.0, 1.0], angular_radius_rad: 0.1, radiance: [2.0, 3.0, 5.0] })), + ..original.options + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request }; + ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap() + }; + assert!(path_mean(make(false)).0.into_iter().all(|v| v > 0.0)); + assert_eq!(path_mean(make(true)).0, [0.0; 3], "all cap directions meet the real black ceiling outside the primary aperture"); +} + +#[test] +fn composed_cpu_volume_sun_and_sky_use_phase_nee_physical_sources_and_complementary_escape_mis() { + let sources = celestial_fixture(1, 1, true, true).options; + let build = |samples, depth| { + let base = cpu_volume_fixture(samples, depth, false, false, Some(job::volume::HomogeneousVolume { anisotropy: 0.3, ..volume_slab() })); + let options = RaytraceOptions { environment: None, sun: sources.sun.clone(), sky: sources.sky.clone(), ..base.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + for depth in [1, 2, 16] { + let expected = independent_volume_celestial(64, depth, build(1, depth).options.volume.unwrap(), false, 1, &independent_sky, true); + let actual = volume_mean(build(64, depth)); + assert_eq!(actual.1, expected.1); + for (a, e) in actual.0.into_iter().zip(expected.0) { + assert!((a - e).abs() < 1e-12, "volume+Sun/Sky depth{depth}: {a} vs independent {e}"); + } + } + let output = complete_presentation(build(7, 4), 1); + assert_eq!(output, complete_presentation(build(7, 4), 16384)); + for (n, png) in &output.0 { + assert_eq!(*png, complete_presentation(build(*n, 4), 3).1); + } + let expected = independent_volume_celestial(7, 4, build(1, 4).options.volume.unwrap(), false, 1, &independent_sky, true); + assert_eq!( + native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0, + [expected.0[0] as f32, expected.0[1] as f32, expected.0[2] as f32, (f64::from(expected.1) / 7.0) as f32] + ); +} +#[test] +fn composed_cpu_subsurface_sun_and_sky_keep_phase_only_delta_escape_and_physical_beer() { + let sources = celestial_fixture(1, 1, true, true).options; + let build = |samples| { + let base = cpu_subsurface_fixture(samples, false, 0, 16, [1.0, 0.0], -0.6, None); + let options = RaytraceOptions { environment: None, sun: sources.sun.clone(), sky: sources.sky.clone(), ..base.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap() + }; + let environment = |d: Vec3| independent_sky(d) + if d.z >= 0.7_f64.cos() { Vec3::new(2.0, 3.0, 5.0) } else { Vec3::ZERO }; + let expected = independent_single_box_subsurface(&build(64), &environment); + for (a, e) in path_mean(build(64)).0.into_iter().zip(expected) { + assert!((a - e).abs() < 1e-12, "SSS+Sun/Sky escape/Beer: {a} vs independent {e}"); + } + let output = complete_presentation(build(7), 1); + assert_eq!(output, complete_presentation(build(7), 16384)); + for (n, png) in &output.0 { + assert_eq!(*png, complete_presentation(build(*n), 3).1); + } +} + +#[test] +fn cpu_volume_empty_scene_integrates_boxes_before_the_original_ortho_origin_and_beyond_its_far_plane() { + let base = cpu_volume_fixture(64, 1, false, false, None); + let original = primary_ray(&base.request, 0.5, 0.5, base.clip).unwrap(); + let h = (0..64).filter(|n| progressive::variates(9, 0, *n, 0x5041_5448_6000)[0] < 1.0 - (-1.0_f64).exp()).count(); + assert!(h > 0 && h < 64); + for [lo, hi] in [[-1000.0, -998.0], [original.origin().z + 10.0, original.origin().z + 12.0]] { + if hi < 0.0 { + assert!(-hi + original.origin().z > original.interval()[1], "the far fixture must lie beyond the old complete model interval"); + } else { + assert!(lo > original.origin().z, "the near fixture must lie before the old optical origin"); + } + let volume = job::volume::HomogeneousVolume { + min_mm: [-10.0, -10.0, lo], + max_mm: [10.0, 10.0, hi], + extinction_per_mm: 0.5, + scattering_albedo: [0.0; 3], + anisotropy: 0.0, + }; + let options = RaytraceOptions { volume: Some(volume), environment: None, ..base.options.clone() }; + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let build = || ImageTask::new(base.scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); + let actual = volume_mean(build()); + assert_eq!(actual.0, [0.0; 3]); + assert_eq!((actual.1, actual.2), (h as u16, 64)); + let output = complete_presentation(build(), 1); + assert_eq!(output, complete_presentation(build(), 16384)); + let alpha = h as f64 / 64.0; + assert_eq!(native_exr_pixels(output.2.as_deref().unwrap()).get_pixel(0, 0).0, [0.0, 0.0, 0.0, alpha as f32]); + assert_eq!(alpha_pixel(&output.1), [0, 0, 0, (alpha * 255.0).round() as u8]); + assert_eq!(build().request.camera, base.request.camera); + assert_eq!(build().scene.bounds, base.scene.bounds); + assert!(build().scene.meshes.is_empty()); + } +} + +fn prepared_general_glass_fixture(nested: bool, ior: f64) -> ImageTask { + let original = cpu_general_glass_fixture(8, nested, ior); + let original_work = original.work.used(); + let scene = original.scene.clone(); + let request = original.request.clone(); + let options = original.options.clone(); + drop(original); + let cancel = CancelToken::default(); + let proof = certify_for_request(&scene, &request, &options, &cancel).unwrap().unwrap(); + assert!(proof.legacy.is_none()); + assert_eq!((proof.general.len(), proof.general.capacity()), (1, 1)); + assert!(proof.general[0].ready()); + assert!(proof.work_used > 0); + let certified_work = proof.work_used; + let allocation = proof.general.as_ptr(); + let source = Arc::as_ptr(&scene.meshes[0].mesh); + let task = ImageTask::new_prepared(scene, request, cancel, options, None, Some(proof)).unwrap(); + assert_eq!(task.glass.as_ptr(), allocation, "the certified allocation moves directly into the image task"); + assert_eq!(Arc::as_ptr(&task.scene.meshes[0].mesh), source, "certification never rebuilds or repairs the rendered boundary"); + assert!(task.glass[0].ready()); + assert_eq!(task.work.used(), original_work + certified_work, "the one certificate debit follows the proof"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + task +} + +#[test] +fn cpu_general_glass_strict_preparation_moves_the_ready_boundary_without_recertifying_or_changing_any_prefix() { + for nested in [false, true] { + for ior in [1.0, 1.5] { + let standalone = complete_presentation(cpu_general_glass_fixture(8, nested, ior), 1); + assert!(standalone.2.is_some(), "compare the actual unmodified raw master as well as every PNG"); + for quantum in [1, 16384] { + let prepared = complete_presentation(prepared_general_glass_fixture(nested, ior), quantum); + assert_eq!(prepared, standalone, "all prefixes, final PNG, raw EXR and cumulative work must match exactly"); + } + } + } +} + +#[test] +fn cpu_general_glass_prepared_cancel_and_work_exhaustion_keep_the_original_certificate_debit_without_a_sample() { + for cancel in [false, true] { + let mut task = prepared_general_glass_fixture(true, 1.5); + let used = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(task.glass[0].ready(), "neither failure replaces a complete proof with a fresh cursor"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.take_linear_exr().is_none()); + assert!(task.encoder.is_none() && task.output.is_empty()); + } +} diff --git a/crates/render/src/raytrace/progressive.rs b/crates/render/src/raytrace/progressive.rs index cdb02c29d..11ac7efa3 100644 --- a/crates/render/src/raytrace/progressive.rs +++ b/crates/render/src/raytrace/progressive.rs @@ -1,14 +1,195 @@ //! Deterministic counter sampling and owned camera-film continuation. //! No target sample count, work quantum or preview cadence enters the sampler. +use crate::{ + film::{ + adaptive::{AdaptiveCameraFilm, CountsPlane, SamplingIdentity}, + primary::PrimaryFilm, + }, + job::{ + CancelToken, CpuBudget, CpuProgressiveOptions, ErrorCode, JobError, Result, + adaptive::{AdaptiveSampling, PreviewStage, SamplingReport}, + }, +}; -use crate::{film::primary::PrimaryFilm, job::CpuProgressiveOptions}; - +pub(super) enum CameraFilm { + Uniform(PrimaryFilm), + // One fixed, fallibly prepaid metadata slot keeps the ordinary task's layout + // small. Its two pixel arrays are allocated only for explicit adaptive intent. + Adaptive(Vec), +} +impl CameraFilm { + pub(super) fn required_bytes( + width: u32, + height: u32, + options: CpuProgressiveOptions, + adaptive: Option<&AdaptiveSampling>, + budget: CpuBudget, + ) -> Result { + match adaptive { + None => PrimaryFilm::required_bytes(width, height, options, budget), + Some(adaptive) => AdaptiveCameraFilm::required_bytes(width, height, options, *adaptive, budget), + } + } + pub(super) fn new( + width: u32, + height: u32, + options: CpuProgressiveOptions, + adaptive: Option<&AdaptiveSampling>, + budget: CpuBudget, + bytes: u64, + cancel: &CancelToken, + ) -> Result { + match adaptive { + None => PrimaryFilm::new(width, height, options, bytes, cancel, budget).map(Self::Uniform), + Some(adaptive) => { + cancel.check()?; + let mut slot = Vec::new(); + slot.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve CPU adaptive film state"))?; + if slot.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "CPU adaptive state capacity exceeds admission")); + } + slot.push(AdaptiveCameraFilm::new(width, height, options, *adaptive, budget, bytes, cancel)?); + Ok(Self::Adaptive(slot)) + } + } + } + fn state(&self) -> Result<&AdaptiveCameraFilm> { + match self { + Self::Adaptive(slot) => slot.first().ok_or_else(|| JobError::new(ErrorCode::Internal, "CPU adaptive film state is missing")), + _ => Err(JobError::new(ErrorCode::Internal, "ordinary film has no adaptive state")), + } + } + fn state_mut(&mut self) -> Result<&mut AdaptiveCameraFilm> { + match self { + Self::Adaptive(slot) => slot.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "CPU adaptive film state is missing")), + _ => Err(JobError::new(ErrorCode::Internal, "ordinary film has no adaptive state")), + } + } + pub(super) fn samples(&self) -> u32 { + match self { + Self::Uniform(film) => film.samples(), + Self::Adaptive(slot) => slot.first().map_or(0, AdaptiveCameraFilm::completed_passes), + } + } + pub(super) fn initialized(&self) -> usize { + match self { + Self::Uniform(film) => film.initialized(), + Self::Adaptive(slot) => slot.first().map_or(0, AdaptiveCameraFilm::initialized), + } + } + pub(super) fn ready(&self) -> bool { + match self { + Self::Uniform(film) => film.ready(), + Self::Adaptive(slot) => slot.first().is_some_and(AdaptiveCameraFilm::ready), + } + } + pub(super) fn initialize_one(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + match self { + Self::Uniform(film) => film.initialize_one(cancel, charge), + Self::Adaptive(_) => self.state_mut()?.initialize_one(cancel, charge), + } + } + pub(super) fn add( + &mut self, + index: usize, + ordinal: u32, + rgb: [f64; 3], + covered: bool, + cancel: &CancelToken, + charge: &mut impl FnMut() -> Result<()>, + ) -> Result<()> { + match self { + Self::Uniform(film) => film.add(index, ordinal, rgb, covered, cancel, charge), + Self::Adaptive(_) => { + let film = self.state_mut()?; + if ordinal != film.completed_passes() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU adaptive absolute pass disagrees with its film")); + } + let identity = + film.sampling_identity(index)?.ok_or_else(|| JobError::new(ErrorCode::Internal, "stopped CPU adaptive pixel was traced"))?; + film.add(index, identity, rgb, covered, cancel, charge) + } + } + } + pub(super) fn pixel(&self, index: usize) -> Result<([f64; 3], u16, u16)> { + match self { + Self::Uniform(film) => film.pixel(index), + Self::Adaptive(_) => { + let pass = self.state()?.complete_pass()?; + let (mean, _) = pass.pixel(index)?; + let counts = pass.counts().pixel(index)?; + Ok((mean, counts.covered(), counts.samples())) + } + } + } + pub(super) fn counts(&self) -> Result> { + match self { + Self::Uniform(_) => Ok(None), + Self::Adaptive(_) => self.state()?.counts_plane().map(Some), + } + } + pub(super) fn identity(&self, index: usize, seed: u32) -> Result> { + match self { + Self::Uniform(film) => Ok(Some(SamplingIdentity { seed, ordinal: film.samples(), stage: PreviewStage::Production })), + Self::Adaptive(_) => self.state()?.sampling_identity(index), + } + } + pub(super) fn skip(&mut self, index: usize, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + self.state_mut()?.skip_one(index, cancel, charge) + } + pub(super) fn resetting(&self) -> bool { + matches!(self, Self::Adaptive(slot) if slot.first().is_some_and(AdaptiveCameraFilm::resetting)) + } + pub(super) fn reset_progress(&self) -> usize { + match self { + Self::Adaptive(slot) => slot.first().map_or(0, AdaptiveCameraFilm::next_pixel), + _ => 0, + } + } + pub(super) fn reset_one(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + self.state_mut()?.reset_one(cancel, charge) + } + pub(super) fn pilot_complete(&self) -> bool { + match self { + Self::Uniform(_) => false, + Self::Adaptive(slot) => slot.first().is_some_and(|film| { + film.complete_pass().is_ok_and(|pass| { + let metadata = pass.metadata(); + metadata.stage == PreviewStage::Pilot && metadata.completed == metadata.pilot_samples + }) + }), + } + } + pub(super) fn begin_production(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + self.state_mut()?.begin_production(cancel, charge) + } + pub(super) fn report(&self) -> Result> { + match self { + Self::Uniform(_) => Ok(None), + Self::Adaptive(_) => self.state()?.report().map(Some), + } + } +} pub(super) struct Progressive { - pub film: PrimaryFilm, + pub film: CameraFilm, pub options: CpuProgressiveOptions, + pub target: u32, pub resolving: bool, pub resolve_pixel: usize, } +impl Progressive { + pub(super) fn identity(&self, pixel: usize) -> Result { + self.film.identity(pixel, self.options.seed)?.ok_or_else(|| JobError::new(ErrorCode::Internal, "stopped adaptive pixel requested variates")) + } + pub(super) fn variates(&self, pixel: usize, domain: u64) -> Result<[f64; 2]> { + let identity = self.identity(pixel)?; + Ok(variates(identity.seed, pixel as u64, identity.ordinal, domain)) + } + pub(super) fn area_key(&self, pixel: usize, value: u64) -> Result { + let identity = self.identity(pixel)?; + Ok(value ^ (u64::from(identity.seed ^ self.options.seed) << 32)) + } +} /// Integer-only mixing before conversion to exactly representable 53-bit unit /// variates. Domains separate camera, BSDF and environment choices at each bounce. diff --git a/crates/render/src/raytrace/reflection.rs b/crates/render/src/raytrace/reflection.rs index 958f36267..7b907c256 100644 --- a/crates/render/src/raytrace/reflection.rs +++ b/crates/render/src/raytrace/reflection.rs @@ -30,9 +30,7 @@ pub fn rough_specular(surface: OpaqueSurface, normal: Vec3, view: Vec3, u: [f64; let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("GGX normal"))?; let axis = if n.z.abs() < 0.9 { Vec3::Z } else { Vec3::X }; let frame = VisualFrame::new(n, axis.cross(n)).map_err(|_| TraceError::InvalidInput("GGX visible frame"))?; - let matched = - AnisotropicSurface::new(surface.base_color(), surface.metallic(), surface.roughness(), surface.roughness(), surface.dielectric_ior()) - .map_err(|_| TraceError::InvalidInput("GGX visible surface"))?; + let matched = AnisotropicSurface::from_isotropic_optical(surface); matched .sample_visible_reflection(frame, n, view, u) .map(|s| s.map(|s| ReflectionSample { direction: s.direction, weight: s.weight, pdf: s.pdf })) diff --git a/crates/render/src/raytrace/reflection_vndf_tests.rs b/crates/render/src/raytrace/reflection_vndf_tests.rs index 25b5b28e9..9cf3219fe 100644 --- a/crates/render/src/raytrace/reflection_vndf_tests.rs +++ b/crates/render/src/raytrace/reflection_vndf_tests.rs @@ -39,3 +39,37 @@ fn explicit_ndf_control_is_not_the_production_visible_sampler() { assert_eq!(mirror_sample.pdf, 1.0); assert_eq!(mirror_sample.weight, Vec3::new(1.0, 1.0, 1.0)); } + +#[test] +fn authored_point_zero_two_vndf_matches_independent_normal_view_density_and_furnace() { + let old = OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.045, 1.5).unwrap(); + let finish = old.with_authored_finish(old.base_color(), 1.0, 0.02).unwrap(); + let a2 = 0.02_f64.powi(4); + let mut sum = 0.0; + let mut oracle = 0.0; + for i in 0..4096 { + let u = (f64::from(i) + 0.5) / 4096.0; + let denominator = (1.0 - u) + a2 * u; + let cosine = ((1.0 - u) - a2 * u) / denominator; + let expected = 2.0 * cosine / (cosine + (a2 + (1.0 - a2) * cosine * cosine).sqrt()); + let sample = rough_specular(finish, Vec3::Z, Vec3::Z, [u, 0.375]).unwrap().unwrap(); + let pdf = denominator * denominator / (std::f64::consts::PI * a2 * 4.0); + assert!((sample.direction.z - cosine).abs() < 1e-14); + assert!((sample.pdf - pdf).abs() < 1e-12 * pdf.max(1.0)); + assert!((sample.weight - Vec3::new(expected, expected, expected)).len() < 1e-12); + sum += sample.weight.x; + oracle += expected; + } + assert!((sum - oracle).abs() < 1e-10); + assert!((sum / 4096.0 - 1.0).abs() < 1e-8, "independent white-furnace bound at narrow finite GGX roughness"); + assert!(rough_specular(finish, Vec3::Z, Vec3::Z, [1.0 - a2 / 4.0, 0.375]).unwrap().is_none(), "a below-surface reflection retains its null mass"); + // The old constructor remains the production baseline for every old finish; + // the optical adapter introduces no new arithmetic or variate consumption. + let base = crate::anisotropic_surface::AnisotropicSurface::new(old.base_color(), 1.0, 0.045, 0.045, 1.5).unwrap(); + let frame = crate::anisotropic_surface::VisualFrame::new(Vec3::Z, -Vec3::Y).unwrap(); + for u in [[0.0, 0.0], [0.125, 0.375], [0.75, 0.5]] { + let actual = rough_specular(old, Vec3::Z, Vec3::Z, u).unwrap().unwrap(); + let original = base.sample_visible_reflection(frame, Vec3::Z, Vec3::Z, u).unwrap().unwrap(); + assert_eq!((actual.direction, actual.pdf, actual.weight), (original.direction, original.pdf, original.weight)); + } +} diff --git a/crates/render/src/subsurface.rs b/crates/render/src/subsurface.rs index eb53adf17..b979e2a7b 100644 --- a/crates/render/src/subsurface.rs +++ b/crates/render/src/subsurface.rs @@ -3,6 +3,8 @@ //! rate in inverse millimetres, not an invented density or surface-opacity hack. use super::TransmissionError; use serde::{Deserialize, Serialize}; +use solidcore_record::Vec3; +use solidcraft_geom::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -25,6 +27,66 @@ impl Subsurface { pub fn active(self) -> bool { self.scattering_per_mm > 0.0 } + /// Analog collision distance in millimetres. A positive infinity means the + /// collision is beyond every finite admitted query, not an unbounded loop. + /// Counter zero uses the centre of its lowest53-bit cell; no other sample, + /// radiance, optical number or geometric distance is clamped. + pub fn free_flight(self, uniform: f64) -> Result { + self.validate()?; + if !self.active() || !uniform.is_finite() || !(0.0..1.0).contains(&uniform) { + return Err(TransmissionError::Scattering); + } + let open = if uniform == 0.0 { 1.0 / 18_014_398_509_481_984.0 } else { uniform }; + let distance = -(-open).ln_1p() / self.scattering_per_mm; + if distance.is_nan() || distance <= 0.0 { + return Err(TransmissionError::Scattering); + } + Ok(distance) + } + /// Normalized HG density over propagation directions, per steradian. + pub fn phase(self, cosine: f64) -> Result { + self.validate()?; + if !cosine.is_finite() || !(-1.0..=1.0).contains(&cosine) { + return Err(TransmissionError::Angle); + } + let g = self.anisotropy; + let denominator = 1.0 + g * g - 2.0 * g * cosine; + Ok((1.0 - g * g) / (4.0 * std::f64::consts::PI * denominator * denominator.sqrt())) + } + /// Inverse HG distribution continuous at g=0. The small-g expression is an + /// algebraic rearrangement of the same inverse, never an isotropic shortcut. + pub fn sample_cosine(self, uniform: f64) -> Result { + self.validate()?; + if !uniform.is_finite() || !(0.0..1.0).contains(&uniform) { + return Err(TransmissionError::Scattering); + } + let g = self.anisotropy; + let cosine = if g.abs() < 0.1 { + let t = 2.0 * uniform - 1.0; + let numerator = t + 0.5 * g * (3.0 + t * t) + g * g * t + 0.5 * g * g * g * (t * t - 1.0); + numerator / (1.0 + g * t).powi(2) + } else { + let ratio = (1.0 - g * g) / (1.0 - g + 2.0 * g * uniform); + (1.0 + g * g - ratio * ratio) / (2.0 * g) + }; + // Floating roundoff at the two geometric poles cannot change a unit + // direction's cosine domain. This is not a radiance or density clamp. + Ok(cosine.clamp(-1.0, 1.0)) + } + pub fn sample_direction(self, incoming: Vec3, uniform: [f64; 2]) -> Result { + if !uniform[1].is_finite() || !(0.0..1.0).contains(&uniform[1]) { + return Err(TransmissionError::Scattering); + } + let direction = crate::surface::unit_direction(incoming).map_err(|_| TransmissionError::Direction)?; + let cosine = self.sample_cosine(uniform[0])?; + let radius = ((1.0 - cosine) * (1.0 + cosine)).sqrt(); + let angle = std::f64::consts::TAU * uniform[1]; + let axis = if direction.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z }; + let x = crate::surface::unit_direction(axis.cross(direction)).map_err(|_| TransmissionError::Direction)?; + let y = direction.cross(x); + crate::surface::unit_direction(x * (radius * angle.cos()) + y * (radius * angle.sin()) + direction * cosine) + .map_err(|_| TransmissionError::Direction) + } pub fn survival(self, distance_mm: f64) -> Result { self.validate()?; if !distance_mm.is_finite() || distance_mm < 0.0 { @@ -49,3 +111,71 @@ mod tests { assert!(!Subsurface { scattering_per_mm: 0.0, ..s }.active()); } } + +#[cfg(test)] +mod transport_math_tests { + use super::*; + #[test] + fn free_flight_matches_independent_survival_inverse_and_keeps_tiny_rate_queries_bounded() { + for rate in [0.001, 0.4, 100.0] { + let s = Subsurface { scattering_per_mm: rate, anisotropy: 0.0 }; + for u in [0.0, 1e-8, 0.1, 0.5, 1.0_f64.next_down()] { + let distance = s.free_flight(u).unwrap(); + assert!(distance > 0.0 && distance.is_finite()); + let open = if u == 0.0 { 2.0_f64.powi(-54) } else { u }; + assert!((s.survival(distance).unwrap() - (1.0 - open)).abs() < 3e-15); + } + } + let tiny = Subsurface { scattering_per_mm: f64::MIN_POSITIVE * f64::EPSILON, anisotropy: 0.0 }; + assert_eq!(tiny.free_flight(0.5).unwrap(), f64::INFINITY, "an infinite flight only means no collision on a finite query"); + assert_eq!(tiny.survival(1e12).unwrap(), 1.0); + let inactive = Subsurface { scattering_per_mm: 0.0, anisotropy: 0.0 }; + assert!(inactive.free_flight(0.5).is_err()); + for value in [f64::NAN, f64::INFINITY, -0.1, 1.0] { + assert!(Subsurface { scattering_per_mm: 1.0, anisotropy: 0.0 }.free_flight(value).is_err()); + } + } + #[test] + fn hg_inverse_matches_an_independent_cdf_for_zero_small_and_extreme_anisotropy() { + for g in [-0.95, -0.1, -1e-10, 0.0, 1e-10, 0.1, 0.95] { + let s = Subsurface { scattering_per_mm: 1.0, anisotropy: g }; + for u in [0.0, 1e-8, 0.001, 0.1, 0.5, 0.9, 0.999, 1.0_f64.next_down()] { + let c = s.sample_cosine(u).unwrap(); + // Integral of2pi*p(c), rationalized independently of the inverse. + let root = (1.0 + g * g - 2.0 * g * c).sqrt(); + let cdf = (1.0 - g) * (1.0 + c) / ((1.0 + g + root) * root); + assert!((cdf - u).abs() < 2e-12, "g{g},u{u}: CDF{cdf}"); + for incoming in [Vec3::Z, -Vec3::Z, Vec3::X, Vec3::new(0.3, 0.4, 0.5)] { + let direction = s.sample_direction(incoming, [u, 0.37]).unwrap(); + let incoming = crate::surface::unit_direction(incoming).unwrap(); + assert!((direction.len() - 1.0).abs() < 1e-15); + assert!((direction.dot(incoming) - c).abs() < 1e-15); + } + if g == 0.0 { + assert_eq!(c, 2.0 * u - 1.0); + } + } + } + } + fn integrate(f: &impl Fn(f64) -> f64, a: f64, b: f64, eps: f64, depth: u8) -> f64 { + let m = (a + b) * 0.5; + let q1 = (a + m) * 0.5; + let q3 = (m + b) * 0.5; + let coarse = (b - a) * (f(a) + 4.0 * f(m) + f(b)) / 6.0; + let fine = (b - a) * (f(a) + 4.0 * f(q1) + 2.0 * f(m) + 4.0 * f(q3) + f(b)) / 12.0; + if depth == 0 || (fine - coarse).abs() < 15.0 * eps { + fine + (fine - coarse) / 15.0 + } else { + integrate(f, a, m, eps * 0.5, depth - 1) + integrate(f, m, b, eps * 0.5, depth - 1) + } + } + #[test] + fn hg_density_has_unit_mass_and_its_authored_first_moment_by_independent_quadrature() { + for g in [-0.95, -0.1, -1e-10, 0.0, 1e-10, 0.1, 0.95] { + let s = Subsurface { scattering_per_mm: 1.0, anisotropy: g }; + let density = |c| std::f64::consts::TAU * s.phase(c).unwrap(); + assert!((integrate(&density, -1.0, 1.0, 1e-13, 24) - 1.0).abs() < 2e-11); + assert!((integrate(&|c| c * density(c), -1.0, 1.0, 1e-13, 24) - g).abs() < 2e-11); + } + } +} diff --git a/crates/render/src/surface.rs b/crates/render/src/surface.rs index 69a629b61..e1727474f 100644 --- a/crates/render/src/surface.rs +++ b/crates/render/src/surface.rs @@ -65,6 +65,27 @@ impl OpaqueSurface { Ok(Self { base_color, metallic, roughness, dielectric_ior, clear_coat: None }) } + /// Bounded runtime optical finish, matching authored aging's 0.02..1 domain. + /// The public appearance constructor keeps its historical 0.045 minimum. This + /// explicit internal route preserves authored values without a clamp, retains + /// IOR/coat identity and validates every newly supplied component. + #[cfg(any(feature = "raytrace-cpu", test))] + pub(crate) fn with_authored_finish(mut self, base_color: Vec3, metallic: f64, roughness: f64) -> Result { + if !base_color.is_finite() || ![base_color.x, base_color.y, base_color.z].into_iter().all(|c| (0.0..=1.0).contains(&c)) { + return Err(SurfaceError::BaseColor); + } + if !metallic.is_finite() || !(0.0..=1.0).contains(&metallic) { + return Err(SurfaceError::Metallic); + } + if !roughness.is_finite() || !(0.02..=1.0).contains(&roughness) { + return Err(SurfaceError::Roughness); + } + self.base_color = base_color; + self.metallic = metallic; + self.roughness = roughness; + Ok(self) + } + /// Runtime optical layer; never serialized into a document appearance. pub fn with_clear_coat(mut self, coat: crate::clear_coat::ClearCoat) -> Self { self.clear_coat = if coat.weight() == 0.0 { None } else { Some(coat) }; diff --git a/crates/render/src/texture_input.rs b/crates/render/src/texture_input.rs index 63982a0ec..adbe62882 100644 --- a/crates/render/src/texture_input.rs +++ b/crates/render/src/texture_input.rs @@ -110,6 +110,9 @@ impl TextureSource { } pub fn new(bytes: Vec, role: MapRole) -> Result { let format = admitted_format(&bytes, bytes.capacity())?; + if format == ImageFormat::Png { + png_metadata::validate(&bytes)?; + } let (width, height) = guarded(|| { let mut decoder = reader(&bytes, format).into_decoder().map_err(|e| invalid(e.to_string()))?; if !matches!(decoder.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::Rgb8 | image::ColorType::Rgba8) { @@ -160,12 +163,12 @@ impl TextureSource { } Ok(self.bytes.clone()) } - /// Bounded whole-image codec work, intended for a caller-owned worker. Cancellation is - /// checked at the codec boundary, not during PNG/JPEG decoding. No partial image escapes. #[cfg(all(test, feature = "raytrace-cpu"))] pub(crate) fn encoded_weak(&self) -> std::sync::Weak> { Arc::downgrade(&self.bytes) } + /// Bounded whole-image codec work, intended for a caller-owned worker. Cancellation is + /// checked at the codec boundary, not during PNG/JPEG decoding. No partial image escapes. pub fn decode(&self, cancelled: impl Fn() -> bool) -> Result { if cancelled() { return Err(invalid("texture decoding cancelled")); diff --git a/crates/render/src/texture_input/png_metadata.rs b/crates/render/src/texture_input/png_metadata.rs index ba90cf63f..3fb896fb8 100644 --- a/crates/render/src/texture_input/png_metadata.rs +++ b/crates/render/src/texture_input/png_metadata.rs @@ -312,7 +312,7 @@ impl PngMetadata { } Ok(matches!(self.phase, Phase::Done)) } - #[cfg(all(test, feature = "raytrace-cpu"))] + #[cfg(test)] pub(crate) fn phase_name(&self) -> &'static str { match self.phase { Phase::Header => "metadata_header", diff --git a/crates/render/src/texture_input/tests.rs b/crates/render/src/texture_input/tests.rs index 36b4bc959..3abfec1ec 100644 --- a/crates/render/src/texture_input/tests.rs +++ b/crates/render/src/texture_input/tests.rs @@ -64,6 +64,181 @@ fn texture_input_caps_encoded_storage_and_refuses_precision_loss() { assert!(TextureSource::new(out.into_inner(), MapRole::NormalOpenGl).is_err()); } +fn metadata_chunk(kind: &[u8; 4], data: &[u8]) -> Vec { + // Independent bitwise IEEE CRC; production uses its fixed lookup table. + let mut out = (data.len() as u32).to_be_bytes().to_vec(); + out.extend(kind); + out.extend(data); + let mut crc = u32::MAX; + for byte in kind.iter().chain(data) { + crc ^= u32::from(*byte); + for _ in 0..8 { + crc = if crc & 1 == 0 { crc >> 1 } else { (crc >> 1) ^ 0xedb88320 }; + } + } + out.extend((!crc).to_be_bytes()); + out +} +fn normalized_exif(entries: u16, orientation: u16) -> Vec { + let mut data = b"II".to_vec(); + data.extend(42_u16.to_le_bytes()); + data.extend(8_u32.to_le_bytes()); + data.extend(entries.to_le_bytes()); + for i in 0..entries { + data.extend((if i == 0 { 0x112_u16 } else { 0xc000 + i }).to_le_bytes()); + data.extend(3_u16.to_le_bytes()); + data.extend(1_u32.to_le_bytes()); + data.extend((if i == 0 { orientation } else { i }).to_le_bytes()); + data.extend(0_u16.to_le_bytes()); + } + data.extend(0_u32.to_le_bytes()); + data +} +fn insert_metadata(mut image: Vec, kind: &[u8; 4], data: &[u8], before_data: bool) -> Vec { + let at = if before_data { 33 } else { image.len() - 12 }; + image.splice(at..at, metadata_chunk(kind, data)); + image +} +#[test] +fn png_metadata_policy_refuses_icc_and_rotated_or_misordered_exif_before_any_codec() { + let plain = png(2, 1); + let expected = TextureSource::new(plain.clone(), MapRole::BaseColor).unwrap().decode(|| false).unwrap(); + let normalized = insert_metadata(plain.clone(), b"eXIf", &normalized_exif(8, 1), true); + let decoded = TextureSource::new(normalized.clone(), MapRole::BaseColor).unwrap().decode(|| false).unwrap(); + assert_eq!(decoded.rgba(), expected.rgba()); + assert_eq!(normalized.as_slice(), TextureSource::new(normalized.clone(), MapRole::BaseColor).unwrap().bytes.as_ref().as_slice()); + for (kind, data, before, reason) in [ + (*b"eXIf", normalized_exif(1, 6), true, "orientation"), + (*b"eXIf", normalized_exif(1, 6), false, "precede IDAT"), + (*b"eXIf", normalized_exif(1, 1), false, "precede IDAT"), + (*b"iCCP", b"profile\0\0broken".to_vec(), true, "ICC"), + (*b"iCCP", b"profile\0\0broken".to_vec(), false, "ICC"), + ] { + let bytes = insert_metadata(plain.clone(), &kind, &data, before); + assert!(png_metadata::validate(&bytes).unwrap_err().to_string().contains(reason)); + assert!(TextureSource::new(bytes, MapRole::BaseColor).err().unwrap().to_string().contains(reason)); + } +} +#[test] +fn png_metadata_policy_rejects_a_small_icc_container_before_its_large_partial_inflate() { + use std::io::Write; + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + for _ in 0..10_240 { + encoder.write_all(&[0; 4096]).unwrap(); + } + let mut compressed = encoder.finish().unwrap(); + compressed.truncate(compressed.len() - 6); + let mut icc = b"profile\0\0".to_vec(); + icc.extend(compressed); + assert!(icc.len() < 128 * 1024, "the hostile source remains far below the existing16MiB cap"); + let bytes = insert_metadata(png(1, 1), b"iCCP", &icc, true); + // The pure policy never constructs a decoder; missing/truncated compressed + // contents cannot turn unsupported ICC into a None profile after inflation. + assert!(png_metadata::validate(&bytes).unwrap_err().to_string().contains("ICC")); + assert!(TextureSource::new(bytes, MapRole::Roughness).err().unwrap().to_string().contains("ICC")); +} +#[test] +fn png_metadata_cooperative_checks_cover_crc_ifd_tail_order_and_static_policy() { + let source = insert_metadata(png(2, 1), b"eXIf", &normalized_exif(32, 1), true); + let mut scanner = png_metadata::PngMetadata::new(true, true); + let mut entries = 0; + let mut done = false; + for _ in 0..1000 { + if scanner.phase_name() == "metadata_ifd" { + entries += 1; + } + if scanner.step(&source).unwrap() { + done = true; + break; + } + } + assert!(done); + assert_eq!(entries, 33, "32 exact IFD entries plus their bounded final transition"); + let mut corrupt = source.clone(); + let idat = corrupt.windows(4).position(|kind| kind == b"IDAT").unwrap(); + corrupt[idat + 4] ^= 0xff; + let mut scanner = png_metadata::PngMetadata::new(true, true); + assert!((0..1000).find_map(|_| scanner.step(&corrupt).err()).unwrap().to_string().contains("CRC")); + for kind in [*b"IHDR", *b"PLTE", *b"ABCD", *b"acTL", *b"fcTL", *b"fdAT"] { + let hostile = insert_metadata(png(1, 1), &kind, &[0; 13], false); + let mut scanner = png_metadata::PngMetadata::new(true, true); + assert!((0..1000).find_map(|_| scanner.step(&hostile).err()).is_some(), "tail {kind:?} cannot escape validation without Reader::finish"); + } + let separated = insert_metadata(png(1, 1), b"vpAg", &[1], false); + let separated = insert_metadata(separated, b"IDAT", &[0], false); + let mut scanner = png_metadata::PngMetadata::new(true, true); + assert!((0..1000).find_map(|_| scanner.step(&separated).err()).unwrap().to_string().contains("consecutive")); +} + +#[test] +fn png_text_metadata_preflight_bills_real_vector_growth_under_the_existing_codec_cap() { + let mut image = png(1, 1); + let marker = image.windows(4).position(|kind| kind == b"IDAT").unwrap() - 4; + let tail = image.split_off(marker); + let entry = metadata_chunk(b"tEXt", b"k\0"); + let record_size = std::mem::size_of::() as u64; + let count = (MAX_CODEC_BYTES / (4 * record_size)).next_power_of_two() as usize; + let mut within = Vec::with_capacity(image.len() + count * entry.len() + tail.len()); + within.extend(&image); + for _ in 0..count { + within.extend(&entry); + } + within.extend(&tail); + assert!(within.len() < MAX_TEXTURE_BYTES); + // This is a pure allocation-free policy check, not a large codec allocation. + png_metadata::validate(&within).unwrap(); + let mut excessive = Vec::with_capacity(image.len() + (count + 1) * entry.len() + tail.len()); + excessive.extend(&image); + for _ in 0..count + 1 { + excessive.extend(&entry); + } + excessive.extend(&tail); + assert!(excessive.len() < MAX_TEXTURE_BYTES); + assert!( + png_metadata::validate(&excessive).unwrap_err().to_string().contains("codec allowance"), + "the next actual Vec growth would overlap old/new arrays above64MiB" + ); + assert!(TextureSource::new(excessive, MapRole::BaseColor).err().unwrap().to_string().contains("codec allowance")); +} + +#[test] +#[cfg(target_pointer_width = "64")] +fn png_text_metadata_bills_latin1_old_and_new_string_backing_before_a_codec_can_run() { + const MIB: usize = 1024 * 1024; + let base = png(1, 1); + let marker = base.windows(4).position(|kind| kind == b"IDAT").unwrap() - 4; + let prefix = &base[..marker]; + let tail = &base[marker..]; + let mut latin = Vec::with_capacity(12 * MIB + 2); + latin.extend(b"k\0"); + latin.resize(12 * MIB + 2, 0xff); + let large = metadata_chunk(b"tEXt", &latin); + let mut alone = Vec::with_capacity(prefix.len() + large.len() + tail.len()); + alone.extend(prefix); + alone.extend(&large); + alone.extend(tail); + png_metadata::validate(&alone).unwrap(); // No arbitrary12MiB text-size prohibition. + let count = 262_143; + let tiny = metadata_chunk(b"tEXt", b"k\0"); + let mut hostile = Vec::with_capacity(prefix.len() + count * tiny.len() + large.len() + tail.len()); + hostile.extend(prefix); + for _ in 0..count { + hostile.extend(&tiny); + } + hostile.extend(&large); + hostile.extend(tail); + assert!(hostile.len() < MAX_TEXTURE_BYTES && hostile.capacity() <= MAX_TEXTURE_BYTES); + assert_eq!(std::mem::size_of::(), 48); + // Independent lower bound, deliberately ignoring all small-string, fixed + // decoder and parser storage: raw16MiB + existing text-vector12MiB + + // old12/new24MiB Latin1 expansion already reaches the whole64MiB cap. + // The positive keyword/fixed allocations make that an actual excess. + let lower_bound = 16 * MIB + (count + 1) * 48 + 12 * MIB + 24 * MIB; + assert_eq!(lower_bound as u64, MAX_CODEC_BYTES); + assert!(png_metadata::validate(&hostile).unwrap_err().to_string().contains("codec allowance")); + assert!(TextureSource::new(hostile, MapRole::BaseColor).err().unwrap().to_string().contains("codec allowance")); +} + fn declaration_chunk(kind: &[u8; 4], data: &[u8]) -> Vec { let mut result = (data.len() as u32).to_be_bytes().to_vec(); result.extend(kind); diff --git a/crates/render/src/texture_sampling.rs b/crates/render/src/texture_sampling.rs index eba9657d6..e8fe7bbbd 100644 --- a/crates/render/src/texture_sampling.rs +++ b/crates/render/src/texture_sampling.rs @@ -59,7 +59,9 @@ impl<'a> TextureView<'a> { Ok(Self { rgba, width, height }) } - /// Shape-only borrow of immutable storage validated incrementally by its builder. + /// Shape-only borrow of private immutable storage whose builder already + /// validated every sample incrementally. Never use on unvalidated external + /// pixels: this avoids an image-wide scan on every future mapped ray. #[cfg(feature = "raytrace-cpu")] pub(crate) fn from_admitted(rgba: &'a [f32], dimensions: [u32; 2]) -> Result { let [width, height] = dimensions; @@ -71,6 +73,7 @@ impl<'a> TextureView<'a> { } Ok(Self { rgba, width: width as usize, height: height as usize }) } + /// Bilinear level-zero RGB for an explicitly opaque consumer. Alpha is validated /// but deliberately ignored (even zero-alpha RGB participates). This is NOT /// transparent compositing or premultiplied-alpha filtering. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 39f2799e7..348fced84 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -298,38 +298,47 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result if id == "view.pick" { return crate::view_pick::pick_command(app, ¶ms); } + // Eligibility follows the same case-insensitive IDs as the engine. + let fit_id = solidcraft_engine::find_command(id).map_or(id, |spec| spec.id); + let fit_command = !matches!( + fit_id, + "view.fit" + | "view.home" + | "view.tool" + | "view.tool.zoom" + | "view.spin" + | "view.visual_style" + | "view.grid" + | "view.ground_shadow" + | "view.navigation_bar" + | "view.ribbon_tabs_only" + | "view.next_tab" + | "view.previous_tab" + | "view.layout" + | "view.navigate" + | "view.ambient_occlusion" + | "view.perspective" + | "view.angle_readout" + | "view.graphics_preset" + | "view.history_layout" + | "timeline.play" + | "browser.expand_all" + | "browser.collapse_all" + ) && !fit_id.starts_with("settings."); + // History changes and session swaps can return to the first-body fitting window. + let history_may_fit = app.session.undo.len() <= 2 + || SWITCHES_DESIGN.contains(&fit_id) + || matches!(fit_id, "edit.undo" | "edit.restore_checkpoint" | "doc.open" | "doc.recover" | "sketch.finish"); + // Placement failure does not establish an empty model. Keep its camera and + // let the existing placement diagnostic explain the unavailable world. + let was_empty = fit_command && history_may_fit && app.session.world_state().is_ok_and(|world| world.bodies.is_empty()); let r = app.run(id, params); // Update Links in a part edited in place reads the assembly around it too, as its button does. if r.is_ok() && is_command(Some(id), "component.update_links") && app.edit_in_place.active.is_some() { crate::edit_in_place::refresh(app); } if r.is_ok() - && !matches!( - id, - "view.fit" - | "view.home" - | "view.tool" - | "view.tool.zoom" - | "view.spin" - | "view.visual_style" - | "view.grid" - | "view.ground_shadow" - | "view.navigation_bar" - | "view.ribbon_tabs_only" - | "view.next_tab" - | "view.previous_tab" - | "view.layout" - | "view.navigate" - | "view.ambient_occlusion" - | "view.perspective" - | "view.angle_readout" - | "view.graphics_preset" - | "view.history_layout" - | "timeline.play" - | "browser.expand_all" - | "browser.collapse_all" - ) - && !id.starts_with("settings.") + && was_empty && app.session.active_sketch.is_none() // Cheap test first: placing the world (`world_state`) after every step of a batch in a // design with components placed every component's bodies again once per step. @@ -2491,23 +2500,62 @@ mod tests { #[test] fn a_step_does_not_place_the_world_for_the_first_body_fit() { let mut h = crate::scenario::Harness::new(); - let v = batch( - &mut h, - json!({"commands": [ + // The harness call settles frames, which legitimately place the world for drawing. + let Outcome::Done(v) = super::batch( + &mut h.app, + &json!({"commands": [ {"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "body_name": "Cube"}}, {"command": "component.from_bodies", "params": {"bodies": ["Cube"]}}, {"command": "occurrence.copy", "params": {"component": "Cube", "translate": [0, 40, 0]}}, ]}), - ); + ) else { + panic!("a command batch cannot be a screenshot"); + }; assert!(v["result"].get("failed").is_none(), "{v}"); assert!(h.app.session.undo.len() > 2, "past the first-body fit"); // Straight to `execute`, with no frame: drawing places the world too. + assert!(h.app.session.cached_world_state().is_none()); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let r = super::execute(&mut h.app, "select.clear", json!({})); + assert!(r.is_ok(), "{r:?}"); + assert!(h.app.session.cached_world_state().is_none(), "clearing selection placed the components before the command"); + assert_eq!(h.app.cam, camera); + assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); let r = super::execute(&mut h.app, "solid.sphere", json!({"radius": 3, "center": [80, 0, 0], "operation": "new"})); assert!(r.is_ok(), "{r:?}"); assert!(h.app.session.cached_world_state().is_none(), "the step placed the components again"); assert_eq!(crate::open_meshing::session_world(&h.app.session).bodies.len(), 3); } + #[test] + fn excluded_control_view_commands_leave_a_cold_component_world_unplaced() { + for id in ["view.grid", "VIEW.GRID", "view.tool.zoom", "VIEW.TOOL.ZOOM"] { + let mut saved = Session::default(); + saved.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Cube"})).unwrap(); + saved.execute("component.from_bodies", &json!({"bodies":["Cube"]})).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app.session = Session::opened((*saved.doc).clone(), None); + assert_eq!(h.app.session.undo.len(), 0, "history permits fitting, so only the command exclusion can prevent placement"); + assert!(!h.app.session.doc.occurrences.is_empty()); + assert!(h.app.session.cached_world_state().is_none()); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let r = super::execute(&mut h.app, id, json!({"on":false})); + assert!(r.is_ok(), "{r:?}"); + assert_eq!(r.unwrap()["on"], false, "the engine accepted {id}"); + if id == "view.grid" { + assert!(!h.app.ui.show_grid); + } + assert!(h.app.session.cached_world_state().is_none(), "{id} placed a world it cannot fit"); + assert_eq!(h.app.cam, camera); + assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.session.undo.is_empty() && h.app.session.redo.is_empty()); + } + } + /// #743: a batch is one request through the app's queue, answered within a frame, however /// many steps it has. #[test] @@ -2834,6 +2882,156 @@ mod tests { assert_eq!(a.app.cam, b.app.cam, "the first-body fit must happen as for engine.execute"); } + #[test] + fn existing_single_body_control_queries_keep_the_current_camera_and_history() { + let mut saved = Session::default(); + saved.execute("solid.box", &json!({"length":80,"width":50,"height":12,"body_name":"Subject"})).unwrap(); + let mut h = crate::scenario::Harness::new(); + crate::documents::open_tab(&mut h.app, Session::opened((*saved.doc).clone(), None)).unwrap(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + h.frames(4); + crate::render_workspace::enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.cancel_view_animation(); + h.app.cam.distance = 321.0; + h.app.cam.yaw = 0.3; + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); + assert_eq!(h.app.session.undo.len(), 0, "a freshly opened one-body design exercises the old refit heuristic"); + for command in ["appearance.library", "render.settings.get", "render.scene"] { + let reply = h.call("engine.execute", json!({"command":command,"params":{}})); + assert_eq!(reply["ok"], true, "{command}: {reply}"); + h.frames(4); + assert_eq!(h.app.cam, camera, "read-only {command} must keep the product framing"); + assert!(h.app.pending_fit.is_none()); + assert!(std::sync::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); + } + let reply = h.call( + "engine.batch", + json!({"commands":[ + {"command":"appearance.library","params":{}}, {"command":"render.scene","params":{}} + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + h.frames(4); + assert_eq!(h.app.cam, camera); + assert!(std::sync::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); + } + + #[test] + fn control_undo_from_three_steps_to_two_still_fits_the_first_body() { + for id in ["edit.undo", "EDIT.UNDO"] { + let mut h = crate::scenario::Harness::new(); + h.frames(4); + h.app.run("solid.box", json!({"length":80,"width":50,"height":12,"body_name":"Subject"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#204080"})).unwrap(); + let feature = h.app.session.doc.features[0].id; + h.app.run("timeline.delete", json!({"feature":feature})).unwrap(); + assert_eq!(h.app.session.undo.len(), 3); + assert!(h.app.session.world_state().unwrap().bodies.is_empty()); + h.app.cancel_view_animation(); + h.app.cam.distance = 10_000.0; + assert!(h.app.pending_fit.is_none()); + let r = super::execute(&mut h.app, id, json!({})); + assert!(r.is_ok(), "{r:?}"); + assert_eq!(h.app.session.undo.len(), 2); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); + assert!(h.app.pending_fit.is_some(), "Undo crossing the early-history boundary must retain the measured first-body fit"); + h.frames(4); + assert!(h.app.pending_fit.is_none()); + assert!(h.app.cam.distance < 1000.0); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn control_finish_edit_from_a_long_empty_part_still_fits_the_returned_assembly() { + for id in ["component.finish_edit", "COMPONENT.FINISH_EDIT"] { + let mut h = crate::scenario::Harness::new(); + h.frames(4); + let part_path = h.dir.join("part.sc"); + let assembly_path = h.dir.join("assembly.sc"); + let mut part = Session::default(); + part.execute("solid.box", &json!({"length":80,"width":50,"height":12,"body_name":"Subject"})).unwrap(); + part.execute("file.save", &json!({"path":part_path})).unwrap(); + let component = h.app.run("component.insert_design", json!({"path":part_path})).unwrap()["component"].as_u64().unwrap(); + h.app.run("file.save", json!({"path":assembly_path})).unwrap(); + h.settle(); + h.app.cancel_view_animation(); + h.app.cam.distance = 10_000.0; + let assembly_camera = h.app.cam; + let assembly = h.app.session.doc.clone(); + let assembly_history = (h.app.session.undo.len(), h.app.session.redo.len()); + assert_eq!(assembly_history, (1, 0)); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); + + h.app.run("component.edit_in_place", json!({"component":component})).unwrap(); + h.settle(); + assert!(h.app.edit_in_place.active.is_some()); + assert_eq!(h.app.session.path.as_deref(), part_path.to_str()); + assert!(h.app.session.undo.is_empty()); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#204080"})).unwrap(); + h.app.run("parameters.add", json!({"name":"clearance","expression":"1 mm"})).unwrap(); + let feature = h.app.session.doc.features[0].id; + h.app.run("timeline.delete", json!({"feature":feature})).unwrap(); + h.app.run("file.save", json!({})).unwrap(); + assert_eq!(h.app.session.undo.len(), 3); + assert!(!h.app.session.is_dirty()); + assert!(h.app.session.world_state().unwrap().bodies.is_empty()); + assert!(h.app.pending_fit.is_none()); + + // Finish switches synchronously to the assembly's own saved history and + // last loaded one-body model, before any background link refresh lands. + let r = super::execute(&mut h.app, id, json!({})); + assert!(r.is_ok(), "{id}: {r:?}"); + assert!(h.app.edit_in_place.active.is_none()); + assert_eq!(h.app.session.path.as_deref(), assembly_path.to_str()); + assert!(std::sync::Arc::ptr_eq(&assembly, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), assembly_history); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.fov, h.app.cam.up), + (assembly_camera.yaw, assembly_camera.pitch, assembly_camera.roll, assembly_camera.fov, assembly_camera.up), + "returning to the tab restores its orientation and projection while fitting its body" + ); + assert!(h.app.pending_fit.is_some(), "{id}: a session swap must retain the measured first-body fit"); + h.settle(); + assert!(h.app.pending_fit.is_none()); + assert!(h.app.cam.distance < 1000.0); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), assembly_history); + } + } + + #[test] + fn control_first_body_creation_still_fits_but_later_appearance_edits_do_not() { + let mut h = crate::scenario::Harness::new(); + h.frames(4); + h.app.cancel_view_animation(); + h.app.cam.distance = 10_000.0; + let (request, _receiver) = + ControlRequest::new("engine.execute", json!({"command":"solid.box","params":{"length":80,"width":50,"height":12,"body_name":"Subject"}})); + let Outcome::Done(reply) = handle(&mut h.app, &h.ctx, &request) else { panic!("a command reply cannot be a screenshot") }; + assert_eq!(reply["ok"], true, "{reply}"); + assert!(h.app.pending_fit.is_some(), "the first actual body must request the measured fit"); + h.frames(4); + assert!(h.app.pending_fit.is_none()); + assert!(h.app.cam.distance < 1000.0); + h.app.cam.yaw = 0.7; + h.app.cam.distance = 321.0; + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + let reply = h.call("engine.execute", json!({"command":"appearance.assign","params":{"bodies":["Subject"],"color":"#204080"}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.frames(4); + assert_eq!(h.app.cam, camera); + assert!(h.app.pending_fit.is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + /// A request carrying `allow_paths` (from an MCP server, #205) reaches files only inside /// those folders; the same request without it, like the user's own dialogs, is unconfined. #[test] diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index f2b482d42..62a1d3b5f 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -193,6 +193,24 @@ impl Documents { } } +/// Route native render completion by the document-lifetime owner, never by the +/// selected tab or a mutable path/name. The engine capsule verifies its registry. +pub(crate) fn render_owner(app: &SolveApp, uid: u64) -> Option<&Session> { + if app.session.uid == uid { Some(&app.session) } else { app.docs.background().find(|s| s.uid == uid) } +} +pub(crate) fn with_render_owner( + app: &mut SolveApp, + uid: u64, + apply: impl FnOnce(&mut Session, &mut crate::render_workspace::ViewState) -> T, +) -> Option { + if app.session.uid == uid { + Some(apply(&mut app.session, &mut app.render_workspace.view)) + } else { + let slot = app.docs.background_mut().find(|slot| slot.session.uid == uid)?; + Some(apply(&mut slot.session, &mut slot.view.render)) + } +} + /// The host renamed a design file: every open tab of that path follows it, including the /// borrowed design name the tab title shows (#11375). pub fn follow_file_rename(app: &mut SolveApp, old_path: &str, new_path: &str) { @@ -328,7 +346,9 @@ pub fn switch(app: &mut SolveApp, i: usize) { if i == app.docs.active || i >= app.docs.slots.len() { return; } - let Some(incoming) = app.docs.slots.get_mut(i).and_then(Option::take) else { return }; + let Some(incoming) = app.docs.slots.get_mut(i).and_then(Option::take) else { + return; + }; crate::linked_source::note_unread(app); let out = swap_in(app, incoming); let a = app.docs.active; @@ -384,7 +404,9 @@ pub(crate) fn record_stamps_at(app: &mut SolveApp, path: &str, stamps: &[(u64, c &mut app.docs.link_stamps } else { let saved_at = |s: &DocSlot| s.session.path.as_deref().is_some_and(|p| same_path(p, path)); - let Some(slot) = app.docs.slots.iter_mut().flatten().find(|s| saved_at(s)) else { return }; + let Some(slot) = app.docs.slots.iter_mut().flatten().find(|s| saved_at(s)) else { + return; + }; &mut slot.link_stamps }; for (c, s) in stamps { @@ -609,6 +631,10 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) { return; } app.docs.closing = None; + let closing_uid = if i == app.docs.active { Some(app.session.uid) } else { app.docs.slots[i].as_ref().map(|slot| slot.session.uid) }; + if let Some(uid) = closing_uid { + crate::render_workspace::prepare::document_closing(app, uid); + } if n <= 1 { crate::browser::discard_reveals(app); crate::semantic_content::leave_document(app); @@ -733,7 +759,9 @@ pub fn request_quit(app: &mut SolveApp) { /// Ask about the next design with unsaved changes, or quit when none is left. fn quit_step(app: &mut SolveApp) { - let Some(skip) = app.docs.quitting.clone() else { return }; + let Some(skip) = app.docs.quitting.clone() else { + return; + }; if app.docs.closing.is_some() { return; } @@ -986,7 +1014,9 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { order.extend(held.map(|(from, _)| from)); let mut dropped: Option<(usize, usize)> = None; for i in order { - let Some((name, dirty)) = info.get(i) else { continue }; + let Some((name, dirty)) = info.get(i) else { + continue; + }; let w = width(i); let left = match held { Some((from, left)) if from == i => left, diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 1b09f2f75..180c62d69 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -15,6 +15,8 @@ pub use solidcraft_gpu::view::{ /// A frame of the viewport as an egui paint callback. pub struct ViewportCallback(pub Frame); +/// A transparent, depth-correct selection/hover layer over live product pixels. +pub(crate) struct ProductHighlightCallback(pub Frame); /// The viewport callback composites transparently onto this egui GPU mesh. Both its clear /// surface and gradient therefore use the same published/animated tokens as the panels; no @@ -224,6 +226,166 @@ fn cpu_picture( #[cfg(test)] mod test_support { + /// Paint real egui textures and callbacks into a readable window target. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) struct EguiFixture { + device: super::wgpu::Device, + queue: super::wgpu::Queue, + renderer: std::sync::Arc>, + output: super::wgpu::Texture, + size: [u32; 2], + pub(crate) product_highlight_callbacks: usize, + pub(crate) viewport_callbacks: usize, + } + + #[cfg(not(target_arch = "wasm32"))] + impl EguiFixture { + pub(crate) fn new(app: &mut crate::SolveApp, size: [u32; 2]) -> Option { + use super::*; + let Some((_, device, queue)) = offscreen_device() else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "GPU adapter required for egui fixture"); + eprintln!("skipped egui fixture: no admitted adapter/device"); + return None; + }; + let format = wgpu::TextureFormat::Rgba8UnormSrgb; + let renderer = Arc::new(egui::epaint::mutex::RwLock::new(egui_wgpu::Renderer::new(&device, format, Default::default()))); + let window = GpuTarget { format, depth: None, samples: 1, tess: false, oit: false }; + let scene = GpuTarget { depth: Some(solidcraft_gpu::depth_format(&device, true)), ..window }; + let view = Renderer::with_window_target(&device, scene, window, None); + let installed = view.target(); + app.viewport.gpu = Some(installed); + app.viewport.draw_stats = Some(view.stats()); + renderer.write().callback_resources.insert(view); + app.render_workspace.host = Some( + crate::render_workspace::host_executor(device.limits().max_texture_dimension_2d, installed.depth.is_some(), installed.samples.max(1)) + .unwrap(), + ); + crate::render_workspace::sync_backend(app); + let output = device.create_texture(&wgpu::TextureDescriptor { + label: Some("full egui fixture"), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + Some(Self { device, queue, renderer, output, size, product_highlight_callbacks: 0, viewport_callbacks: 0 }) + } + + pub(crate) fn frame(&mut self, ctx: &egui::Context, events: Vec, add: impl FnMut(&mut egui::Ui)) -> Vec { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.size[0] as f32, self.size[1] as f32))), + time: Some(1.0), + focused: true, + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, add); + self.product_highlight_callbacks = 0; + self.viewport_callbacks = 0; + for clipped in &out.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Callback(callback) = shape + && let Some(callback) = callback.callback.downcast_ref::() + { + self.product_highlight_callbacks += usize::from(callback.downcast_ref::().is_some()); + self.viewport_callbacks += usize::from(callback.downcast_ref::().is_some()); + } + }); + } + paint_egui_output(ctx, &mut out, &self.renderer, &self.device, &self.queue, &self.output); + read_egui_pixels(&self.device, &self.queue, &self.output) + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn paint_egui_output( + ctx: &egui::Context, + out: &mut egui::FullOutput, + renderer: &std::sync::Arc>, + device: &super::wgpu::Device, + queue: &super::wgpu::Queue, + output: &super::wgpu::Texture, + ) -> usize { + use super::*; + let jobs = ctx.tessellate(std::mem::take(&mut out.shapes), out.pixels_per_point); + let screen = egui_wgpu::ScreenDescriptor { size_in_pixels: [output.width(), output.height()], pixels_per_point: out.pixels_per_point }; + let mut encoder = device.create_command_encoder(&Default::default()); + let mut renderer = renderer.write(); + for (id, deltas) in out.textures_delta.set.drain() { + for delta in deltas { + renderer.update_texture(device, queue, id, &delta); + } + } + if let Some(effect) = &renderer.frame_compositor { + effect.begin_viewport(egui::ViewportId::ROOT.0.value()); + } + let extra = renderer.update_buffers(device, queue, &mut encoder, &jobs, &screen); + let target = output.create_view(&Default::default()); + let composed = renderer + .frame_compositor + .as_ref() + .is_some_and(|effect| effect.render(&renderer, &mut encoder, &target, &jobs, &screen, [0.0, 0.0, 0.0, 1.0])); + if !composed { + let mut pass = encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("fixture ordinary UI"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime(); + renderer.render(&mut pass, &jobs, &screen); + } + queue.submit(extra.into_iter().chain([encoder.finish()])); + if let Some(effect) = &renderer.frame_compositor { + effect.submitted(); + } + for id in out.textures_delta.free.drain() { + renderer.free_texture(&id); + } + drop(renderer); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + jobs.len() + } + + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn read_egui_pixels(device: &super::wgpu::Device, queue: &super::wgpu::Queue, texture: &super::wgpu::Texture) -> Vec { + use super::*; + let size = texture.size(); + let stride = (size.width * 4).div_ceil(256) * 256; + let read = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("full egui readback"), + size: u64::from(stride) * u64::from(size.height), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &read, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride), rows_per_image: Some(size.height) }, + }, + size, + ); + queue.submit([encoder.finish()]); + let slice = read.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let bytes = slice.get_mapped_range().unwrap(); + bytes.chunks_exact(stride as usize).flat_map(|row| row[..size.width as usize * 4].iter().copied()).collect() + } + /// For tests that look at pictures: install the headless GPU renderer (the CLI's). `false`, with /// the reason printed, on a machine without a GPU adapter, and the test skips. #[cfg(not(target_arch = "wasm32"))] @@ -246,7 +408,7 @@ mod test_support { } } #[cfg(all(test, not(target_arch = "wasm32")))] -pub(crate) use test_support::test_picture_renderer; +pub(crate) use test_support::{EguiFixture, test_picture_renderer}; impl egui_wgpu::CallbackTrait for ViewportCallback { fn prepare( @@ -270,6 +432,31 @@ impl egui_wgpu::CallbackTrait for ViewportCallback { } } +impl egui_wgpu::CallbackTrait for ProductHighlightCallback { + fn prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + _screen: &egui_wgpu::ScreenDescriptor, + encoder: &mut wgpu::CommandEncoder, + resources: &mut egui_wgpu::CallbackResources, + ) -> Vec { + if let Some(renderer) = resources.get_mut::() { + renderer.prepare_product_highlights(device, queue, encoder, &self.0); + } + Vec::new() + } + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &egui_wgpu::CallbackResources) { + let Some(renderer) = resources.get::() else { return }; + let viewport = info.viewport_in_pixels(); + renderer.paint_product_highlights( + &self.0, + pass, + [viewport.left_px as f32, viewport.top_px as f32, viewport.width_px as f32, viewport.height_px as f32], + ); + } +} + /// The shader's analysis colours and flags for the theme's colours. pub fn analysis_colors(c: &crate::theme::AnalysisColors) -> [f32; 36] { solidcraft_gpu::view::analysis_colors(c) @@ -971,7 +1158,6 @@ mod tests { } fn frame(&mut self) -> f64 { - use super::*; let started = std::time::Instant::now(); // Keep local layout/input stationary, then transform only after emission. if let Some(layer) = self.root_layer { @@ -993,81 +1179,13 @@ mod tests { ui.ctx().set_transform_layer(ui.layer_id(), transform); }); self.root_layer = root_layer; - let jobs = self.ctx.tessellate(out.shapes, out.pixels_per_point); - self.jobs = jobs.len(); - let screen = egui_wgpu::ScreenDescriptor { size_in_pixels: self.size, pixels_per_point: out.pixels_per_point }; - let mut encoder = self.device.create_command_encoder(&Default::default()); - let mut renderer = self.renderer.write(); - for (id, deltas) in out.textures_delta.set.drain() { - for delta in deltas { - renderer.update_texture(&self.device, &self.queue, id, &delta); - } - } - if let Some(effect) = &renderer.frame_compositor { - effect.begin_viewport(egui::ViewportId::ROOT.0.value()); - } - let extra = renderer.update_buffers(&self.device, &self.queue, &mut encoder, &jobs, &screen); - let target = self.output.create_view(&Default::default()); - let composed = renderer - .frame_compositor - .as_ref() - .is_some_and(|effect| effect.render(&renderer, &mut encoder, &target, &jobs, &screen, [0.0, 0.0, 0.0, 1.0])); - if !composed { - let mut pass = encoder - .begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("fixture ordinary UI"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &target, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }) - .forget_lifetime(); - renderer.render(&mut pass, &jobs, &screen); - } - self.queue.submit(extra.into_iter().chain([encoder.finish()])); - if let Some(effect) = &renderer.frame_compositor { - effect.submitted(); - } - for id in out.textures_delta.free.drain() { - renderer.free_texture(&id); - } - drop(renderer); - self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + self.jobs = super::test_support::paint_egui_output(&self.ctx, &mut out, &self.renderer, &self.device, &self.queue, &self.output); started.elapsed().as_secs_f64() * 1000.0 } fn pixels(&self, source: bool) -> Vec { - use super::*; let texture = if source { self.app.blur.source_texture().unwrap() } else { self.output.clone() }; - let size = texture.size(); - let stride = (size.width * 4).div_ceil(256) * 256; - let read = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("full egui readback"), - size: u64::from(stride) * u64::from(size.height), - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - let mut encoder = self.device.create_command_encoder(&Default::default()); - encoder.copy_texture_to_buffer( - texture.as_image_copy(), - wgpu::TexelCopyBufferInfo { - buffer: &read, - layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride), rows_per_image: Some(size.height) }, - }, - size, - ); - self.queue.submit([encoder.finish()]); - let slice = read.slice(..); - slice.map_async(wgpu::MapMode::Read, |_| {}); - self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); - let bytes = slice.get_mapped_range().unwrap(); - bytes.chunks_exact(stride as usize).flat_map(|row| row[..size.width as usize * 4].iter().copied()).collect() + super::test_support::read_egui_pixels(&self.device, &self.queue, &texture) } fn evidence(&self, name: &str) { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8dcef729c..3bc2a5473 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -702,12 +702,10 @@ mod tests { ENGLISH.messages().values().map(String::as_str).collect() } - /// Catalogs delivered complete. English is the source catalog; Arabic, Czech, Italian, Japanese and Chinese - /// are complete. German, Korean, Malay, Russian, French and Ukrainian - /// are partial (German and Korean predate the coverage guards; Russian, French and Ukrainian - /// are kept partial so a new label doesn't need more translations), so their gaps fall back - /// to English and are reported by `cargo xtask i18n` without failing the build, while - /// nothing in the complete catalogs may regress. + /// English is the source catalog. Arabic, Hebrew, Japanese, Vietnamese and Chinese + /// are complete; every English key must be present. Other catalogs are partial: + /// gaps fall back to English and `cargo xtask i18n` reports them without failing. + /// New labels still require German and Korean under the contributor policy. const COMPLETE: &[&str] = &["ar", "he", "ja", "vi", "zh"]; /// `text()` falls back to English silently, so a message a complete locale never received is diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b779acf09..4f79de89c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -642,6 +642,8 @@ pub struct SolveApp { /// How long OK waits for a feature before computing it off the window thread, saying so; /// `None`: it waits as long as it takes (headless use, tests). The desktop app sets it. pub apply_off_thread: Option, + /// One bounded native render proof/retirement owner, independent of tab state. + pub(crate) render_preparation: render_workspace::prepare::State, /// Tests: work started off the window thread (a feature's evaluation, a Properties /// measurement) waits for this before it reports done. #[cfg(test)] @@ -888,6 +890,7 @@ impl SolveApp { timeline_playback: None, delete_check: None, apply_off_thread: None, + render_preparation: Default::default(), #[cfg(test)] apply_gate: None, last_command: None, @@ -1250,6 +1253,34 @@ impl SolveApp { Ok(reply) }); self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS; + self.after_command(id, ¶ms, revision, selected_before, r) + } + + /// Commit already prepared rendering through the same window post-hooks, + /// without executing capture or admission again on the window. + pub(crate) fn finish_render_preparation( + &mut self, + id: &str, + params: &Value, + finish: impl FnOnce(&mut Session) -> Result, + ) -> Result { + let revision = self.session.revision; + let selected_before = self.session.selection.clone(); + let result = finish(&mut self.session).and_then(|reply| { + render_workspace::apply_command(self, id, &reply)?; + Ok(reply) + }); + self.after_command(id, params, revision, selected_before, result) + } + + fn after_command( + &mut self, + id: &str, + params: &Value, + revision: u64, + selected_before: Vec, + r: Result, + ) -> Result { // An Undo offered by the last toast is stale once another command changed the design. if self.status_undo && revision != self.session.revision { self.status_undo = false; @@ -1278,7 +1309,7 @@ impl SolveApp { render_workspace::light::apply_visibility(self, id, v); } if matches!(id, "render.lights.set" | "render.lights.add" | "render.lights.duplicate" | "render.lights.remove") { - render_workspace::light::edited(self, ¶ms, v); + render_workspace::light::edited(self, id, params, v); } } done @@ -1347,6 +1378,11 @@ impl SolveApp { if id == "view.render_inspector" { render_workspace::set_inspector_visible(self, v.get("visible").and_then(Value::as_bool).unwrap_or(true)); } + if id == "view.render_live" + && let Some(paused) = v.get("paused").and_then(Value::as_bool) + { + render_workspace::live::set_paused(self, paused); + } if id == "view.render_browser" { render_workspace::apply_browser_controls(self, v); } @@ -2825,6 +2861,11 @@ impl SolveApp { fn resolve_fit(&mut self, ctx: &egui::Context) { viewport::refresh_layout(self, ctx); + if self.fit_waits < Self::FIT_WAITS && render_workspace::wait_entry_fit_layout(self) { + self.fit_waits += 1; + ctx.request_repaint(); + return; + } if self.viewport.layout.is_some() && let Some((cam, bounds, animate, shared)) = self.pending_fit.take() { @@ -2848,7 +2889,9 @@ impl SolveApp { self.pending_fit = Some((cam, bounds, animate, shared)); } else { self.fit_waits = 0; + let previous = self.cam; self.cam = self.fitted_bounds(cam, &want); + render_workspace::settle_entry_fit(self, cam, bounds, previous); } ctx.request_repaint(); return; @@ -2857,8 +2900,10 @@ impl SolveApp { if animate { self.animate_to(to); } else { + let previous = self.cam; self.cam = to; self.cam_anim = None; + render_workspace::settle_entry_fit(self, cam, bounds, previous); // An open's framing settles here, once the layout is known. An open still meshing // takes this as the camera it framed from the outlines, so the framing it does // when the last body is ready isn't mistaken for the user having moved the view. @@ -3014,6 +3059,7 @@ impl SolveApp { /// Stop any view animation where it is (the user took over the camera). pub fn cancel_view_animation(&mut self) { + render_workspace::cancel_entry_fit(self); self.pending_fit = None; self.cam_anim = None; } @@ -3219,6 +3265,7 @@ impl SolveApp { /// Lay out the whole window. pub fn ui(&mut self, ui: &mut egui::Ui) { prefs::prepare_blur(self, ui.ctx()); + render_workspace::displayed::begin(self); let blur_source = !self.home.open && !render_workspace::result_active(self); let _blur_scope = self.blur.begin(ui.ctx(), blur_source); value_step::set_enabled(ui.ctx(), self.preferences.step_values); @@ -3266,6 +3313,7 @@ impl SolveApp { control::publish_design(self, &control::DESIGN_WATCH); self.frame_ms = now_ms() - t0; frame_watch::end(self); + render_workspace::displayed::finish(self, ui.ctx()); } fn cad_ui(&mut self, ui: &mut egui::Ui, report_input: &mut Option) { @@ -3566,6 +3614,10 @@ impl SolveApp { if req.refuse_cancelled_chat() { return; } + let Some(req) = render_workspace::prepare::control(self, req) else { + ctx.request_repaint(); + return; + }; let reply = req.reply.clone(); match control::handle(self, ctx, &req) { control::Outcome::Done(v) => { diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 797bbba02..a849a2266 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -496,6 +496,7 @@ pub(crate) fn view_key(app: &mut SolveApp, ctx: &egui::Context, key: egui::Key, if ctrl { // The model moves with the arrow, as it does under a pan drag. if let Some(rect) = app.viewport.rect { + let rect = crate::render_workspace::camera_rect(app, rect); let step = rect.height() * 0.1; let params = json!({"motion": "pan", "delta": [dx * step, dy * step]}); if result { @@ -551,6 +552,7 @@ pub(crate) fn step_key_hold(app: &mut SolveApp, ctx: &egui::Context) { /// Continuous camera changes use the same JSON command as programmatic callers. pub(crate) fn camera_motion(app: &mut SolveApp, rect: Rect, mut params: serde_json::Value) { + let rect = crate::render_workspace::camera_rect(app, rect); let stored_fov = app.cam.fov; params["camera"] = json!(projection(app, rect).cam); params["viewport"] = json!([rect.width().max(1.0), rect.height().max(1.0)]); @@ -587,6 +589,10 @@ pub(crate) struct CameraInput { /// selectable, so a press that would start a selection navigates as on empty space; with /// `caps.orbit` off, bindings that orbit do nothing and pan and zoom work as usual. pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &egui::Response, caps: NavCaps) -> CameraInput { + // A framed Render image and its gray letterbox share input ownership, but + // camera deltas and anchors use the exact image projection's pixel scale. + let input_rect = rect; + let rect = crate::render_workspace::camera_rect(app, rect); let picking = caps.pick; let (hover, scroll, mods, middle, secondary_down, primary_down, primary_pressed, primary_released, delta) = ui.input(|i| { ( @@ -605,16 +611,16 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e // The right button belongs to the marking menu while it is open. let secondary_down = secondary_down && app.viewport.context_menu.is_none(); // The axis view handles its own clicks; the model underneath must not see them. - let axes = if caps.orbit { axis_rect(app, rect) } else { Rect::NOTHING }; + let axes = if caps.orbit { axis_rect(app, input_rect) } else { Rect::NOTHING }; // So is the View angles readout under it (#6032). - let readout = crate::view_angles::readout_rect(ui.ctx(), rect).filter(|_| caps.orbit && app.preferences.show_view_angles); + let readout = crate::view_angles::readout_rect(ui.ctx(), input_rect).filter(|_| caps.orbit && app.preferences.show_view_angles); // Floating windows and menus own input over the model, including wheel navigation. egui's // hit test also counts the model as under the pointer a few points past its own edge and // inside a window's or a list's edge (#678), so the pointer must be in the viewport too, // with no window or menu above it. let inside = ui.is_enabled() && resp.contains_pointer() - && ui.rect_contains_pointer(rect) + && ui.rect_contains_pointer(input_rect) && hover.is_some_and(|p| !axes.contains(p) && !readout.is_some_and(|r| r.contains(p))); // The wheel and trackpad gestures go on under a box anchored to the model (a value box such // as Extrude's distance, a dimension's editor): it scrolls nothing, and a pan, orbit or zoom @@ -625,7 +631,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e && !crate::value_step::enabled(ui.ctx()) && !hover.is_some_and(|p| crate::dim_view::window::covers(ui.ctx(), p)) && hover.is_some_and(|p| { - rect.contains(p) + input_rect.contains(p) && !axes.contains(p) && !readout.is_some_and(|r| r.contains(p)) && ui.ctx().layer_id_at(p).is_some_and(crate::ui_kit::container::is_canvas) @@ -742,7 +748,9 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e let empty_space = |app: &SolveApp| { app.viewport.context_menu.is_none() && hover.is_some_and(|p| { - if !picking { + // The free canvas owns navigation, including gray letterbox. Its + // invisible continuation of the camera ray contains no pickable scene. + if !picking || !rect.contains(p) { return true; } let proj = projection(app, rect); @@ -953,6 +961,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e /// for its page; the 3D mouse only reads the device and queues the motion /// ([`crate::space_mouse::navigate_frame`]). pub(crate) fn device(app: &mut SolveApp, rect: Rect, caps: NavCaps) { + let rect = crate::render_workspace::camera_rect(app, rect); if app.viewport.device_motion.is_none() && app.viewport.bridge_motion.is_none() { return; } diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 6a76269e7..ca3f9556c 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1181,6 +1181,12 @@ preference_settings! { cut_preview_tint: bool = true, PAGE_GRAPHICS => check_id("prefs.cut_preview_tint"); /// Restore the previous platform-specific fixed Render preview geometry budget. render_previous_geometry_budget: bool = false, PAGE_GRAPHICS => check_id("prefs.render_previous_geometry_budget"); + /// Restore Raster for new Render setups, fixed CPU sampling and its mode selector. + /// Refit on entry and keep shot activation camera-neutral, with the previous preview + /// framing, navigation, picking and selection overlays. Disable automatic live feedback + /// and automatic result opening; retain the previous result/cancel viewing behavior. + /// GPU sample edits round to powers of two. + render_legacy_image_defaults: bool = false, PAGE_GRAPHICS => check_id("prefs.render_legacy_image_defaults"); /// How finely the viewport tessellates curved faces and edges: `coarse`, `normal`, `fine` or /// `ultra` (#1287). Only the display plan the viewport draws; never the design or exports. display_quality: String = "normal".into(), PAGE_GRAPHICS; @@ -8511,6 +8517,20 @@ mod tests { } } + #[test] + fn render_legacy_image_defaults_round_trips_and_resets() { + use serde_json::json; + let mut app = crate::SolveApp::new(Default::default(), Default::default()); + assert!(!app.preferences.render_legacy_image_defaults); + let out = super::set(&mut app, &json!({"render_legacy_image_defaults":true})).unwrap(); + assert_eq!(out["render_legacy_image_defaults"], true); + let mut restored = crate::SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&app.prefs()); + assert!(restored.preferences.render_legacy_image_defaults); + super::defaults(&mut restored, super::PAGE_GRAPHICS); + assert!(!restored.preferences.render_legacy_image_defaults); + } + #[test] fn render_previous_geometry_budget_round_trips_and_resets() { use serde_json::json; diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs index 7c5b4bf84..c4a2d24f3 100644 --- a/crates/ui-egui/src/prefs/graphics.rs +++ b/crates/ui-egui/src/prefs/graphics.rs @@ -369,6 +369,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { #[cfg(target_os = "linux")] window_system_row(app, ui, help_label_width); setting::render_previous_geometry_budget(app, ui).backing_on_hover_text(app.tr("prefs.render_previous_geometry_budget_help")); + setting::render_legacy_image_defaults(app, ui).backing_on_hover_text(app.tr("prefs.render_legacy_image_defaults_help")); }); }); }); diff --git a/crates/ui-egui/src/render_ui/mod.rs b/crates/ui-egui/src/render_ui/mod.rs index d9e11ee0b..3a1ec0e42 100644 --- a/crates/ui-egui/src/render_ui/mod.rs +++ b/crates/ui-egui/src/render_ui/mod.rs @@ -77,7 +77,22 @@ pub(crate) fn stage_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { crate::scenario::publish_rect("render:stage_header", Rect::from_min_max(rect.min, egui::pos2(rect.right(), split))); crate::scenario::publish_rect("render:stage_divider", Rect::from_min_size(egui::pos2(rect.left(), split), vec2(rect.width(), 1.0))); crate::scenario::publish_rect("render:stage_tools", Rect::from_min_max(egui::pos2(rect.left(), split), rect.max)); - ui_kit::StageBar::row(ui, rect, true, |ui| stage_tools(app, ui)); + ui_kit::StageBar::row(ui, rect, true, |ui| { + // Keep the renderer settings reachable before the horizontally scrolling + // Look tools and source text, including on a narrow window. + if app.render_workspace.view.stage == Stage::Look + && !crate::render_workspace::result_active(app) + && !crate::render_workspace::comparison_active(app) + { + let settings = ui_kit::StageBar::icon_action(ui, "settings", app.tr("render.live.source_settings_help")); + crate::scenario::publish_target("render:preview:settings", settings.rect); + if settings.clicked() { + let _ = app.run("view.render_select", serde_json::json!({"kind":"output"})); + } + } + crate::render_workspace::live::controls(app, ui); + stage_tools(app, ui); + }); } fn stage_tools(app: &mut SolveApp, ui: &mut egui::Ui) { @@ -127,27 +142,24 @@ fn stage_tools(app: &mut SolveApp, ui: &mut egui::Ui) { } } crate::render_workspace::assign::banner(app, ui); - ui_kit::StageBar::separator(ui); - let note = ui_kit::StageBar::note(ui, app.tr("render.stage_preview_note")).backing_on_hover_text(app.tr("render.preview_lighting_help")); - crate::scenario::publish_rect("render:preview_note", note.rect); - if ui_kit::StageBar::icon_action(ui, "settings", app.tr("render.preview_image_settings_help")).clicked() { + if !crate::render_workspace::result_active(app) && !crate::render_workspace::comparison_active(app) { + ui_kit::StageBar::separator(ui); + let (label, help) = crate::render_workspace::live::source_note(app); + let t = Tokens::get(); + let available = (ui.available_width() - (t.control_height - t.space_2) - ui.spacing().item_spacing.x).max(0.0); + let note = ui_kit::StageBar::note_bounded(ui, &label, available).backing_on_hover_text(format!("{label}\n\n{}", app.tr(help))); + crate::scenario::publish_rect("render:preview_note", note.rect); + } + if ui_kit::StageBar::icon_action(ui, "camera", app.tr("render.preview_image_settings_help")).clicked() { app.start("render.settings.get"); } } Stage::Light => { - ui_kit::text(ui, app.tr("render.lights_fixed_to"), ui_kit::Text::Inline); - ui.add_enabled_ui(false, |ui| { - let mut selected = usize::MAX; - ui_kit::segmented( - ui, - &mut selected, - &[app.tr("render.fixed_camera"), app.tr("render.fixed_world")], - ui_kit::Segments { intrinsic: true, ..Default::default() }, - ); - }) - .response - .backing_on_disabled_hover_text(app.tr("render.light_anchor_pending")); - ui_kit::text(ui, app.tr("render.light_anchor_pending"), ui_kit::Text::Inline); + // Light geometry is authored in world coordinates, including the implicit studio. + // This describes the existing rig; it is not an editable coordinate-frame setting. + let note = ui_kit::StageBar::note_bounded(ui, app.tr("render.light_space_world"), ui.available_width()) + .backing_on_hover_text(app.tr("render.light_space_world_help")); + crate::scenario::publish_rect("render:light_space_note", note.rect); } Stage::Frame => { let mut projection = usize::from(app.cam.fov == 0.0); diff --git a/crates/ui-egui/src/render_ui/scene.rs b/crates/ui-egui/src/render_ui/scene.rs index 3af41122f..413e23d7c 100644 --- a/crates/ui-egui/src/render_ui/scene.rs +++ b/crates/ui-egui/src/render_ui/scene.rs @@ -70,7 +70,7 @@ fn section(app: &mut SolveApp, ui: &mut egui::Ui, key: &str) -> bool { let open = browser::is_open(app, &id, true); let label = app.tr(&format!("render.tree_{key}")).to_string(); let add_label = app.tr(if key == "lights" { "render.tree_add_light" } else { "render.tree_add_shot" }).to_string(); - let pending = app.tr("render.light_backend_limit").to_string(); + let pending = app.tr("render.method_limit_raster").to_string(); let actions = [ui_kit::TreeAction { icon: "plus", hover_only: false, @@ -143,6 +143,11 @@ pub(crate) fn light_types(app: &SolveApp) -> Vec<&'static str> { } pub(crate) fn environment(app: &SolveApp) -> (String, String) { let view = &app.render_workspace.view; + if view.method == ImageMethod::GpuRaytrace && view.studio.environment == studio::Environment::None && view.studio.lighting_enabled { + // An explicit constant, including black, is not the implicit studio. + // It owns RGB radiance, not the legacy draft rotation/intensity pair. + return (app.tr("render.tree_constant").to_string(), String::new()); + } let fixed = || (app.tr("render.tree_fixed_studio").to_string(), view.draft.environment_rotation, view.draft.environment_intensity); let source = |input: &hdr::Input| match input { hdr::Input::EmbeddedResource { resource } => format!("{} {resource}", app.tr("render.tree_hdr")), @@ -154,6 +159,7 @@ pub(crate) fn environment(app: &SolveApp) -> (String, String) { let (name, rotation, intensity) = match view.method { ImageMethod::CpuRaytrace => match view.cpu.environment { cpu::Environment::Hdr => (source(&view.cpu.hdr), view.cpu.rotation_rad, view.cpu.intensity), + cpu::Environment::Sky => (app.tr("render.studio_sky").into(), view.cpu.rotation_rad, view.cpu.intensity), cpu::Environment::Constant => (app.tr("render.tree_constant").into(), 0.0, view.cpu.intensity), cpu::Environment::None => fixed(), }, diff --git a/crates/ui-egui/src/render_ui/wear.rs b/crates/ui-egui/src/render_ui/wear.rs index 8aed39ca6..7048a14b5 100644 --- a/crates/ui-egui/src/render_ui/wear.rs +++ b/crates/ui-egui/src/render_ui/wear.rs @@ -8,9 +8,9 @@ use crate::{SolveApp, theme::Tokens, ui_kit}; use solidcraft_engine::render::job::aging::{AgingKind, AgingLayer, SurfaceClass}; pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { - note(app, ui, "render.effects_gpu_only"); + note(app, ui, "render.aging_raytrace_help"); ui.add_space(Tokens::get().space_4); - let enabled = app.render_workspace.view.method == ImageMethod::GpuRaytrace; + let enabled = matches!(app.render_workspace.view.method, ImageMethod::CpuRaytrace | ImageMethod::GpuRaytrace); let response = ui.add_enabled_ui(enabled, |ui| layer_controls(app, ui)); crate::scenario::publish_rect("render:wear:controls", response.response.rect); } @@ -163,7 +163,7 @@ fn layer_controls(app: &mut SolveApp, ui: &mut egui::Ui) { note(app, ui, "render.aging_target_help"); }); } - if app.render_workspace.view.method == ImageMethod::GpuRaytrace && before != stack { + if matches!(app.render_workspace.view.method, ImageMethod::CpuRaytrace | ImageMethod::GpuRaytrace) && before != stack { app.render_workspace.view.studio.aging = stack; app.render_workspace.view.dirty = true; } diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 5d6a5f9b7..cfcba4d8f 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -50,8 +50,14 @@ mod library; #[path = "render_ui/assign.rs"] pub(crate) mod assign; +#[path = "render_workspace_displayed.rs"] +pub(crate) mod displayed; #[path = "render_workspace_light.rs"] pub(crate) mod light; +#[path = "render_workspace_live.rs"] +pub(crate) mod live; +#[path = "render_workspace_prepare.rs"] +pub(crate) mod prepare; #[path = "render_workspace_materials.rs"] mod materials; @@ -145,12 +151,15 @@ pub struct State { /// A GPU error the preview's last geometry upload caught. pub upload_error: crate::gpu::UploadError, pub image_host: Option, + live: live::State, + displayed: displayed::State, pub view: ViewState, /// This frame's existing canvas response, consumed once after result chrome /// publishes its real input shields. Never stored in document/tab state. result_navigation: Option<(egui::Rect, egui::Response, bool)>, revision: u64, design_camera: Option<(Camera, bool)>, + entry_fit: Option, slot: SceneSlot, key: Option, /// What the product scene was extracted from: the document's and the world state's @@ -177,6 +186,17 @@ struct PreviewImage { image: Result, } +/// Only the automatic fit of an otherwise clean Render entry may move its transient +/// camera baseline. The saved shot camera remains owned by its explicit update action. +struct EntryFit { + name: String, + clean: RenderSetup, + source: Camera, + bounds: solidcraft_engine::geom::Aabb3, + interim: Camera, + layout: Option, +} + struct DisplayImage<'a> { info: &'a solidcraft_engine::render::job::FrameInfo, image: &'a Result, @@ -196,6 +216,15 @@ pub enum PathHost { } impl PathHost { + /// Setup is a temporary readiness state, not a failed device or request. + fn pending_message_key(&self) -> Option<&'static str> { + match self { + Self::NotStarted => Some("render.gpu_path_not_started"), + Self::Preparing(..) => Some("render.gpu_path_preparing"), + Self::Ready(_) | Self::Failed(_) => None, + } + } + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn start(&mut self, create: impl FnOnce() -> Result + Send + 'static) { if !matches!(self, Self::NotStarted) { @@ -221,7 +250,9 @@ impl PathHost { /// Take the worker's answer if it has come; returns how long a successful setup took. fn poll(&mut self) -> Option { - let Self::Preparing(rx, started) = self else { return None }; + let Self::Preparing(rx, started) = self else { + return None; + }; let took = started.elapsed(); *self = match rx.try_recv() { Ok(Ok(host)) => Self::Ready(host), @@ -248,7 +279,9 @@ pub fn adapter_key(info: &egui_wgpu::wgpu::AdapterInfo) -> String { /// Remember how long the setup on `key` took, for the next start's estimate. fn record_setup(state: &mut State, took: std::time::Duration) { - let Some(key) = state.setup_key.clone() else { return }; + let Some(key) = state.setup_key.clone() else { + return; + }; if state.setup_seconds.len() >= MAX_SETUP_TIMES && !state.setup_seconds.contains_key(&key) { return; } @@ -374,12 +407,22 @@ pub struct ViewState { pub(crate) object_query: String, draft: RenderSetup, dirty: bool, + live_paused: bool, + /// Product framing retained across Design/Render visits, never a saved setting. + render_camera: Option, + /// The CPU sampling choice was initialised or explicitly selected in this draft. + cpu_sampling_initialized: bool, clean_setup: Option, + /// Whether the clean baseline existed in the design, distinguishing Undo removal from + /// an unsaved initial choice that must survive preference or host changes. + clean_persisted: bool, clean_name: String, job: Option, completed: Option, retained: Vec, follow_job: bool, + /// Only a UI Render action that opened the viewer may automatically return to live. + auto_result_job: Option, compare: Option, transparent: bool, method: ImageMethod, @@ -404,6 +447,19 @@ pub struct ViewState { result_job: Option, } +/// The engine retains terminal failures as metadata only. Keep the submitted handle while +/// automatic viewing owns the result, including its native cleanup barrier. +#[derive(Clone)] +struct AutoResultJob { + job: solidcraft_engine::render::job::JobId, + handle: solidcraft_engine::render::job::JobHandle, +} +impl std::fmt::Debug for AutoResultJob { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.job, f) + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] enum ResultScale { #[default] @@ -446,12 +502,17 @@ impl Default for ViewState { object_query: String::new(), draft: RenderSetup::default(), dirty: false, + live_paused: false, + render_camera: None, + cpu_sampling_initialized: false, clean_setup: None, + clean_persisted: false, clean_name: "Studio".into(), job: None, completed: None, retained: Vec::new(), follow_job: true, + auto_result_job: None, compare: None, transparent: false, method: ImageMethod::Raster, @@ -492,10 +553,13 @@ impl Default for State { geometry_budget: WEB_GEOMETRY_BYTES, upload_error: Arc::new(Mutex::new(None)), image_host: None, + live: Default::default(), + displayed: Default::default(), view: Default::default(), result_navigation: None, revision: u64::MAX, design_camera: None, + entry_fit: None, slot: Arc::new(Mutex::new(None)), key: None, scene_signature: None, @@ -557,7 +621,9 @@ impl State { self.path_host = PathHost::failed(crate::i18n::tr("render.gpu_path_crashed").into()); return; } - let Some(create) = self.pending_setup.take() else { return }; + let Some(create) = self.pending_setup.take() else { + return; + }; if let (Some(path), Some(key)) = (&self.setup_marker, &self.setup_key) { write_marker(path, key); } @@ -662,6 +728,10 @@ pub(crate) fn result_active(app: &SolveApp) -> bool { active(app) && app.render_workspace.view.result } +pub(crate) fn comparison_active(app: &SolveApp) -> bool { + active(app) && app.render_workspace.view.compare.is_some() +} + pub(crate) fn comparison_drag_captured(app: &SolveApp) -> bool { active(app) && app.render_workspace.view.compare.as_ref().is_some_and(|view| view.dragging) } @@ -685,7 +755,9 @@ pub(crate) fn inspect_state(app: &SolveApp) -> serde_json::Value { "active": active(app), "stage": view.stage.key(), "setup": view.name, "draft_dirty": view.dirty, "method": method, "job": view.job, "completed": view.completed, "results": view.retained, + "displayed_receipt": displayed::inspect(app), "comparison": view.compare, + "live": live::inspect(app), "preparation": prepare::inspect(app), "batch_preparation": prepare::inspect_batches(app), "queue": app.session.render_queue_state(), "showing_result": view.result, "export_format": if view.studio.export_exr {"exr"} else {"png"}, }) @@ -792,9 +864,13 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { if app.render_workspace.view.job.is_some() { cache_render_images(app, ctx); } + prepare::tick(app, ctx); + live::tick(app, ctx); } pub fn reset_document(app: &mut SolveApp) { + // The app-global preparation owner drains across this document replacement. + prepare::cancel(app); crate::render_ui::reset_shell(app); app.ui.ribbon_context = None; let host = app.render_workspace.host.clone(); @@ -806,7 +882,12 @@ pub fn reset_document(app: &mut SolveApp) { let pending_setup = app.render_workspace.pending_setup.take(); #[cfg(not(target_arch = "wasm32"))] let (setup_marker, crashed_setup) = (app.render_workspace.setup_marker.take(), app.render_workspace.crashed_setup.take()); - app.render_workspace = State { host, image_host, path_host, setup_seconds, setup_key, pending_setup, geometry_budget, ..Default::default() }; + // Hosts are shared across documents. Keep late scratch captures and their cleanup + // barrier until released so a new document cannot race an old live job for admission. + let mut live = std::mem::take(&mut app.render_workspace.live); + live.retire_document(); + app.render_workspace = + State { host, image_host, path_host, setup_seconds, setup_key, pending_setup, geometry_budget, live, ..Default::default() }; #[cfg(not(target_arch = "wasm32"))] { // The running-setup marker is the application's, like the setup itself. @@ -820,6 +901,7 @@ pub fn reset_document(app: &mut SolveApp) { } pub(crate) fn invalidate_images(app: &mut SolveApp) { + app.render_workspace.displayed.clear(); app.render_workspace.image = None; app.render_workspace.image_info = None; app.render_workspace.preview_image = None; @@ -848,6 +930,7 @@ pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { app.run("render.scene", json!({}))?; let entering = !active(app); if entering { + app.render_workspace.displayed.clear(); app.render_workspace.design_camera = Some((app.cam, app.ui.perspective)); app.ui.tab = "RENDER".into(); select_stage(app, app.render_workspace.view.stage.key()); @@ -855,13 +938,46 @@ pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { selection_editor(app, &RenderSelection::Nothing); } } + let remembered = + entering.then_some(app.render_workspace.view.render_camera).flatten().filter(|_| !app.preferences.render_legacy_image_defaults); + if let Some(camera) = remembered { + app.run("render.camera.set", json!({"camera":camera}))?; + app.follow_view_request(false); + app.ui.perspective = camera.fov > 0.0; + } setups::refresh_dirty(app); + let hydrate_camera = entering + && remembered.is_none() + && !app.preferences.render_legacy_image_defaults + && !app.render_workspace.view.dirty + && !setups::has_runtime_inputs(app); setups::sync_revision(app); - // Fit once the setup in effect is known: the fit frames that image's aspect. - if entering { + let mut restored = remembered.is_some(); + if hydrate_camera && app.session.doc.render.setups.get(&app.render_workspace.view.name).is_some_and(|setup| setup.camera != Camera::default()) + { + let name = app.render_workspace.view.name.clone(); + inspector::activate_saved_shot(app, name)?; + restored = true; + } + // Only an uncomposed first view fits automatically. An explicit saved or + // remembered Render camera keeps its lens projection and exact framing. + if entering && !restored { let scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|e| e.to_string())?; if !scene.bounds.is_empty() { + let clean = + app.render_workspace.view.clean_setup.clone().filter(|clean| { + !app.render_workspace.view.dirty && !setups::has_runtime_inputs(app) && setups::draft(app).as_ref() == Ok(clean) + }); + let source = app.cam; app.fit_bounds(scene.bounds); + app.render_workspace.entry_fit = clean.map(|clean| EntryFit { + name: app.render_workspace.view.name.clone(), + clean, + source, + bounds: scene.bounds, + interim: app.cam, + layout: None, + }); } } #[cfg(not(target_arch = "wasm32"))] @@ -869,7 +985,12 @@ pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { app.render_workspace.start_deferred_path_host(); } } else { + app.render_workspace.displayed.clear(); assign::stop(app); + if active(app) { + app.render_workspace.view.render_camera = (!app.preferences.render_legacy_image_defaults).then_some(app.cam); + setups::refresh_dirty(app); + } if let Some((camera, perspective)) = app.render_workspace.design_camera.take() { app.cam = camera; app.ui.up_axis = camera.up; @@ -881,11 +1002,74 @@ pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { app.viewport.hover = None; app.cam_anim = None; if !render { + cancel_entry_fit(app); app.pending_fit = None; } Ok(()) } +/// Camera takeover cancels the entry-only allowance along with the pending fit. +pub(crate) fn cancel_entry_fit(app: &mut SolveApp) { + app.render_workspace.entry_fit = None; +} + +/// The first Render frame can still carry Design's measured floating-panel bounds. +/// Only this exact automatic entry fit waits for two matching Render measurements. +pub(crate) fn wait_entry_fit_layout(app: &mut SolveApp) -> bool { + let Some(entry) = app.render_workspace.entry_fit.as_ref() else { + return false; + }; + if !active(app) + || app.render_workspace.view.name != entry.name + || app.cam != entry.interim + || app.pending_fit != Some((entry.source, entry.bounds, false, false)) + { + cancel_entry_fit(app); + return false; + } + let Some(layout) = app.viewport.layout.as_ref() else { + return false; + }; + let layout = picture_layout(app, layout); + let Some(entry) = app.render_workspace.entry_fit.as_mut() else { + return false; + }; + if entry.layout.as_ref() == Some(&layout) { + return false; + } + entry.layout = Some(layout); + true +} + +/// Called only when a nonanimated pending fit actually installs its final camera. +pub(crate) fn settle_entry_fit(app: &mut SolveApp, source: Camera, bounds: solidcraft_engine::geom::Aabb3, previous: Camera) { + let Some(entry) = app.render_workspace.entry_fit.take() else { + return; + }; + if !active(app) + || app.render_workspace.view.name != entry.name + || source != entry.source + || bounds != entry.bounds + || previous != entry.interim + || app.render_workspace.view.clean_setup.as_ref() != Some(&entry.clean) + || setups::has_runtime_inputs(app) + { + return; + } + let Ok(mut draft) = setups::draft(app) else { + return; + }; + draft.camera = entry.clean.camera; + if draft != entry.clean { + return; + } + let Some(clean) = app.render_workspace.view.clean_setup.as_mut() else { + return; + }; + clean.camera = app.cam; + setups::refresh_dirty(app); +} + /// Stage navigation is transient per-document state. It never applies a resource or starts a job. pub(crate) fn select_stage(app: &mut SolveApp, key: &str) { let stage = match key { @@ -1019,8 +1203,13 @@ pub(crate) fn appearances_card(app: &mut SolveApp, ui: &mut egui::Ui, bounds: eg fn image_host(app: &SolveApp, method: ImageMethod) -> Result<&ImageHost, String> { if method == ImageMethod::GpuRaytrace { - let PathHost::Ready(host) = &app.render_workspace.path_host else { - return Err(app.tr("render.gpu_unavailable").to_string()); + let host = match &app.render_workspace.path_host { + PathHost::NotStarted => return Err(app.tr("render.gpu_path_not_started").to_string()), + PathHost::Preparing(..) => return Err(app.tr("render.gpu_path_preparing").to_string()), + PathHost::Failed(error) => { + return Err(format!("{}: {error}", app.tr("render.gpu_path_failed"))); + } + PathHost::Ready(host) => host, }; let descriptor = host.descriptor().map_err(|error| error.to_string())?; if !host.is_available() @@ -1054,8 +1243,8 @@ fn image_request(app: &SolveApp) -> Result { fn raw_image_request(app: &SolveApp) -> Result { cpu::validate_progressive_image(app)?; - if !setups::has_runtime_inputs(app) { - return Ok(json!({"settings":setups::snapshot(app)?})); + if !setups::requires_runtime_request(app) { + return Ok(json!({"settings":setups::image_snapshot(app)?})); } let view = &app.render_workspace.view; // Temporary bindings and unsaved HDR captures use the runtime API. Embedded HDRs @@ -1063,15 +1252,14 @@ fn raw_image_request(app: &SolveApp) -> Result { if !view.draft.surfaces.is_empty() { return Err(app.tr("render.saved_maps_runtime_conflict").to_string()); } - let settings = RenderSetup { camera: app.cam, job: None, ..view.draft.clone() }; + let mut settings = RenderSetup { camera: app.cam, job: None, ..view.draft.clone() }; + materials::overlay_coats(app, &mut settings)?; let mut params = json!({"settings":settings,"transparent_background":view.transparent}); match view.method { ImageMethod::Raster => {} ImageMethod::CpuRaytrace => { - if view.transparent { - return Err(app.tr("render.cpu_opaque_required").to_string()); - } cpu::params(app, &mut params)?; + params["aging"] = json!(view.studio.aging); } ImageMethod::GpuRaytrace => { params["progressive"] = json!(true); @@ -1085,8 +1273,138 @@ fn raw_image_request(app: &SolveApp) -> Result { Ok(params) } +fn celestial_switch_active(app: &SolveApp) -> bool { + let view = &app.render_workspace.view; + view.studio.sun_enabled + || match view.method { + ImageMethod::CpuRaytrace => view.cpu.environment == cpu::Environment::Sky, + ImageMethod::GpuRaytrace => view.studio.environment == studio::Environment::Sky, + ImageMethod::Raster => false, + } +} + +/// One prospective numerical command transfers every shared physical effect. +/// Failure restores the full draft; navigation and saved camera stay untouched. +fn switch_celestial_method(app: &mut SolveApp, method: ImageMethod, enable_indirect: bool) -> Result<(), String> { + if setups::has_unportable_bindings(app) { + return Err(app.tr("render.setup_runtime_unsupported").into()); + } + let before = setups::draft(app)?; + let before_render = std::sync::Arc::downgrade(&app.session.doc.render); + let previous = app.render_workspace.view.clone(); + if previous.studio.transmission_samples != 1 { + return Err(app.tr("render.cpu_celestial_unportable").into()); + } + let mut next = previous.clone(); + if method == ImageMethod::CpuRaytrace { + if enable_indirect { + let depth = u8::try_from(next.max_depth).map_err(|_| app.tr("render.cpu_celestial_switch").to_string())?; + let path = solidcraft_engine::render::job::CpuPathOptions { max_depth: depth }; + path.validate().map_err(|error| error.to_string())?; + next.raytrace.path = Some(path); + next.raytrace.progressive.get_or_insert_default(); + next.raytrace.primary_samples = 1; + next.raytrace.shadows = true; + next.cpu_sampling_initialized = true; + } + if next.raytrace.path.is_none() { + if next.studio.volume.is_some_and(|volume| volume.active()) { + return Err(app.tr("render.cpu_volume_path_required").into()); + } + if celestial_switch_active(app) { + return Err(app.tr("render.cpu_celestial_switch").into()); + } + } + next.cpu.environment = match previous.studio.environment { + studio::Environment::Sky => cpu::Environment::Sky, + studio::Environment::Hdr => cpu::Environment::Hdr, + studio::Environment::None => { + let ambient = if previous.studio.lighting_enabled { previous.studio.ambient } else { [0.0; 3] }; + let intensity = ambient.into_iter().fold(0.0_f64, f64::max); + if intensity > 64.0 { + return Err(app.tr("render.cpu_environment_bounds").into()); + } + next.cpu.color = if intensity > 0.0 { ambient.map(|value| value / intensity) } else { [1.0; 3] }; + next.cpu.intensity = intensity; + if intensity > 0.0 { cpu::Environment::Constant } else { cpu::Environment::None } + } + }; + if previous.studio.environment != studio::Environment::None { + if previous.studio.environment == studio::Environment::Hdr && previous.studio.assume_linear_srgb { + return Err(app.tr("render.environment.primaries_gpu").into()); + } + next.cpu.gradient = previous.studio.gradient; + next.cpu.rotation_rad = previous.studio.rotation_rad; + next.cpu.intensity = previous.studio.intensity; + next.cpu.hdr = previous.studio.hdr.clone(); + } + } else if method == ImageMethod::GpuRaytrace { + next.studio.environment = match previous.cpu.environment { + cpu::Environment::Sky => studio::Environment::Sky, + cpu::Environment::Hdr => studio::Environment::Hdr, + cpu::Environment::None | cpu::Environment::Constant => studio::Environment::None, + }; + next.studio.ambient = if previous.cpu.environment == cpu::Environment::Constant { + previous.cpu.color.map(|value| value * previous.cpu.intensity) + } else { + [0.0; 3] + }; + if previous.cpu.environment != cpu::Environment::None && previous.cpu.environment != cpu::Environment::Constant { + next.studio.gradient = previous.cpu.gradient; + next.studio.rotation_rad = previous.cpu.rotation_rad; + next.studio.intensity = previous.cpu.intensity; + next.studio.hdr = previous.cpu.hdr.clone(); + next.studio.assume_linear_srgb = false; + } + } else { + return Err(app.tr("render.output_raytrace_only").into()); + } + light::celestial_method(app, &mut next, method)?; + next.method = method; + next.dirty = true; + app.render_workspace.view = next; + let result = environment::validate_atmosphere(app) + .and_then(|()| setups::snapshot(app).map(|_| ())) + .and_then(|()| cpu::validate_progressive_image(app)) + .and_then(|()| setups::persist_editor(app, &before)); + if let Err(error) = result { + app.render_workspace.view = previous; + return Err(error); + } + light::celestial_method_applied(app, &before_render, previous.method); + Ok(()) +} + +/// Volume and celestial choices share one atomic transaction, including both. +fn switch_volume_method(app: &mut SolveApp, method: ImageMethod, enable_indirect: bool) -> Result<(), String> { + switch_celestial_method(app, method, enable_indirect) +} + 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()) + { + let result = if app.render_workspace.view.studio.volume.is_some() { + switch_volume_method(app, method, false) + } else { + switch_celestial_method(app, method, false) + }; + if let Err(error) = result { + app.set_status(error, true); + } + return; + } app.render_workspace.view.method = method; + if method == ImageMethod::CpuRaytrace && !app.render_workspace.view.cpu_sampling_initialized { + let options = &mut app.render_workspace.view.raytrace; + if !app.preferences.render_legacy_image_defaults && options.progressive.is_none() { + options.progressive = Some(Default::default()); + options.primary_samples = 1; + } + app.render_workspace.view.cpu_sampling_initialized = true; + } // Raster has no exposure control. Selecting it explicitly selects its zero-EV response. if method == ImageMethod::Raster { app.render_workspace.view.draft.exposure_ev = 0.0; @@ -1110,7 +1428,9 @@ 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 response = crate::ui_kit::dropdown_menu(ui, "render_image_method", &label, |ui| { + let bounded = celestial_switch_active(app) || app.render_workspace.view.studio.volume.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 [ (ImageMethod::Raster, "render:method-raster"), (ImageMethod::CpuRaytrace, "render:method-cpu"), @@ -1128,7 +1448,36 @@ fn method_dropdown(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response { response.backing_on_hover_text(reason); } } - }); + 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() { + 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" }, + &[ + ("depth", &app.render_workspace.view.max_depth.to_string()), + ("spp", &sampling.samples_per_pixel.to_string()), + ("seed", &sampling.seed.to_string()), + ], + ); + let short = app.tr(if volume_path { "render.cpu_volume_method_adopt" } else { "render.cpu_celestial_adopt_label" }).to_string(); + let action = crate::ui_kit::list_picker(ui, "render:method-cpu-indirect", &short, false).on_hover_text(detail); + crate::scenario::publish_handle("render:method-cpu-indirect", action.rect.center()); + if volume_path { + crate::scenario::publish_handle("render:method-cpu-volume", action.rect.center()); + } + if action.clicked() { + if let Err(error) = switch_celestial_method(app, ImageMethod::CpuRaytrace, true) { + app.set_status(error, true); + } + ui.close(); + } + } + }; + let response = if bounded { + crate::ui_kit::bounded_dropdown_menu(ui, "render_image_method", &label, width, choices) + } else { + crate::ui_kit::dropdown_menu(ui, "render_image_method", &label, choices) + }; crate::scenario::publish_handle("render:method", response.rect.center()); response } @@ -1138,6 +1487,9 @@ fn cpu_sampling_controls(app: &mut SolveApp, ui: &mut egui::Ui) { if progressive { crate::ui_kit::text(ui, app.tr("render.cpu_progressive_help"), crate::ui_kit::Text::Note("render.cpu_progressive_help")); } + if progressive && !app.preferences.render_legacy_image_defaults { + return; + } ui.add_enabled_ui(!progressive, |ui| { crate::ui_kit::text(ui, app.tr("render.children.edge_samples"), crate::ui_kit::Text::Inline); let samples = app.render_workspace.view.raytrace.primary_samples; @@ -1491,6 +1843,28 @@ fn displayed_image(app: &SolveApp) -> Option> { Some(DisplayImage { info: state.image_info.as_ref()?, image: &state.image.as_ref()?.1, preview: None }) } +fn captured_adaptive_preview( + status: &solidcraft_engine::render::job::JobStatus, + completed: u32, +) -> Result, String> { + use solidcraft_engine::render::job::adaptive::AdaptivePreview; + if status.request.integrator == Integrator::Raytrace && status.resolved.executor.as_str() != "gpu-path" { + let Some(options) = &status.request.raytrace else { + return Ok(None); + }; + options + .adaptive + .as_deref() + .map(|adaptive| { + let maximum = options.progressive.ok_or_else(|| crate::i18n::tr("render.error_provisional_identity").to_string())?.samples_per_pixel; + AdaptivePreview::captured(*adaptive, maximum, completed).map_err(|error| error.to_string()) + }) + .transpose() + } else { + AdaptivePreview::at(status.options, completed).map_err(|error| error.to_string()) + } +} + fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewInfo, png: &[u8]) { if app.render_workspace.view.job != Some(info.frame.job) { return; @@ -1504,7 +1878,7 @@ fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewIn return; } let result = (|| -> Result { - if info.frame_sequence == 0 || !(1..=4096).contains(&info.samples_per_pixel) { + if info.frame_sequence == 0 || info.samples_per_pixel == 0 { return Err(crate::i18n::tr("render.error_provisional_identity").into()); } let handle = app.session.render_job_handle(info.frame.job).map_err(|e| e.to_string())?; @@ -1512,15 +1886,32 @@ fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewIn if (info.frame.width, info.frame.height) != (captured.request.width, captured.request.height) { return Err(crate::i18n::tr("render.error_checkpoint_dimensions").into()); } - let options = solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: info.samples_per_pixel, seed: 0 }; - options.validate_image_with_budget(info.frame.width, info.frame.height, captured.request.cpu_budget()).map_err(|error| error.to_string())?; - let image = decode_render_image( - png, - info.frame.width, - info.frame.height, - captured_image_limits(&captured.request), - ctx.input(|i| i.max_texture_side), - )?; + if info.frame.executor != captured.resolved.executor || info.frame.scene_generation != captured.scene_generation { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + let limits = if info.frame.executor.as_str() == "gpu-path" { + let target = captured.options.preview_target().map_err(|e| e.to_string())?; + let adaptive = + solidcraft_engine::render::job::adaptive::AdaptivePreview::at(captured.options, info.samples_per_pixel).map_err(|e| e.to_string())?; + if info.samples_per_pixel >= target || info.adaptive != adaptive { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + solidcraft_engine::render::job::GPU_PATH_LIMITS + } else { + let adaptive = captured_adaptive_preview(&captured, info.samples_per_pixel)?; + let exceeds_target = adaptive.is_some() + && info.samples_per_pixel + >= captured.request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::preview_target).map_err(|e| e.to_string())?; + if exceeds_target || info.adaptive != adaptive { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + let options = solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: info.samples_per_pixel, seed: 0 }; + options + .validate_image_with_budget(info.frame.width, info.frame.height, captured.request.cpu_budget()) + .map_err(|error| error.to_string())?; + captured_image_limits(&captured.request) + }; + let image = decode_render_image(png, info.frame.width, info.frame.height, limits, ctx.input(|i| i.max_texture_side))?; Ok(ctx.load_texture("sc_render_preview", image, egui::TextureOptions::LINEAR)) })(); // Cache errors by identity too: a malformed publication cannot decode on every repaint. @@ -1547,7 +1938,9 @@ fn cache_preview_image(app: &mut SolveApp, ctx: &egui::Context) { } fn remember_displayed_job(app: &mut SolveApp, preserve_view: bool) { - let Some(job) = displayed_image(app).map(|display| display.info.job) else { return }; + let Some(job) = displayed_image(app).map(|display| display.info.job) else { + return; + }; if app.render_workspace.view.result_job != Some(job) { app.render_workspace.view.result_job = Some(job); if !preserve_view { @@ -1566,10 +1959,46 @@ fn cache_render_images(app: &mut SolveApp, ctx: &egui::Context) { cache_completed_image(app, ctx); // Checkpoint updates and preview→final/cancel transitions preserve shared pan/zoom. remember_displayed_job(app, preserve_view); + finish_auto_result(app); +} + +fn finish_auto_result(app: &mut SolveApp) { + use solidcraft_engine::render::job::Phase; + let Some(auto) = &app.render_workspace.view.auto_result_job else { + return; + }; + if app.render_workspace.view.job != Some(auto.job) { + app.render_workspace.view.auto_result_job = None; + return; + } + let handle = auto.handle.clone(); + let Ok(status) = handle.status() else { return }; + if !matches!(status.progress.phase, Phase::Completed | Phase::Cancelled | Phase::Failed) { + return; + } + let view = &mut app.render_workspace.view; + view.auto_result_job = None; + if matches!(status.progress.phase, Phase::Cancelled | Phase::Failed) + && !app.preferences.render_legacy_image_defaults + && view.result + && view.follow_job + && view.compare.is_none() + && view.completed.is_none() + { + // The automatically opened viewer has neither a final nor a valid checkpoint. + // Resume the product canvas before live::tick observes its suspension state. + view.result = false; + live::drain_final(app, handle); + if let Some(error) = status.error { + app.set_status(error.to_string(), true); + } + } } fn sync_results(app: &mut SolveApp) { - let Ok(mut results) = app.session.render_retained_results() else { return }; + let Ok(mut results) = app.session.render_retained_results() else { + return; + }; let view = &mut app.render_workspace.view; for result in &mut results { if result.shot.is_none() { @@ -1591,12 +2020,15 @@ fn sync_results(app: &mut SolveApp) { fn follow_batch(app: &mut SolveApp) { let queue = app.session.render_queue_state(); + follow_batch_view(&mut app.render_workspace.view, queue); +} +fn follow_batch_view(view: &mut ViewState, queue: solidcraft_engine::render_jobs::RenderQueueState) { if let Some(job) = queue.job { - if app.render_workspace.view.job != Some(job) { - app.render_workspace.view.follow_job = app.render_workspace.view.compare.is_none(); + if view.job != Some(job) { + view.follow_job = view.compare.is_none(); } - app.render_workspace.view.job = Some(job); - app.render_workspace.view.job_shot = queue.shot; + view.job = Some(job); + view.job_shot = queue.shot; } } @@ -1728,8 +2160,7 @@ fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { }); return; } - compare::controls(app, ui); - result_action_controls(app, ui); + classic_result_actions(app, ui); } /// Keep enabled state on the wrapping UI itself. Button::Enabled opens a child @@ -1751,16 +2182,21 @@ fn result_action_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let selected = results.iter().position(|result| Some(result.frame.job) == app.render_workspace.view.completed); let label = selected.and_then(|index| results.get(index)).map(result_label).unwrap_or_else(|| app.tr("render.results_choose").to_string()); let mut chosen = None; - let picker = crate::ui_kit::compact_dropdown_menu(ui, "render_results", &label, |ui| { + let t = Tokens::get(); + let width = (ui.available_width() - t.control_height - ui.spacing().item_spacing.x).max(t.control_height); + let picker = crate::ui_kit::bounded_dropdown_menu(ui, "render_results", &label, width, |ui| { for (index, result) in results.iter().enumerate().rev() { - let response = crate::ui_kit::list_picker(ui, &format!("result:{index}"), &result_label(result), selected == Some(index)); + let item_label = result_label(result); + let response = crate::ui_kit::list_picker(ui, &format!("result:{index}"), &item_label, selected == Some(index)); crate::scenario::publish_target(&format!("render:result:select:{index}"), response.rect); if response.clicked() { chosen = Some(index); ui.close(); } + response.on_hover_text(item_label); } }); + let picker = picker.on_hover_text(&label); crate::scenario::publish_target("render:results", picker.rect); if let Some(index) = chosen { let _ = app.run("render.result.select", json!({"index":index})); @@ -1783,6 +2219,7 @@ fn result_action_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let enabled = view != "actual" || !reduced_display(app); let response = result_action_button(ui, app.tr(key), enabled, host); crate::scenario::publish_target(&format!("render:result-{view}"), response.rect); + crate::scenario::publish_target(&format!("render:result:view:{view}"), response.rect); if response.clicked() { let _ = app.run("render.result.view", json!({"view":view})); } @@ -1804,6 +2241,81 @@ fn result_action_controls(app: &mut SolveApp, ui: &mut egui::Ui) { } } +fn classic_result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { + // Each independently sized control group begins in the original free width. + // A ComboBox width is a minimum; placing it after the comparison strip in a + // wrapped row can otherwise move its entire hit target under the inspector. + ui.horizontal_wrapped(|ui| compare::controls(app, ui)); + let results = app.render_workspace.view.retained.clone(); + if !results.is_empty() { + ui.horizontal_wrapped(|ui| { + let selected = results.iter().position(|result| Some(result.frame.job) == app.render_workspace.view.completed); + let label = + selected.and_then(|index| results.get(index)).map(result_label).unwrap_or_else(|| app.tr("render.results_choose").to_string()); + let mut chosen = None; + let t = Tokens::get(); + let width = (ui.available_width() - t.control_height - ui.spacing().item_spacing.x).max(t.control_height); + let picker = crate::ui_kit::bounded_dropdown_menu(ui, "render_results", &label, width, |ui| { + for (index, result) in results.iter().enumerate().rev() { + let label = result_label(result); + let response = crate::ui_kit::list_picker(ui, &format!("result:{index}"), &label, selected == Some(index)); + crate::scenario::publish_target(&format!("render:result:select:{index}"), response.rect); + if response.clicked() { + chosen = Some(index); + ui.close(); + } + response.on_hover_text(label); + } + }); + let picker = picker.on_hover_text(&label); + crate::scenario::publish_target("render:results", picker.rect); + if let Some(index) = chosen { + let _ = app.run("render.result.select", json!({"index":index})); + } + let discard = ui + .add_enabled_ui(selected.is_some(), |ui| crate::ui_kit::StageBar::icon_action(ui, "delete", app.tr("cmd.render.result.discard"))) + .inner; + crate::scenario::publish_target("render:result-discard", discard.rect); + if discard.clicked() + && let Some(index) = selected + { + let _ = app.run("render.result.discard", json!({"index":index})); + } + }); + } + ui.horizontal_wrapped(|ui| { + for (view, key) in [("model", "render.state_model"), ("fit", "render.output_fit"), ("actual", "render.result_actual")] { + let enabled = view != "actual" || !reduced_display(app); + let response = crate::ui_kit::button(ui, app.tr(key), crate::ui_kit::Button::Enabled(enabled)); + crate::scenario::publish_target(&format!("render:result:view:{view}"), response.rect); + crate::scenario::publish_target(&format!("render:result-{view}"), response.rect); + if response.clicked() { + let _ = app.run("render.result.view", json!({"view":view})); + } + } + let copy = crate::ui_kit::button( + ui, + app.tr("render.output_copy"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.result.copy").is_ok()), + ); + crate::scenario::publish_target("render:result-copy", copy.rect); + if copy.clicked() { + app.start("render.result.copy"); + } + let export = + crate::ui_kit::button(ui, studio::export_label(app), crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.export").is_ok())); + crate::scenario::publish_target("render:result-export", export.rect); + if export.clicked() { + app.start("render.export"); + } + let close = crate::ui_kit::StageBar::icon_action(ui, "close", app.tr("cmd.render_result_close")); + crate::scenario::publish_target("render:result-close", close.rect); + if close.clicked() { + app.start("render.result.close"); + } + }); +} + fn result_label(result: &solidcraft_engine::render_jobs::RetainedResult) -> String { let name = result.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed")); let label = crate::i18n::format( @@ -1822,28 +2334,48 @@ fn result_header(app: &mut SolveApp, ui: &mut egui::Ui) { None if ribbon::busy(app) => "render.state_in_progress", None => "render.result_title", }; - if app.universal_panel_host_enabled() { - crate::ui_kit::text(ui, app.tr(state), crate::ui_kit::Text::Inline); - result_actions(app, ui); - } else { - ui.horizontal_wrapped(|ui| { - crate::ui_kit::text(ui, app.tr(state), crate::ui_kit::Text::Inline); - result_actions(app, ui); - }); - } - let Some((info, preview)) = display else { return }; + crate::ui_kit::text(ui, app.tr(state), crate::ui_kit::Text::Inline); + result_actions(app, ui); + let Some((info, preview)) = display else { + return; + }; if let Some(preview) = &preview { - ui.colored_label( - t.warning, + let target = app + .session + .render_job_handle(preview.frame.job) + .ok() + .and_then(|handle| handle.status().ok()) + .map(|status| { + if preview.frame.executor.as_str() == "gpu-path" { + status.options.samples + } else { + status.request.raytrace.as_ref().and_then(|options| options.preview_target().ok()).unwrap_or(preview.samples_per_pixel) + } + }) + .unwrap_or(preview.samples_per_pixel); + let message = if let Some(adaptive) = preview.adaptive { format!( - "{} · {} {} · {} {}", + "{} · {} · {} {}", + app.tr("render.result_provisional"), + adaptive_preview_label(app, adaptive), + app.tr("render.result_sequence"), + preview.frame_sequence + ) + } else { + format!( + "{} · {} / {} {} · {} {}", app.tr("render.result_provisional"), preview.samples_per_pixel, + target, app.tr("render.cpu_progressive_spp"), app.tr("render.result_sequence"), preview.frame_sequence - ), - ); + ) + }; + ui.colored_label(t.warning, message); + if preview.adaptive.is_some() { + ui.small(app.tr("render.adaptive.preview_help")); + } ui.small(app.tr("render.result_provisional_help")); } if let Some(display) = displayed_image(app) @@ -1882,7 +2414,9 @@ pub(crate) fn host_result_overlays(app: &mut SolveApp, ui: &mut egui::Ui) { if !app.universal_panel_host_enabled() || !active(app) || (!result_active(app) && app.render_workspace.view.compare.is_none()) { return; } - let Some(canvas) = app.viewport.rect.filter(|rect| rect.is_finite() && rect.is_positive()) else { return }; + let Some(canvas) = app.viewport.rect.filter(|rect| rect.is_finite() && rect.is_positive()) else { + return; + }; crate::viewport::refresh_layout(app, ui.ctx()); if !crate::render_ui::focused(app) && let Some(usable) = app.viewport.layout.as_ref().and_then(|layout| layout.usable.clone()) @@ -1979,7 +2513,9 @@ fn update_host_result_camera(app: &mut SolveApp, ctx: &egui::Context, canvas: eg let camera = if scale == ResultScale::Actual { result_camera(size, canvas, ctx.pixels_per_point(), scale) } else { - let Some(usable) = app.viewport.layout.as_ref().and_then(|layout| layout.usable.as_ref()) else { return }; + let Some(usable) = app.viewport.layout.as_ref().and_then(|layout| layout.usable.as_ref()) else { + return; + }; let aspect = size[0].max(1) as f32 / size[1].max(1) as f32; let Some(room) = usable.fit_rect_with_clearance(aspect, Point { x: canvas.center().x, y: canvas.center().y }, Tokens::get().space_8) else { return; @@ -2022,6 +2558,7 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { crate::viewport::refresh_layout(app, ui.ctx()); } let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_result_content")); + content.set_clip_rect(free.intersect(ui.clip_rect())); let ui = &mut content; let Some(info) = displayed_image(app).map(|display| display.info.clone()) else { let message = match &app.render_workspace.image { @@ -2032,9 +2569,23 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { if !host { crate::ui_kit::Container::navigation_contents(ui, |ui| result_header(app, ui)); } - let canvas = ui.available_rect_before_wrap(); + let unavailable = app + .render_workspace + .view + .job + .and_then(|job| app.session.render_job_handle(job).ok()) + .and_then(|handle| handle.status().ok()) + .and_then(|status| status.preview_unavailable_reason); + let canvas = ui.available_rect_before_wrap().intersect(free); ui.centered_and_justified(|ui| { - ui.add(egui::Label::new(egui::RichText::new(message).size(t.font_heading).color(t.text)).wrap()); + ui.vertical_centered(|ui| { + ui.add(egui::Label::new(egui::RichText::new(message).size(t.font_heading).color(t.text)).wrap()); + if ribbon::busy(app) + && let Some(reason) = unavailable + { + ui.small(reason); + } + }); }); app.viewport.rect = Some(canvas); return; @@ -2042,7 +2593,8 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { if !host { crate::ui_kit::Container::navigation_contents(ui, |ui| result_header(app, ui)); } - let rect = ui.available_rect_before_wrap(); + // Widget growth cannot enlarge the reserved image/navigation canvas. + let rect = ui.available_rect_before_wrap().intersect(free); if rect.width() < 1.0 || rect.height() < 1.0 { return; } @@ -2089,7 +2641,9 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(display) = displayed_image(app) && let Ok(texture) = display.image { + let source = displayed::Source::image(display.info, display.preview); painter.image(texture.id(), image_rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Tokens::get().file_image_tint); + app.render_workspace.displayed.record(&painter, image_rect, source); } painter.rect_stroke(image_rect, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Outside); } @@ -2122,6 +2676,17 @@ fn preview_signature(app: &mut SolveApp) -> (u64, usize, u64) { signature } +pub(super) fn adaptive_preview_label(_app: &SolveApp, progress: solidcraft_engine::render::job::adaptive::AdaptivePreview) -> String { + use solidcraft_engine::render::job::adaptive::PreviewStage; + crate::i18n::format( + match progress.stage { + PreviewStage::Pilot => "render.adaptive.pilot_progress", + PreviewStage::Production => "render.adaptive.production_progress", + }, + &[("current", &progress.completed.to_string()), ("target", &progress.target.to_string())], + ) +} + impl State { fn prepare_preview(&mut self, signature: (u64, usize, u64, u64), capture: impl FnOnce() -> Result) -> Result<(), String> { if self.scene_signature != Some(signature) { @@ -2353,7 +2918,9 @@ fn gpu_scene_with_budget(scene: &ProductScene, budget: u64) -> Result<(u64, GpuS let n = if surface.is_some() { solidcraft_engine::render::surface::unit_direction(n).ok()? } else { n }.to_f32(); p.into_iter().chain(n).all(f32::is_finite).then_some((p, n)) }); - let [Some(a), Some(b), Some(c)] = vertices else { return Err(crate::i18n::tr("render.error_product_triangle").into()) }; + let [Some(a), Some(b), Some(c)] = vertices else { + return Err(crate::i18n::tr("render.error_product_triangle").into()); + }; let rgba = [color[0], color[1], color[2], (opacity * 255.0).round() as u8]; let index = gpu.color(rgba); for (p, n) in [a, b, c] { @@ -2391,23 +2958,54 @@ pub fn image_aspect(setup: &RenderSetup) -> f64 { f64::from(setup.width.max(1)) / f64::from(setup.height.max(1)) } -/// `layout` seen from the picture: while Frame shows the picture's frame the preview projects -/// into that frame, not the viewport, so a fit that keeps the product inside this layout keeps -/// it inside the image. Elsewhere the preview fills the viewport and the layout is unchanged. -pub(crate) fn picture_layout(app: &SolveApp, layout: &crate::viewport_layout::Layout) -> crate::viewport_layout::Layout { - let Some(frame) = shot::preview_rect(app, layout.viewport) else { return layout.clone() }; - // The same 16-point margin the viewport's fit keeps inside its free area. - crate::viewport_layout::Layout { viewport: frame, drawable: layout.drawable.intersect(frame.shrink(16.0)), ..layout.clone() } +/// Product Fit/navigation use the actual output-camera frame in every inspector. +/// Contextual guide visibility is independent; the compatibility preference keeps +/// its previous Frame-only projection policy. +pub(crate) fn camera_rect(app: &SolveApp, supplied: egui::Rect) -> egui::Rect { + if app.viewport.rect != Some(supplied) { + return supplied; + } + authored_camera_rect(app, supplied) } -/// The exact projection used by Frame/selected-Shot paint and picking, with -/// current real host obstacles clipped to that picture rather than the window. +/// Resolve the painted projection from an authoritative outer product canvas. +fn authored_camera_rect(app: &SolveApp, supplied: egui::Rect) -> egui::Rect { + if !active(app) || app.preferences.render_legacy_image_defaults || app.render_workspace.view.result || app.render_workspace.view.compare.is_some() + { + return supplied; + } + live::projection_rect(app, shot::render_rect(app, supplied)) +} + +pub(crate) fn picture_layout(app: &SolveApp, layout: &crate::viewport_layout::Layout) -> crate::viewport_layout::Layout { + let frame = if app.preferences.render_legacy_image_defaults { + live::projection_rect(app, shot::render_rect(app, layout.viewport)) + } else { + camera_rect(app, layout.viewport) + }; + if frame == layout.viewport { + return layout.clone(); + } + // The same 16-point margin the viewport's fit keeps inside its free area. + crate::viewport_layout::Layout { + viewport: frame, + drawable: layout.drawable.intersect(frame.shrink(16.0)), + middle: layout.middle.intersect(frame), + ..layout.clone() + } +} + +/// Clip the current host obstacles to the painted product projection. pub(crate) fn host_picture_layout( app: &SolveApp, layout: &crate::viewport_layout::Layout, usable: &crate::panel_runtime::HostUsableRegion, ) -> Option { - let picture = shot::preview_rect(app, layout.viewport).unwrap_or(layout.viewport); + let picture = if app.preferences.render_legacy_image_defaults { + shot::preview_rect(app, layout.viewport).unwrap_or(layout.viewport) + } else { + authored_camera_rect(app, layout.viewport) + }; crate::viewport_layout::host_projection_layout(layout, usable, picture) } @@ -2482,11 +3080,17 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let viewport = ui.max_rect(); app.viewport.rect = Some(viewport); // Framing uses the output camera's own aspect, including navigation and picking. - let rect = shot::preview_rect(app, viewport).unwrap_or(viewport); + let rect = live::projection_rect(app, shot::render_rect(app, viewport)); + crate::scenario::publish_rect("render:product:frame", rect); crate::viewport::refresh_layout(app, ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with("render_preview"), Sense::click_and_drag()); + // Gray letterbox remains an ordinary navigation surface. Geometry assignment + // and selection are separately limited to the actual image camera below. + let input_rect = if app.preferences.render_legacy_image_defaults { rect } else { viewport }; + let response = ui.interact(input_rect, ui.scope_id().with("render_preview"), Sense::click_and_drag()); + let geometry_current = live::picking_current(app); if !environment::ring_input(app, ui, rect, &response) { - let input = crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps::RENDER); + let input = crate::navigation::handle(app, ui, input_rect, &response, crate::navigation::NavCaps::RENDER); + let image_inside = input.inside && input.hover.is_some_and(|point| rect.contains(point)); let navigating = input.scroll != 0.0 || input.pinch != 1.0 || input.pan != egui::Vec2::ZERO @@ -2499,16 +3103,16 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { || app.cam_anim.is_some(); let hits = input .hover - .filter(|_| input.inside && !navigating) + .filter(|_| image_inside && !navigating && geometry_current) .map(|p| crate::viewport::pick_cached(app, &crate::viewport::projection(app, rect), p)) .unwrap_or_default(); let candidate = assign::candidate(app, &hits, input.mods); app.viewport.hover = candidate.as_ref().map(|(hit, _)| hit.clone()); - let assigning = assign::input(app, ui, &response, candidate.as_ref(), input.inside && !navigating); - if !assigning && input.inside && !navigating { + let assigning = assign::input(app, ui, &response, candidate.as_ref(), image_inside && !navigating && geometry_current); + if !assigning && image_inside && !navigating { assign::hover_tooltip(app, &response, candidate.as_ref()); } - if !assigning && response.clicked_by(egui::PointerButton::Primary) && input.inside && !navigating { + if !assigning && response.clicked_by(egui::PointerButton::Primary) && image_inside && !navigating && geometry_current { let (add, toggle) = crate::tool_modifiers::selection_click( crate::tool_modifiers::Held::from_modifiers(input.mods), app.preferences.selection_shift_add_only, @@ -2527,7 +3131,14 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { app.viewport.hover = None; } crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app)); - paint_product(app, ui, rect, app.cam, None); + if live::has_picture(app) { + live::paint(app, ui, rect); + if live::picking_current(app) { + paint_product_feedback(app, ui, rect, app.cam); + } + } else { + paint_product(app, ui, rect, app.cam, None); + } shot::overlay(app, ui, viewport); if !app.universal_panel_host_enabled() { crate::viewport::axis_view(app, ui, viewport); @@ -2546,17 +3157,26 @@ fn product_projection(camera: Camera, radius: f64, canvas: egui::Rect, image: Op } fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera: Camera, image: Option) { + paint_product_kind(app, ui, rect, camera, image, false); +} +fn paint_product_feedback(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera: Camera) { + paint_product_kind(app, ui, rect, camera, None, true); +} +fn paint_product_kind(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera: Camera, image: Option, feedback: bool) { let background = preview_background(app); - crate::gpu::paint_background(ui.painter(), rect, &background); + if !feedback { + crate::gpu::paint_background(ui.painter(), rect, &background); + } let result = (|| -> Result<(), String> { if app.viewport.gpu.is_none() { return Err(crate::i18n::tr("render.error_gpu_preview").into()); } let ppp = ui.ctx().pixels_per_point(); let setup = &app.render_workspace.view.draft; - if (app.render_workspace.view.method == ImageMethod::Raster && setup.exposure_ev != 0.0) - || setup.environment_rotation != 0.0 - || setup.environment_intensity != 1.0 + if !feedback + && ((app.render_workspace.view.method == ImageMethod::Raster && setup.exposure_ev != 0.0) + || setup.environment_rotation != 0.0 + || setup.environment_intensity != 1.0) { return Err(crate::i18n::tr("render.error_fixed_preview").into()); } @@ -2612,8 +3232,8 @@ fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera app.viewport.hl_key = highlight_key; } let slot = app.render_workspace.slot.clone(); - let callback = ViewportCallback(Frame { - product_lights: Some(light::preview(app)?), + let frame = Frame { + product_lights: if feedback { None } else { Some(light::preview(app)?) }, product: true, upload_error: Some(app.render_workspace.upload_error.clone()), key, @@ -2650,8 +3270,12 @@ fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera }, hatch: Default::default(), moving: None, - }); - crate::blur::viewport(ui.painter(), rect, callback, rect, [background.viewport_top, background.viewport_bottom]); + }; + if feedback { + ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, crate::gpu::ProductHighlightCallback(frame))); + } else { + crate::blur::viewport(ui.painter(), rect, ViewportCallback(frame), rect, [background.viewport_top, background.viewport_bottom]); + } Ok(()) })(); if let Err(error) = result { @@ -2661,6 +3285,23 @@ fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera /// Apply validated UI requests after the same registry call used by automation. pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Value) -> Result<(), String> { + if matches!(id, "render.result.view" | "render.result.close" | "render.result.select" | "render.result.discard" | "render.compare") { + app.render_workspace.displayed.clear(); + } + if matches!( + id, + "render.start" + | "render.batch" + | "render.result.regrade" + | "render.result.view" + | "render.result.close" + | "render.result.select" + | "render.result.discard" + | "render.result.pin" + | "render.compare" + ) { + app.render_workspace.view.auto_result_job = None; + } match id { "render.preflight.copy" => { app.render_workspace.clipboard_text = Some(reply["text"].as_str().ok_or("invalid check report")?.to_string()); @@ -2757,11 +3398,27 @@ pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Va /// `key` names the row's scenario handles (`ui_kit::progress_action`). pub(crate) fn progress_pill(app: &mut SolveApp, ui: &mut egui::Ui, key: &str) -> bool { + if prepare::progress(app, ui) { + return true; + } + if live::final_pending(app) { + crate::ui_kit::text(ui, app.tr("render.live.final_waiting"), crate::ui_kit::Text::Inline); + let cancel = crate::ui_kit::button(ui, app.tr("cmd.render_cancel"), crate::ui_kit::Button::Normal); + crate::scenario::publish_target("render:progress-cancel", cancel.rect); + if cancel.clicked() { + app.start("render.cancel"); + } + return true; + } if !ribbon::busy(app) { return false; } - let Some(job) = app.render_workspace.view.job else { return false }; - let Ok(status) = app.session.execute("render.status", &json!({"job":job})) else { return false }; + let Some(job) = app.render_workspace.view.job else { + return false; + }; + let Ok(status) = app.session.execute("render.status", &json!({"job":job})) else { + return false; + }; let phase = status["progress"]["phase"].as_str().unwrap_or("unknown"); if !matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling") { return false; diff --git a/crates/ui-egui/src/render_workspace_cpu.rs b/crates/ui-egui/src/render_workspace_cpu.rs index 35d9b7df9..c9ebe03c4 100644 --- a/crates/ui-egui/src/render_workspace_cpu.rs +++ b/crates/ui-egui/src/render_workspace_cpu.rs @@ -14,11 +14,23 @@ pub(super) fn validate_progressive_image(app: &SolveApp) -> Result<(), String> { // methods stop here, before the English refusals of the render and document crates. let (width, height) = (view.draft.width, view.draft.height); let size = (u64::from(width), u64::from(height)); + let camera_sampling = if view.method == super::ImageMethod::CpuRaytrace { + solidcraft_engine::render::job::cpu_camera_sampling(view.raytrace.progressive, view.studio.adaptive, view.raytrace.budget) + .map_err(|error| error.to_string())? + } else { + None + }; if width > 0 && height > 0 && image_limits(app).fit(size.0, size.1, None) != Some(size) { return Err(super::inspector::size_limit_reason(app, width, height)); } if view.method == super::ImageMethod::CpuRaytrace { - view.raytrace.budget.validate_image(width, height, view.raytrace.progressive).map_err(|error| error.to_string())?; + view.raytrace.budget.validate_image(width, height, camera_sampling).map_err(|error| error.to_string())?; + if view.studio.denoise { + solidcraft_engine::render::job::validate_cpu_denoise_image(width, height).map_err(|error| error.to_string())?; + } + if let Some(output) = super::studio::cpu_output(view) { + output.validate_image(width, height).map_err(|error| error.to_string())?; + } } Ok(()) } @@ -32,7 +44,14 @@ pub(super) fn image_limits(app: &SolveApp) -> solidcraft_engine::render::RenderL } let options = &app.render_workspace.view.raytrace; let mut limits = options.budget.image_limits(options.progressive.is_some()); - if let Some(progressive) = options.progressive { + if app.render_workspace.view.studio.denoise { + limits.max_dimension = limits.max_dimension.min(8192); + limits.max_pixels = limits.max_pixels.min(16_777_216); + } + let sampling = + solidcraft_engine::render::job::cpu_camera_sampling(options.progressive, app.render_workspace.view.studio.adaptive, options.budget) + .unwrap_or(options.progressive); + if let Some(progressive) = sampling { limits.max_pixels = limits.max_pixels.min(options.budget.limits().max_camera_samples / u64::from(progressive.samples_per_pixel.max(1))); } limits @@ -43,10 +62,25 @@ pub(super) fn image_limits(app: &SolveApp) -> solidcraft_engine::render::RenderL /// raster has no profiles of its own, so its hint also names CPU ray tracing. Neither the method /// nor the profile is switched here: they and the resolution change only when chosen. pub(super) fn profile_for_size(app: &SolveApp, width: u64, height: u64) -> Option { - if app.render_workspace.view.method == super::ImageMethod::GpuRaytrace || image_limits(app).fit(width, height, None) == Some((width, height)) { + if app.render_workspace.view.method == super::ImageMethod::GpuRaytrace { return None; } - CpuBudget::smallest_admitting(u32::try_from(width).ok()?, u32::try_from(height).ok()?, app.render_workspace.view.raytrace.progressive) + let view = &app.render_workspace.view; + if image_limits(app).fit(width, height, None) == Some((width, height)) + && solidcraft_engine::render::job::cpu_camera_sampling(view.raytrace.progressive, view.studio.adaptive, view.raytrace.budget).is_ok() + { + return None; + } + let width = u32::try_from(width).ok()?; + let height = u32::try_from(height).ok()?; + CpuBudget::ALL.into_iter().find(|budget| { + solidcraft_engine::render::job::cpu_camera_sampling( + app.render_workspace.view.raytrace.progressive, + app.render_workspace.view.studio.adaptive, + *budget, + ) + .is_ok_and(|sampling| budget.validate_image(width, height, sampling).is_ok()) + }) } /// The translated name of a profile, as the profile selector shows it. @@ -101,6 +135,7 @@ fn budget_controls(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::text(ui, ¬e, ui_kit::Text::Note("render.cpu_budget_help")); } fn set_progressive(app: &mut SolveApp, enabled: bool) { + app.render_workspace.view.cpu_sampling_initialized = true; let options = &mut app.render_workspace.view.raytrace; if enabled { options.progressive.get_or_insert_default(); @@ -114,33 +149,75 @@ fn set_progressive(app: &mut SolveApp, enabled: bool) { pub(super) fn progressive_controls(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { budget_controls(app, ui); let mut selected = usize::from(app.render_workspace.view.raytrace.progressive.is_some()); - let labels = [app.tr("render.children.single_image").to_string(), app.tr("render.cpu_progressive").to_string()]; + let legacy = app.preferences.render_legacy_image_defaults; + let mut changed = false; let response = ui.scope(|ui| { - ui_kit::row(ui, app.tr("render.children.sampling"), |ui| { - ui_kit::segmented( - ui, - &mut selected, - &labels.iter().map(String::as_str).collect::>(), - ui_kit::Segments { compact: true, targets: &["render:cpu-fixed", "render:cpu-progressive"], ..Default::default() }, - ) - }) + if legacy { + let labels = [app.tr("render.children.single_image").to_string(), app.tr("render.cpu_progressive").to_string()]; + ui_kit::row(ui, app.tr("render.children.sampling"), |ui| { + changed = ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { compact: true, targets: &["render:cpu-fixed", "render:cpu-progressive"], ..Default::default() }, + ); + }); + } else { + let key = if selected == 1 { "render.cpu_progressive_always" } else { "render.cpu_fixed_retained" }; + ui_kit::row(ui, app.tr("render.children.sampling"), |ui| { + ui_kit::text(ui, app.tr(key), ui_kit::Text::Inline); + }); + if selected == 0 { + let reason = progressive_adoption_reason(app); + let button = ui_kit::button(ui, app.tr("render.cpu_progressive_adopt"), ui_kit::Button::Enabled(reason.is_none())); + crate::scenario::publish_target("render:cpu-adopt-progressive", button.rect); + crate::scenario::publish_target("render:cpu-progressive", button.rect); + if button.clicked() { + selected = 1; + changed = true; + } + if let Some(reason) = reason { + ui_kit::text(ui, &reason, ui_kit::Text::Note("render.cpu_progressive_adopt_reason")); + } + ui_kit::text(ui, app.tr("render.cpu_progressive_adopt_help"), ui_kit::Text::Note("render.cpu_progressive_adopt_help")); + } + } }); crate::scenario::publish_target("render:cpu-sampling", response.response.rect); - if response.inner { + if changed { set_progressive(app, selected == 1); } + path_controls(app, ui); let enabled = app.render_workspace.view.raytrace.progressive.is_some(); let mut options = app.render_workspace.view.raytrace.progressive.unwrap_or_default(); if !enabled { ui_kit::text(ui, app.tr("render.children.progressive_reason"), ui_kit::Text::Note("render.children.progressive_reason")); } ui.add_enabled_ui(enabled, |ui| { - let response = - ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| ui_kit::number_field(ui, &mut options.samples_per_pixel, 1..=4096, 1.0, "")); + let maximum = app.render_workspace.view.raytrace.budget.limits().max_samples_per_pixel; + let range = app + .render_workspace + .view + .studio + .adaptive + .and_then(|adaptive| { + let minimum = adaptive.min_samples.max(16); + let cap = maximum.checked_sub(adaptive.pilot_samples)?; + (minimum <= cap).then_some(minimum..=cap) + }) + .unwrap_or(1..=maximum); + let response = ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| { + let field = ui_kit::number_field_preserving(ui, &mut options.samples_per_pixel, range, 1.0, ""); + crate::scenario::publish_target("render:cpu-spp-field", field.rect); + field + }); app.render_workspace.view.dirty |= response.changed(); crate::scenario::publish_target("render:cpu-spp", response.rect); - let response = - ui_kit::row(ui, app.tr("render.cpu_progressive_seed"), |ui| ui_kit::number_field(ui, &mut options.seed, 0..=u32::MAX, 1.0, "")); + let response = ui_kit::row(ui, app.tr("render.cpu_progressive_seed"), |ui| { + let field = ui_kit::number_field(ui, &mut options.seed, 0..=u32::MAX, 1.0, ""); + crate::scenario::publish_target("render:cpu-seed-field", field.rect); + field + }); app.render_workspace.view.dirty |= response.changed(); crate::scenario::publish_target("render:cpu-seed", response.rect); }); @@ -150,11 +227,68 @@ pub(super) fn progressive_controls(app: &mut SolveApp, ui: &mut egui::Ui) -> boo ui_kit::text(ui, app.tr("render.cpu_progressive_help"), ui_kit::Text::Note("render.cpu_progressive_help")); enabled } +/// Shared explicit adoption for Sampling and the CPU Glass transport entry point. +pub(super) fn progressive_adoption_reason(app: &SolveApp) -> Option { + let options = &app.render_workspace.view.raytrace; + if options.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty() && r.samples != 1) { + Some(app.tr("render.cpu_progressive_reflection_adopt").into()) + } else { + options + .budget + .validate_image(app.render_workspace.view.draft.width, app.render_workspace.view.draft.height, Some(Default::default())) + .err() + .map(|e| e.to_string()) + } +} +pub(super) fn adopt_progressive(app: &mut SolveApp) -> Result<(), String> { + if let Some(reason) = progressive_adoption_reason(app) { + return Err(reason); + } + set_progressive(app, true); + app.render_workspace.view.dirty = true; + Ok(()) +} +/// A prospective opt-in never changes old fixed sampling or removes optical bindings. +pub(super) fn path_reason(app: &SolveApp) -> Option { + if let Err(reason) = super::materials::path_compatibility(app) { + return Some(reason); + } + let mut options = app.render_workspace.view.raytrace.clone(); + options.path.get_or_insert_default(); + options.validate().err().map(|error| error.to_string()) +} +fn path_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut enabled = app.render_workspace.view.raytrace.path.is_some(); + let reason = path_reason(app); + let label = app.tr("render.cpu_path_lighting").to_string(); + let response = ui.add_enabled_ui(enabled || reason.is_none(), |ui| ui_kit::checkbox(ui, &label, &mut enabled)); + crate::scenario::publish_target("render:cpu-path", response.inner.rect); + if response.inner.changed() { + app.render_workspace.view.raytrace.path = enabled.then(solidcraft_engine::render::job::CpuPathOptions::default); + app.render_workspace.view.dirty = true; + } + if let Some(reason) = reason { + ui_kit::text(ui, &reason, ui_kit::Text::Note("render.cpu_path_reason")); + } + if let Some(mut path) = app.render_workspace.view.raytrace.path { + let label = app.tr("render.cpu_path_depth").to_string(); + let response = ui_kit::row(ui, &label, |ui| { + let field = ui_kit::number_field_preserving(ui, &mut path.max_depth, 1..=16, 1.0, ""); + crate::scenario::publish_target("render:cpu-path-depth", field.rect); + field + }); + app.render_workspace.view.dirty |= response.changed(); + app.render_workspace.view.raytrace.path = Some(path); + } + ui_kit::text(ui, app.tr("render.cpu_path_help"), ui_kit::Text::Note("render.cpu_path_help")); +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) enum Environment { #[default] None, Constant, + Sky, Hdr, } @@ -170,6 +304,7 @@ pub(super) struct View { pub intensity: f64, pub samples: u32, pub color: [f64; 3], + pub gradient: solidcraft_engine::render::lighting::environment::SkyGradient, pub checked: Option, bindings: std::collections::BTreeMap, } @@ -209,6 +344,7 @@ impl Default for View { intensity: 1.0, samples: 16, color: [1.0; 3], + gradient: Default::default(), checked: None, bindings: Default::default(), } @@ -292,7 +428,13 @@ pub(super) fn set_reflection(app: &mut SolveApp, name: &str, mode: Option Result<(), String> { if base.anisotropic_faces.iter().any(Option::is_some) || !base.dielectrics.is_empty() || base.environment.is_some() + || base.sky.is_some() + || (base.sun.is_some() && !app.render_workspace.view.studio.sun_enabled) + || (base.volume.is_some() && app.render_workspace.view.studio.volume.is_none()) || base.surface_effects.is_some() || base.emissions.is_some() { @@ -343,6 +488,16 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { } let view = &app.render_workspace.view.cpu; let mut options = base.clone(); + 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.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; + options.lens = app.render_workspace.view.studio.lens_enabled.then_some(app.render_workspace.view.studio.lens); + if let Some(lens) = options.lens { + lens.validate_camera(&app.cam).map_err(|error| error.to_string())?; + } if options.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) { return Err(crate::i18n::tr("render.error_area_samples").into()); } @@ -354,11 +509,21 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { // Runtime CPU requests keep the same single saved EV authority as typed jobs. params["settings"]["exposure_ev"] = json!(0.0); if view.environment != Environment::None { - if !view.intensity.is_finite() || !(0.0..=64.0).contains(&view.intensity) { - return Err(app.tr("render.cpu_environment_bounds").to_string()); + let maximum = if view.environment == Environment::Sky { 100.0 } else { 64.0 }; + if !view.intensity.is_finite() || !(0.0..=maximum).contains(&view.intensity) { + return Err(app + .tr(if view.environment == Environment::Sky { "render.cpu_sky_bounds" } else { "render.cpu_environment_bounds" }) + .to_string()); } match view.environment { Environment::Constant => options.environment = Some(RaytraceEnvironmentOptions { color: view.color, intensity: view.intensity }), + Environment::Sky => { + options.sky = Some(Box::new(solidcraft_engine::render::job::CpuSky { + gradient: view.gradient, + rotation_rad: view.rotation_rad, + intensity: view.intensity, + })); + } Environment::Hdr => { if !view.rotation_rad.is_finite() || view.rotation_rad.abs() > 1e6 || !matches!(view.samples, 1 | 4 | 16 | 64) { return Err(app.tr("render.cpu_environment_bounds").to_string()); @@ -492,6 +657,7 @@ pub(super) fn environment_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let key = match selected { Environment::None => "render.cpu_environment_none", Environment::Constant => "render.cpu_environment_constant", + Environment::Sky => "render.studio_sky", Environment::Hdr => "render.studio_hdr", }; let label = app.tr(key).to_string(); @@ -499,6 +665,7 @@ pub(super) fn environment_controls(app: &mut SolveApp, ui: &mut egui::Ui) { for (value, key) in [ (Environment::None, "render.cpu_environment_none"), (Environment::Constant, "render.cpu_environment_constant"), + (Environment::Sky, "render.studio_sky"), (Environment::Hdr, "render.studio_hdr"), ] { if ui_kit::list_picker(ui, key, app.tr(key), value == selected).clicked() { @@ -566,7 +733,9 @@ pub(super) fn record_checked(app: &mut SolveApp, params: &Value, reply: &Value) } fn metadata(app: &SolveApp, ui: &mut egui::Ui, info: &Value) { - let Some(hash) = info["source_sha256"].as_array().filter(|hash| hash.len() == 32) else { return }; + let Some(hash) = info["source_sha256"].as_array().filter(|hash| hash.len() == 32) else { + return; + }; let digest: Option> = hash.iter().map(|byte| byte.as_u64().and_then(|n| u8::try_from(n).ok())).collect(); let Some(digest) = digest else { return }; let digest: String = digest.into_iter().map(|byte| format!("{byte:02x}")).collect(); diff --git a/crates/ui-egui/src/render_workspace_displayed.rs b/crates/ui-egui/src/render_workspace_displayed.rs new file mode 100644 index 000000000..2d2b419a4 --- /dev/null +++ b/crates/ui-egui/src/render_workspace_displayed.rs @@ -0,0 +1,101 @@ +//! The last completed UI pass that submitted a Render image, not a presentation acknowledgement. +//! Fixed metadata only: the receipt owns no textures, pixels, handles, hashes or history. + +use egui::{Context, Painter, Rect}; +use serde::Serialize; +use solidcraft_engine::render::job::{FrameInfo, JobId, PreviewInfo, adaptive::AdaptivePreview}; + +use crate::SolveApp; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Kind { + Preview, + Final, + LivePreview, + LiveFinal, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub(super) struct Source { + pub job: JobId, + pub scene_generation: u64, + pub width: u32, + pub height: u32, + pub kind: Kind, + pub frame_sequence: Option, + /// Fixed sampling: completed SPP. Adaptive sampling: absolute complete iteration; + /// `adaptive` supplies the captured pilot/production interpretation. + pub samples_per_pixel: Option, + pub adaptive: Option, +} +impl Source { + pub(super) fn image(frame: &FrameInfo, preview: Option<&PreviewInfo>) -> Self { + Self { + job: frame.job, + scene_generation: frame.scene_generation, + width: frame.width, + height: frame.height, + kind: if preview.is_some() { Kind::Preview } else { Kind::Final }, + frame_sequence: preview.map(|info| info.frame_sequence), + samples_per_pixel: preview.map(|info| info.samples_per_pixel), + adaptive: preview.and_then(|info| info.adaptive), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub(super) struct Receipt { + #[serde(flatten)] + source: Source, + /// These identify the UI pass that issued the image shape. A logic-only update + /// does not refresh them. They do not acknowledge compositor/GPU presentation. + egui_frame_nr: u64, + egui_pass_nr: u64, +} + +#[derive(Default)] +pub(super) struct State { + candidate: Option, + completed: Option, +} +impl State { + pub(super) fn clear(&mut self) { + *self = Self::default(); + } + fn begin(&mut self) { + self.candidate = None; + } + pub(super) fn record(&mut self, painter: &Painter, image: Rect, source: Source) { + if !painter.is_visible() || painter.opacity() <= 0.0 || !image.is_finite() || !image.intersect(painter.clip_rect()).is_positive() { + return; + } + self.candidate = + Some(Receipt { source, egui_frame_nr: painter.ctx().cumulative_frame_nr(), egui_pass_nr: painter.ctx().cumulative_pass_nr() }); + } + fn finish(&mut self, ctx: &Context) { + // Layout may request a discard after the image was submitted. Keep the last + // completed pass until a non-discarded pass publishes its candidate (or None). + if !ctx.will_discard() { + self.completed = self.candidate; + } + self.candidate = None; + } +} + +pub(crate) fn begin(app: &mut SolveApp) { + app.render_workspace.displayed.begin(); +} + +pub(crate) fn finish(app: &mut SolveApp, ctx: &Context) { + app.render_workspace.displayed.finish(ctx); +} + +pub(super) fn inspect(app: &SolveApp) -> Option { + if !super::active(app) || app.home.open || super::comparison_active(app) { + return None; + } + let receipt = app.render_workspace.displayed.completed?; + let live = matches!(receipt.source.kind, Kind::LivePreview | Kind::LiveFinal); + (live != app.render_workspace.view.result).then_some(receipt) +} diff --git a/crates/ui-egui/src/render_workspace_effects.rs b/crates/ui-egui/src/render_workspace_effects.rs index 06851f0ad..a109f3863 100644 --- a/crates/ui-egui/src/render_workspace_effects.rs +++ b/crates/ui-egui/src/render_workspace_effects.rs @@ -75,8 +75,11 @@ pub(super) fn layer_actions(app: &SolveApp, ui: &mut egui::Ui, prefix: &str, sel } pub(super) fn presentation_controls(app: &mut SolveApp, ui: &mut egui::Ui) { - ui_kit::banner(ui, ui_kit::AssistantTone::Neutral, |ui| note(app, ui, "render.children.effects_banner")); - let enabled = app.render_workspace.view.method == ImageMethod::GpuRaytrace; + ui_kit::banner(ui, ui_kit::AssistantTone::Neutral, |ui| note(app, ui, "render.presentation_banner")); + let enabled = app.render_workspace.view.method != ImageMethod::Raster; + if app.render_workspace.view.method == ImageMethod::CpuRaytrace { + note(app, ui, "render.output_presentation_limits"); + } ui.add_enabled_ui(enabled, |ui| presentation_editor(app, ui)); } fn presentation_editor(app: &mut SolveApp, ui: &mut egui::Ui) { @@ -101,6 +104,15 @@ fn presentation_editor(app: &mut SolveApp, ui: &mut egui::Ui) { }); }); crate::scenario::publish_target("render:tone-map", response.response.rect); + let label = app.tr("render.studio_denoise").to_string(); + let response = ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.studio.denoise); + crate::scenario::publish_target("render:denoise-enable", response.rect); + if app.render_workspace.view.studio.denoise { + note(app, ui, "render.studio_denoise_help"); + if app.render_workspace.view.method == ImageMethod::CpuRaytrace { + note(app, ui, "render.cpu_denoise_help"); + } + } }); let mut editor = std::mem::take(&mut app.render_workspace.view.inspector.effects); let before = app.render_workspace.view.studio.finishing; @@ -241,6 +253,7 @@ fn presentation_editor(app: &mut SolveApp, ui: &mut egui::Ui) { /// Output edits save one numerical job patch; merely revealing Effects is read-only. /// Both the legacy page and the Browser child use this command-backed editor. pub(super) fn output_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let before_setup = setups::draft(app); let before = app.render_workspace.view.studio.clone(); let dirty = app.render_workspace.view.dirty; presentation_controls(app, ui); @@ -248,15 +261,10 @@ pub(super) fn output_controls(app: &mut SolveApp, ui: &mut egui::Ui) { if (before.finishing, before.tone_map, before.denoise, before.linear_exr) == (after.finishing, after.tone_map, after.denoise, after.linear_exr) { return; } - let result = setups::snapshot(app).and_then(|setup| { - let name = app.render_workspace.view.name.clone(); - app.run("render.settings.set", serde_json::json!({"name":name,"set":{"job":setup.job}})).map(|_| ()) - }); + let result = before_setup.and_then(|setup| setups::persist_editor(app, &setup)); if let Err(error) = result { app.render_workspace.view.studio = before; app.render_workspace.view.dirty = dirty; app.set_status(error, true); - } else { - app.render_workspace.view.dirty = true; } } diff --git a/crates/ui-egui/src/render_workspace_environment.rs b/crates/ui-egui/src/render_workspace_environment.rs index 7c1340258..f6dc41b47 100644 --- a/crates/ui-egui/src/render_workspace_environment.rs +++ b/crates/ui-egui/src/render_workspace_environment.rs @@ -284,7 +284,7 @@ pub(super) fn persist(app: &mut SolveApp) { _ => None, }); app.render_workspace.view.dirty = true; - if let Err(error) = setups::save(app) { + if let Err(error) = setups::save_numerical(app) { app.set_status(error, true); } // Keep the checked path available for rechecking; the engine has captured its bytes. @@ -317,16 +317,17 @@ fn source(app: &mut SolveApp, ui: &mut egui::Ui) { ImageMethod::CpuRaytrace => match app.render_workspace.view.cpu.environment { cpu::Environment::None => 0, cpu::Environment::Constant => 1, + cpu::Environment::Sky => 4, cpu::Environment::Hdr => 2, }, ImageMethod::Raster => 0, }; - let keys = if gpu { - ["render.environment.none", "render.studio_sky", "render.environment.hdr_file", "render.environment.builtin"] + let keys: &[&str] = if gpu { + &["render.environment.none", "render.studio_sky", "render.environment.hdr_file", "render.environment.builtin"] } else { - ["render.environment.none", "render.environment.constant", "render.environment.hdr", "render.environment.builtin"] + &["render.environment.none", "render.environment.constant", "render.environment.hdr", "render.environment.builtin", "render.studio_sky"] }; - if selected >= 2 && hdr::input(app, target).embedded() { + if matches!(selected, 2 | 3) && hdr::input(app, target).embedded() { let name = source_name(app, ui.ctx()); ui_kit::banner(ui, ui_kit::AssistantTone::Neutral, |ui| { ui_kit::text(ui, &name, ui_kit::Text::NameCell(true)); @@ -346,46 +347,53 @@ fn source(app: &mut SolveApp, ui: &mut egui::Ui) { } ui.add_enabled_ui(method != ImageMethod::Raster, |ui| { - ui_kit::dropdown_menu(ui, "render_environment_source_kind", app.tr(keys.get(selected).copied().unwrap_or(keys[0])), |ui| { - for (index, key) in keys.iter().enumerate().take(if gpu { 4 } else { 3 }) { - if ui_kit::list_picker(ui, key, app.tr(key), index == selected).clicked() { - if index == 3 { - open_sources(app); - } else if index != selected { - if gpu { - app.render_workspace.view.studio.environment = match index { - 1 => studio::Environment::Sky, - 2 => studio::Environment::Hdr, - _ => studio::Environment::None, - }; - if index == 2 { - app.render_workspace.view.studio.hdr = hdr::Input::Empty; - } - } else { - app.render_workspace.view.cpu.environment = match index { - 1 => cpu::Environment::Constant, - 2 => cpu::Environment::Hdr, - _ => cpu::Environment::None, - }; - if index == 0 { - app.render_workspace.view.raytrace.environment = None; + let picker = + ui_kit::dropdown_menu(ui, "render_environment_source_kind", app.tr(keys.get(selected).copied().unwrap_or(keys[0])), |ui| { + for (index, key) in keys.iter().enumerate() { + let allowed = gpu || index != 4 || app.render_workspace.view.raytrace.path.is_some(); + let item = ui.add_enabled_ui(allowed, |ui| ui_kit::list_picker(ui, key, app.tr(key), index == selected)).inner; + crate::scenario::publish_target(&format!("render:environment:source:{index}"), item.rect); + let item = if allowed { item } else { item.on_hover_text(app.tr("render.cpu_celestial_path_required")) }; + if item.clicked() { + if index == 3 { + open_sources(app); + } else if index != selected { + if gpu { + app.render_workspace.view.studio.environment = match index { + 1 => studio::Environment::Sky, + 2 => studio::Environment::Hdr, + _ => studio::Environment::None, + }; + if index == 2 { + app.render_workspace.view.studio.hdr = hdr::Input::Empty; + } + } else { + app.render_workspace.view.cpu.environment = match index { + 1 => cpu::Environment::Constant, + 2 => cpu::Environment::Hdr, + 4 => cpu::Environment::Sky, + _ => cpu::Environment::None, + }; + if index == 0 || index == 4 { + app.render_workspace.view.raytrace.environment = None; + } } + changed = true; } - changed = true; + ui.close(); } - ui.close(); } - } - }); + }); + crate::scenario::publish_target("render:environment:source", picker.rect); }); }); }); if method == ImageMethod::Raster { note(app, ui, "render.environment.source_raytrace"); } - if selected == 1 && gpu { + if (selected == 1 && gpu) || (!gpu && selected == 4) { for (key, index) in [("render.environment.zenith", 0), ("render.environment.horizon", 1), ("render.environment.sky_ground", 2)] { - let gradient = app.render_workspace.view.studio.gradient; + let gradient = if gpu { app.render_workspace.view.studio.gradient } else { app.render_workspace.view.cpu.gradient }; let mut value = match index { 0 => gradient.zenith, 1 => gradient.horizon, @@ -393,7 +401,7 @@ fn source(app: &mut SolveApp, ui: &mut egui::Ui) { } .map(f64::from); if ui_kit::row(ui, app.tr(key), |ui| ui_kit::linear_color_field(ui, &mut value, 1e6)).changed() { - let gradient = &mut app.render_workspace.view.studio.gradient; + let gradient = if gpu { &mut app.render_workspace.view.studio.gradient } else { &mut app.render_workspace.view.cpu.gradient }; let field = match index { 0 => &mut gradient.zenith, 1 => &mut gradient.horizon, @@ -410,7 +418,26 @@ fn source(app: &mut SolveApp, ui: &mut egui::Ui) { app.render_workspace.view.cpu.color = color; changed = true; } - } else if selected >= 2 { + if method == ImageMethod::CpuRaytrace && app.render_workspace.view.raytrace.path.is_none() { + note(app, ui, "render.cpu_constant_direct_help"); + let sampling = app.render_workspace.view.raytrace.progressive.unwrap_or_default(); + let detail = crate::i18n::format( + "render.cpu_constant_enable_indirect_plan", + &[ + ("depth", &solidcraft_engine::render::job::CpuPathOptions::default().max_depth.to_string()), + ("spp", &sampling.samples_per_pixel.to_string()), + ("seed", &sampling.seed.to_string()), + ], + ); + let action = ui_kit::button(ui, app.tr("render.cpu_volume_enable_path"), ui_kit::Button::Normal).on_hover_text(detail); + crate::scenario::publish_target("render:environment:enable-indirect", action.rect); + if action.clicked() + && let Err(error) = enable_indirect_lighting(app) + { + app.set_status(error, true); + } + } + } else if matches!(selected, 2 | 3) { let before = hdr::input(app, target).clone(); hdr::controls(app, ui, target); changed |= &before != hdr::input(app, target); @@ -491,9 +518,12 @@ fn environment_values(app: &SolveApp) -> Option<(f64, f64, f64, bool)> { ImageMethod::GpuRaytrace if v.studio.environment != studio::Environment::None => { Some((wrapped_degrees(v.studio.rotation_rad), v.studio.intensity, 100.0, true)) } - ImageMethod::CpuRaytrace if v.cpu.environment != cpu::Environment::None => { - Some((wrapped_degrees(v.cpu.rotation_rad), v.cpu.intensity, 64.0, v.cpu.environment == cpu::Environment::Hdr)) - } + ImageMethod::CpuRaytrace if v.cpu.environment != cpu::Environment::None => Some(( + wrapped_degrees(v.cpu.rotation_rad), + v.cpu.intensity, + if v.cpu.environment == cpu::Environment::Sky { 100.0 } else { 64.0 }, + v.cpu.environment != cpu::Environment::Constant, + )), _ => None, } } @@ -506,15 +536,24 @@ fn wrapped_degrees(radians: f64) -> f64 { pub(super) fn commit_environment(app: &mut SolveApp, mut request: Value) -> Result<(), String> { let fields = request.as_object_mut().ok_or_else(|| app.tr("render.env_invalid_edit").to_string())?; fields.insert("name".into(), json!(app.render_workspace.view.name)); - fields.insert("set".into(), json!(setups::snapshot(app)?)); + let mut setup = serde_json::to_value(setups::snapshot(app)?).map_err(|error| error.to_string())?; + if let Some(fields) = setup.as_object_mut() { + fields.remove("camera"); + } + fields.insert("set".into(), setup); app.run("render.environment.set", request)?; - setups::load(app); + setups::reload_numerical(app); Ok(()) } fn save(app: &mut SolveApp, setup: RenderSetup) -> Result<(), String> { - app.run("render.settings.set", json!({"name":app.render_workspace.view.name,"set":setup}))?; - setups::load(app); + // Numerical environment edits keep the shot's explicit Update camera policy. + let mut patch = serde_json::to_value(setup).map_err(|error| error.to_string())?; + if let Some(fields) = patch.as_object_mut() { + fields.remove("camera"); + } + app.run("render.settings.set", json!({"name":app.render_workspace.view.name,"set":patch}))?; + setups::reload_numerical(app); Ok(()) } @@ -527,7 +566,12 @@ pub(super) fn commit_backdrop(app: &mut SolveApp, color: [u8; 3], transparent: b *transparent_background = transparent; options.backdrop = None; } - _ if transparent => return Err(app.tr("render.cpu_opaque_required").into()), + Some(RenderJob::CpuRaytrace { options, transparent_background }) => { + *transparent_background = transparent; + if let Some(output) = &mut options.output { + output.backdrop = None; + } + } _ => {} } save(app, setup) @@ -570,10 +614,10 @@ fn backdrop(app: &mut SolveApp, ui: &mut egui::Ui) { use solidcraft_engine::render::job::finishing::BackdropMode; let title = app.tr("render.env_backdrop").to_string(); ui_kit::section(ui, "render_environment_backdrop", &title, true, |ui| { - let gpu = app.render_workspace.view.method == ImageMethod::GpuRaytrace; + let raytrace = app.render_workspace.view.method != ImageMethod::Raster; let mut mode = if app.render_workspace.view.transparent { 3 - } else if app.render_workspace.view.studio.backdrop_enabled && gpu { + } else if app.render_workspace.view.studio.backdrop_enabled && raytrace { 2 } else { 1 @@ -584,13 +628,13 @@ fn backdrop(app: &mut SolveApp, ui: &mut egui::Ui) { &mut mode, &[app.tr("render.environment.world"), app.tr("render.env_colour"), app.tr("render.environment.gradient"), app.tr("render.env_clear")], ui_kit::Segments { - enabled: &[false, true, gpu && !app.render_workspace.view.transparent, app.render_workspace.view.method != ImageMethod::CpuRaytrace], + enabled: &[false, true, raytrace && !app.render_workspace.view.transparent, true], targets: &["render:environment:world", "render:environment:colour", "render:environment:gradient", "render:environment:clear"], ..Default::default() }, ); - if mode == 2 && !gpu { - app.set_status(app.tr("render.environment.needs_gpu").to_string(), true); + if mode == 2 && !raytrace { + app.set_status(app.tr("render.output_raytrace_only").to_string(), true); mode = before_mode; } if mode != before_mode { @@ -617,10 +661,10 @@ fn backdrop(app: &mut SolveApp, ui: &mut egui::Ui) { app.set_status(error, true); } } - if mode == 2 || !gpu { + if mode == 2 || !raytrace { let mut gradient = app.render_workspace.view.studio.backdrop; let mut changed = false; - ui.add_enabled_ui(gpu && !app.render_workspace.view.transparent, |ui| { + ui.add_enabled_ui(raytrace && !app.render_workspace.view.transparent, |ui| { let mut mode = match gradient.mode { BackdropMode::Vertical => 0, BackdropMode::Horizontal => 1, @@ -679,11 +723,8 @@ fn backdrop(app: &mut SolveApp, ui: &mut egui::Ui) { note(app, ui, "render.environment.blur_pending"); note(app, ui, "render.environment.backdrop_note"); note(app, ui, "render.environment.world_pending"); - if !gpu { - note(app, ui, "render.environment.gradient_gpu"); - } - if app.render_workspace.view.method == ImageMethod::CpuRaytrace { - note(app, ui, "render.cpu_opaque_required"); + if !raytrace { + note(app, ui, "render.output_raytrace_only"); } }); } @@ -696,7 +737,10 @@ pub(super) fn commit_gradient( let mut setup = setups::snapshot(app)?; match &mut setup.job { Some(RenderJob::GpuPath { options, .. }) => options.backdrop = enabled.then_some(gradient), - _ => return Err(app.tr("render.environment.needs_gpu").into()), + Some(RenderJob::CpuRaytrace { options, .. }) => { + options.output.get_or_insert_with(Box::default).backdrop = enabled.then_some(gradient); + } + _ => return Err(app.tr("render.output_raytrace_only").into()), } save(app, setup) } @@ -889,43 +933,220 @@ fn vector_row(ui: &mut egui::Ui, label: &str, value: &mut [f64; 3], range: std:: }) } -/// One home for airborne controls, also used by the transitional Aging page. +/// Full prospective validation, shared by visible controls and method adoption. +pub(super) fn validate_atmosphere(app: &SolveApp) -> Result<(), String> { + validate_volume_value(app, app.render_workspace.view.studio.volume) +} + +fn validate_volume_value(app: &SolveApp, value: Option) -> Result<(), String> { + let view = &app.render_workspace.view; + let Some(volume) = value else { return Ok(()) }; + volume.validate().map_err(|error| error.to_string())?; + if view.method == ImageMethod::Raster { + return Err(app.tr("render.output_raytrace_only").into()); + } + if !volume.active() { + return Ok(()); + } + if view.method == ImageMethod::CpuRaytrace && view.raytrace.path.is_none() { + return Err(app.tr("render.cpu_volume_path_required").into()); + } + if view.studio.denoise { + return Err(app.tr("render.volume_denoise_required").into()); + } + if !view.draft.optics.is_empty() + || (view.method == ImageMethod::CpuRaytrace && !view.raytrace.dielectrics.is_empty()) + || (view.materials.enabled && view.materials.bindings.iter().any(|binding| binding.enabled && binding.glass_enabled)) + { + return Err(app.tr("render.volume_glass_required").into()); + } + if view.method == ImageMethod::GpuRaytrace { + if view.studio.transmission_samples != 1 { + return Err(app.tr("render.volume_single_stratum_required").into()); + } + if !view.studio.lighting_enabled && view.studio.environment == studio::Environment::None { + return Err(app.tr("render.volume_lighting_required").into()); + } + volume.relative_bounds([app.cam.target.x, app.cam.target.y, app.cam.target.z]).map_err(|error| error.to_string())?; + } + Ok(()) +} + +/// Change only the volume intent through one non-camera numerical transaction. +/// Corrective removal never needs an invalid previous volume to validate. +pub(super) fn commit_atmosphere(app: &mut SolveApp, volume: Option) -> Result<(), String> { + if app.render_workspace.view.method == ImageMethod::Raster { + return Err(app.tr("render.output_raytrace_only").into()); + } + if setups::has_unportable_bindings(app) { + return Err(app.tr("render.setup_runtime_unsupported").into()); + } + let before = setups::draft(app)?; + let source = Arc::downgrade(&app.session.doc.render); + let rig = super::light::rows(app)?; + let previous = app.render_workspace.view.clone(); + app.render_workspace.view.studio.volume = volume; + let result = validate_atmosphere(app).and_then(|()| setups::persist_editor(app, &before)); + if let Err(error) = result { + app.render_workspace.view = previous; + return Err(error); + } + super::light::volume_edited(app, &source, previous.method, &before, &rig); + Ok(()) +} + +/// Explicit, camera-neutral adoption shared by constant environment and Atmosphere. +/// Every authored field is retained unless this action names its transport change. +pub(super) fn enable_indirect_lighting(app: &mut SolveApp) -> Result<(), String> { + if app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return Err(app.tr("render.cpu_indirect_method_required").into()); + } + if setups::has_unportable_bindings(app) { + return Err(app.tr("render.setup_runtime_unsupported").into()); + } + let before = setups::draft(app)?; + let source = Arc::downgrade(&app.session.doc.render); + let rig = super::light::rows(app)?; + let previous = app.render_workspace.view.clone(); + let options = &mut app.render_workspace.view.raytrace; + options.path.get_or_insert_default(); + options.progressive.get_or_insert_default(); + options.primary_samples = 1; + options.shadows = true; + app.render_workspace.view.cpu_sampling_initialized = true; + let result = super::materials::path_compatibility(app) + .and_then(|()| cpu::validate_progressive_image(app)) + .and_then(|()| validate_atmosphere(app)) + // Pure full authored intent: includes lens/camera, legacy environment, + // resources and the selected image/profile without IO or source capture. + .and_then(|()| setups::snapshot(app).map(|_| ())) + .and_then(|()| setups::persist_editor(app, &before)); + if let Err(error) = result { + app.render_workspace.view = previous; + return Err(error); + } + super::light::volume_edited(app, &source, previous.method, &before, &rig); + Ok(()) +} + +fn volume_vector_row( + app: &SolveApp, + ui: &mut egui::Ui, + key: &str, + id: &str, + current: [f64; 3], + range: std::ops::RangeInclusive, + speed: f64, +) -> Option<[f64; 3]> { + let mut value = current; + let mut changed = false; + ui_kit::row(ui, app.tr(key), |ui| { + ui.columns(3, |columns| { + for (index, (ui, component)) in columns.iter_mut().zip(current).enumerate() { + let width = ui.available_width().max(0.0); + ui.spacing_mut().text_edit_width = width; + ui.spacing_mut().interact_size.x = width; + ui.set_clip_rect(ui.clip_rect().intersect(ui.max_rect())); + if let Some(edited) = edit(app, ui, &format!("volume-{id}-{index}"), component, |ui, value| { + let response = ui_kit::number_field_preserving(ui, value, range.clone(), speed, ""); + crate::scenario::publish_target(&format!("render:volume:{id}:{index}"), response.rect); + response + }) { + value[index] = edited; + changed = true; + } + } + }); + }); + changed.then_some(value) +} + +/// One common authoring surface; CPU/GPU preserve the same world-mm box intent. pub(super) fn atmosphere(app: &mut SolveApp, ui: &mut egui::Ui) { let title = app.tr("render.environment.atmosphere").to_string(); - ui_kit::section_method(ui, "render_environment_atmosphere", &title, true, "GPU", |ui| { - let gpu = app.render_workspace.view.method == ImageMethod::GpuRaytrace; + ui_kit::section_method(ui, "render_environment_atmosphere", &title, true, "CPU / GPU", |ui| { + let method = app.render_workspace.view.method; let before = app.render_workspace.view.studio.volume; let mut volume = before.unwrap_or_default(); let mut enabled = before.is_some(); let mut changed = false; - ui.add_enabled_ui(gpu, |ui| { - let toggle = ui_kit::checkbox(ui, app.tr("render.environment.medium"), &mut enabled); + let cpu = method == ImageMethod::CpuRaytrace; + let path = app.render_workspace.view.raytrace.path.is_some(); + let prospective_reason = if before.is_none() { validate_volume_value(app, Some(volume)).err() } else { None }; + let supported = method == ImageMethod::GpuRaytrace || (cpu && (path || before.is_some())); + ui.add_enabled_ui(supported, |ui| { + let toggle = ui + .add_enabled_ui(before.is_some() || prospective_reason.is_none(), |ui| { + ui_kit::checkbox(ui, app.tr("render.environment.medium"), &mut enabled) + }) + .inner; + let toggle = if let Some(reason) = &prospective_reason { toggle.on_disabled_hover_text(reason) } else { toggle }; crate::scenario::publish_target("render:volume-enable", toggle.rect); changed |= toggle.changed(); ui.add_enabled_ui(enabled, |ui| { - changed |= vector_row(ui, app.tr("render.environment.min"), &mut volume.min_mm, -1e9..=1e9, 1.0, ""); - changed |= vector_row(ui, app.tr("render.environment.max"), &mut volume.max_mm, -1e9..=1e9, 1.0, ""); - changed |= ui_kit::row(ui, app.tr("render.environment.extinction"), |ui| { - ui_kit::number_field(ui, &mut volume.extinction_per_mm, 0.0..=1000.0, 0.0001, " /mm") - }) - .changed(); - changed |= vector_row(ui, app.tr("render.environment.albedo"), &mut volume.scattering_albedo, 0.0..=1.0, 0.01, ""); - changed |= ui_kit::row(ui, app.tr("render.environment.phase"), |ui| { - ui_kit::slider(ui, &mut volume.anisotropy, -0.95..=0.95, Default::default()) - }) - .changed(); + if let Some(value) = volume_vector_row(app, ui, "render.environment.min", "min", volume.min_mm, -1e9..=1e9, 1.0) { + volume.min_mm = value; + changed = true; + } + if let Some(value) = volume_vector_row(app, ui, "render.environment.max", "max", volume.max_mm, -1e9..=1e9, 1.0) { + volume.max_mm = value; + changed = true; + } + if let Some(value) = edit(app, ui, "volume-extinction", volume.extinction_per_mm, |ui, value| { + ui_kit::row(ui, app.tr("render.environment.extinction"), |ui| { + let response = ui_kit::number_field_preserving(ui, value, 0.0..=1000.0, 0.0001, " /mm"); + crate::scenario::publish_target("render:volume:extinction", response.rect); + response + }) + }) { + volume.extinction_per_mm = value; + changed = true; + } + if let Some(value) = volume_vector_row(app, ui, "render.environment.albedo", "albedo", volume.scattering_albedo, 0.0..=1.0, 0.01) { + volume.scattering_albedo = value; + changed = true; + } + if let Some(value) = edit(app, ui, "volume-anisotropy", volume.anisotropy, |ui, value| { + ui_kit::row(ui, app.tr("render.environment.phase"), |ui| { + let response = ui_kit::number_field_preserving(ui, value, -0.95..=0.95, 0.01, ""); + crate::scenario::publish_target("render:volume:anisotropy", response.rect); + response + }) + }) { + volume.anisotropy = value; + changed = true; + } }); }); - if !gpu { - note(app, ui, "render.environment.needs_gpu"); + if method == ImageMethod::Raster { + note(app, ui, "render.output_raytrace_only"); } - if changed { - app.render_workspace.view.studio.volume = enabled.then_some(volume); - app.render_workspace.view.dirty = true; - if let Err(error) = setups::save(app) { - app.render_workspace.view.studio.volume = before; - app.set_status(error, true); + if cpu { + note(app, ui, "render.cpu_volume_help"); + if !path { + let sampling = app.render_workspace.view.raytrace.progressive.unwrap_or_default(); + let detail = crate::i18n::format( + "render.cpu_volume_enable_path_plan", + &[ + ("depth", &solidcraft_engine::render::job::CpuPathOptions::default().max_depth.to_string()), + ("spp", &sampling.samples_per_pixel.to_string()), + ("seed", &sampling.seed.to_string()), + ], + ); + let action = ui_kit::button(ui, app.tr("render.cpu_volume_enable_path"), ui_kit::Button::Normal).on_hover_text(detail); + crate::scenario::publish_target("render:volume-enable-path", action.rect); + if action.clicked() + && let Err(error) = enable_indirect_lighting(app) + { + app.set_status(error, true); + } } } + if let Some(reason) = prospective_reason.or_else(|| validate_atmosphere(app).err()) { + ui_kit::text(ui, &reason, ui_kit::Text::Note("render:volume:reason")); + } + if changed && let Err(error) = commit_atmosphere(app, enabled.then_some(volume)) { + app.set_status(error, true); + } }); } diff --git a/crates/ui-egui/src/render_workspace_inspector_tests.rs b/crates/ui-egui/src/render_workspace_inspector_tests.rs index 4d2a54d46..114f067d7 100644 --- a/crates/ui-egui/src/render_workspace_inspector_tests.rs +++ b/crates/ui-egui/src/render_workspace_inspector_tests.rs @@ -147,7 +147,8 @@ fn render_workspace_scene_overview_selection_order_links_and_readiness_are_read_ for id in ["open-check", "check", "render", "all-shots"] { assert!(crate::scenario::rect_of(&format!("render:scene:{id}")).is_some()); } - assert!(crate::scenario::rect_of("dialog:note:render.scene_batch_reason").is_some()); + assert!(crate::scenario::rect_of("dialog:note:render.batch_current_settings_help").is_some()); + assert!(super::super::ribbon::action_ready(&h.app, "render.batch").is_ok()); h.step(&json!({"click":{"handle":"render:scene:frame"}})).unwrap(); assert!(matches!(h.app.render_workspace.view.selection, super::super::RenderSelection::Shot(_))); assert_eq!(selected_editor(&h.app), Editor::Camera); @@ -169,6 +170,7 @@ fn render_workspace_scene_overview_selection_order_links_and_readiness_are_read_ #[test] fn render_workspace_shot_e7_order_disabled_reasons_output_link_and_confirm_remove() { let mut h = fixture(); + super::super::select_image_method(&mut h.app, ImageMethod::Raster); h.call("ui.resize", json!({"width":1600,"height":1800})); setups::save(&mut h.app).unwrap(); let name = h.app.render_workspace.view.name.clone(); @@ -183,7 +185,7 @@ fn render_workspace_shot_e7_order_disabled_reasons_output_link_and_confirm_remov assert!(inspector.contains_rect(header)); assert!(h.widget(&name).is_some(), "selected Shot names the inspector"); ordered_sections(&["render.page_camera", "render.shot_lens", "render.shot_exposure_section", "render.stage_frame"], &h.app); - for key in ["render.shot_lens_gpu_reason", "render.shot_exposure_reason", "render.shot_selection_reason"] { + for key in ["render.shot_lens_raytrace_reason", "render.shot_exposure_reason", "render.shot_selection_reason"] { assert!(crate::scenario::rect_of(&format!("dialog:note:{key}")).is_some(), "{key}"); } for id in ["name", "update", "revert", "duplicate", "remove", "output", "distance", "look-selection"] { @@ -360,10 +362,11 @@ fn numerical_editor_saves_before_switch_and_keeps_navigation_camera_explicit() { } #[test] -fn shot_switch_confirms_transient_inputs_and_current_shot_focus_preserves_them() { +fn legacy_shot_switch_confirms_transient_inputs_and_current_shot_focus_preserves_them() { use solidcraft_engine::render::job::ReflectionMode; for kind in ["glass", "maps", "cpu", "camera"] { let mut h = fixture(); + h.app.preferences.render_legacy_image_defaults = true; h.app.render_workspace.view.name = "A".into(); super::super::select_image_method(&mut h.app, if kind == "cpu" { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }); setups::save(&mut h.app).unwrap(); @@ -408,6 +411,7 @@ fn shot_switch_confirms_transient_inputs_and_current_shot_focus_preserves_them() h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); assert_eq!(h.app.render_workspace.view.name, "B"); assert_eq!(h.app.render_workspace.view.draft.width, 321); + assert_eq!(h.app.cam, camera, "legacy shot activation keeps the navigation camera after discarding {kind}"); assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); } @@ -1214,46 +1218,48 @@ fn public_render_inspection_exposes_exact_identities_without_execution_or_docume #[test] fn aging_tab_adds_reorders_disables_and_persists_layers_without_engineering_edits() { use solidcraft_engine::render::job::aging::AgingKind; - let mut h = fixture(); - super::super::select_image_method(&mut h.app, ImageMethod::GpuRaytrace); - let before = h.app.session.doc.to_json(); - h.app.start("render.aging.describe"); - h.frames(3); - assert_eq!(selected_editor(&h.app), Editor::Wear); - assert!(!crate::icon_svg::resolve(solidcraft_engine::find_command("render.aging.describe").unwrap().icon).placeholder); - for code in [1, 3] { - h.step(&json!({"click":{"handle":"render:aging-add"}})).unwrap(); + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = fixture(); + super::super::select_image_method(&mut h.app, method); + let before = h.app.session.doc.to_json(); + h.app.start("render.aging.describe"); + h.frames(3); + assert_eq!(selected_editor(&h.app), Editor::Wear); + assert!(!crate::icon_svg::resolve(solidcraft_engine::find_command("render.aging.describe").unwrap().icon).placeholder); + for code in [1, 3] { + h.step(&json!({"click":{"handle":"render:aging-add"}})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"handle":format!("dialog:list:aging-add-{code}")}})).unwrap(); + h.frames(2); + } + assert_eq!(h.app.render_workspace.view.studio.aging.len(), 2); + assert_eq!(h.app.render_workspace.view.studio.aging.get(1).unwrap().kind, AgingKind::Dust); + h.step(&json!({"click":{"handle":"render:aging-up"}})).unwrap(); h.frames(2); - h.step(&json!({"click":{"handle":format!("dialog:list:aging-add-{code}")}})).unwrap(); + assert_eq!(h.app.render_workspace.view.studio.aging.get(0).unwrap().kind, AgingKind::Dust); + h.step(&json!({"click":{"handle":"render:aging-enabled"}})).unwrap(); h.frames(2); + assert!(!h.app.render_workspace.view.studio.aging.get(0).unwrap().enabled); + assert_ne!(h.app.session.doc.to_json(), before, "Wear saves its stack through render.settings.set"); + assert_eq!(setups::snapshot(&h.app).unwrap().job, h.app.session.doc.render.setups[&h.app.render_workspace.view.name].job); + let targets = super::super::materials::read_targets(&mut h.app).unwrap(); + let identity = targets.iter().find(|target| target.name == "Subject").unwrap().stable_target.clone().unwrap(); + h.app.render_workspace.view.studio.aging.get_mut(0).unwrap().target = Some(identity.clone()); + let expected = setups::snapshot(&h.app).unwrap(); + let wire = serde_json::to_value(&expected).unwrap(); + assert_eq!(wire["job"]["options"]["aging"][0]["target"]["definition"], "Subject"); + assert!(wire["job"]["options"]["aging"][0]["target"].get("body_index").is_none()); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.studio.aging = Default::default(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups[&h.app.render_workspace.view.name], expected); + assert_eq!(h.app.render_workspace.view.studio.aging.get(0).unwrap().target.as_ref(), Some(&identity)); + h.step(&json!({"click":{"handle":"render:aging-remove"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.studio.aging.len(), 1); } - assert_eq!(h.app.render_workspace.view.studio.aging.len(), 2); - assert_eq!(h.app.render_workspace.view.studio.aging.get(1).unwrap().kind, AgingKind::Dust); - h.step(&json!({"click":{"handle":"render:aging-up"}})).unwrap(); - h.frames(2); - assert_eq!(h.app.render_workspace.view.studio.aging.get(0).unwrap().kind, AgingKind::Dust); - h.step(&json!({"click":{"handle":"render:aging-enabled"}})).unwrap(); - h.frames(2); - assert!(!h.app.render_workspace.view.studio.aging.get(0).unwrap().enabled); - assert_ne!(h.app.session.doc.to_json(), before, "Wear saves its stack through render.settings.set"); - assert_eq!(setups::snapshot(&h.app).unwrap().job, h.app.session.doc.render.setups[&h.app.render_workspace.view.name].job); - let targets = super::super::materials::read_targets(&mut h.app).unwrap(); - let identity = targets.iter().find(|target| target.name == "Subject").unwrap().stable_target.clone().unwrap(); - h.app.render_workspace.view.studio.aging.get_mut(0).unwrap().target = Some(identity.clone()); - let expected = setups::snapshot(&h.app).unwrap(); - let wire = serde_json::to_value(&expected).unwrap(); - assert_eq!(wire["job"]["options"]["aging"][0]["target"]["definition"], "Subject"); - assert!(wire["job"]["options"]["aging"][0]["target"].get("body_index").is_none()); - setups::save(&mut h.app).unwrap(); - h.app.render_workspace.view.studio.aging = Default::default(); - setups::load(&mut h.app); - assert_eq!(setups::snapshot(&h.app).unwrap(), expected); - let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); - assert_eq!(reopened.render.setups[&h.app.render_workspace.view.name], expected); - assert_eq!(h.app.render_workspace.view.studio.aging.get(0).unwrap().target.as_ref(), Some(&identity)); - h.step(&json!({"click":{"handle":"render:aging-remove"}})).unwrap(); - h.frames(2); - assert_eq!(h.app.render_workspace.view.studio.aging.len(), 1); } #[test] @@ -1372,9 +1378,9 @@ fn wear_selection_shows_disabled_controls_with_reason_and_never_changes_method() assert!(crate::scenario::rect_of("render:aging-enabled").is_some()); assert!(crate::scenario::rect_of("render:aging-target").is_some()); assert!(crate::scenario::rect_of("render:page:aging").is_none(), "Wear has no master page switcher"); - assert!(h.shapes.iter().any(|s| text_color(&s.shape, h.app.tr("render.effects_gpu_only")).is_some())); + assert!(h.shapes.iter().any(|s| text_color(&s.shape, h.app.tr("render.aging_raytrace_help")).is_some())); colours.push(h.shapes.iter().find_map(|s| text_color(&s.shape, h.app.tr("render.wear_layers"))).unwrap()); - if method != ImageMethod::GpuRaytrace { + if method == ImageMethod::Raster { for handle in ["render:aging-add", "render:aging-enabled", "render:aging-layer:0:enabled", "render:aging-remove"] { h.step(&json!({"click":{"handle":handle}})).unwrap(); assert_eq!(h.app.render_workspace.view.studio.aging, stack); @@ -1382,9 +1388,8 @@ fn wear_selection_shows_disabled_controls_with_reason_and_never_changes_method() } assert_eq!(h.app.session.doc.to_json(), document); } - for colour in &colours[..2] { - assert!(colour.a() < colours[2].a(), "unsupported methods fade the editor"); - } + assert!(colours[0].a() < colours[1].a(), "Raster keeps the unsupported editor visibly disabled"); + assert_eq!(colours[1], colours[2], "both raytracers expose the same aging editor"); h.step(&json!({"click":{"handle":"render:aging-layer:0:enabled"}})).unwrap(); assert!(!h.app.render_workspace.view.studio.aging.get(0).unwrap().enabled); h.app.start("render.aging.describe"); @@ -1738,6 +1743,8 @@ fn cpu_raster_refusing_a_size_names_the_method_and_profile_that_render_it() { fn a_size_the_cpu_profile_refuses_names_the_profile_that_renders_it() { use solidcraft_engine::render::job::CpuBudget; let mut h = fixture(); + // This checks fixed CPU image limits; progressive has its separate camera-sample bound. + h.app.preferences.render_legacy_image_defaults = true; super::super::select_image_method(&mut h.app, ImageMethod::CpuRaytrace); h.frames(3); h.step(&json!({"click":{"handle":"render:shots:size"}})).unwrap(); @@ -2483,6 +2490,32 @@ fn appearance_editor_e2_sections_are_ordered_collapsed_and_expand_for_each_metho for title in titles.into_iter().skip(1) { h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr(title))}})).unwrap(); } + fn painted_reason(shape: &egui::Shape, expected: &str, scope: egui::Rect, clip: egui::Rect) -> bool { + match shape { + egui::Shape::Text(text) if text.galley.text() == expected => { + let rect = text.galley.rect.translate(text.pos.to_vec2()); + rect.is_positive() && !text.galley.elided && scope.contains_rect(rect) && clip.contains_rect(rect) + } + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| painted_reason(shape, expected, scope, clip)), + _ => false, + } + } + let glass_has_reason = |h: &Harness, key: &str| { + let glass = crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass"))).unwrap(); + let coat = crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr("render.appearance_editor.coat"))).unwrap(); + let scope = egui::Rect::from_min_max(egui::pos2(glass.left(), glass.bottom()), egui::pos2(glass.right(), coat.top())); + let expected = h.app.tr(key); + let accessible = h.output.accesskit_update.as_ref().unwrap().nodes.iter().any(|(_, node)| { + node.role() == egui::accesskit::Role::Label + && node.value() == Some(expected) + && node.bounds().is_some_and(|bounds| { + bounds.x1 > bounds.x0 && bounds.y1 > bounds.y0 && bounds.y0 >= f64::from(glass.bottom()) && bounds.y1 <= f64::from(coat.top()) + }) + }); + let painted = h.shapes.iter().any(|shape| painted_reason(&shape.shape, expected, scope, shape.clip_rect.intersect(h.ctx.content_rect()))); + assert_eq!(accessible, painted, "{key}: Glass note metadata and clipped paint disagree in {scope:?}"); + accessible && painted + }; for method in [ImageMethod::Raster, ImageMethod::GpuRaytrace, ImageMethod::CpuRaytrace] { h.app.render_workspace.view.method = method; h.frames(3); @@ -2491,7 +2524,6 @@ fn appearance_editor_e2_sections_are_ordered_collapsed_and_expand_for_each_metho "render.appearance_editor.recipe", "render.appearance_editor.boundary", "render.appearance_editor.thickness", - "render.appearance_editor.absorption", "render.material_shadow", "render.subsurface_enable", "render.material_coat_enable", @@ -2517,9 +2549,17 @@ fn appearance_editor_e2_sections_are_ordered_collapsed_and_expand_for_each_metho ] { assert!(h.widget(h.app.tr(key)).is_some(), "expanded E2 is missing {key} for {method:?}"); } + let absorption = h.app.tr("render.appearance_editor.absorption"); + for (axis, channel) in ["R", "G", "B"].into_iter().enumerate() { + assert!(h.widget(&format!("{absorption} {channel}")).is_some(), "expanded E2 is missing absorption{channel} for {method:?}"); + assert!(crate::scenario::rect_of(&format!("dialog:vector:{absorption}:{axis}")).is_some(), "absorption{channel} keeps its vector handle"); + } let tree = h.output.accesskit_update.as_ref().unwrap(); let glass = tree.nodes.iter().find(|(_, n)| n.label() == Some(h.app.tr("render.appearance_editor.glass_enable"))).unwrap(); - assert_eq!(glass.1.is_disabled(), method != ImageMethod::GpuRaytrace); + assert_eq!(glass.1.is_disabled(), method == ImageMethod::Raster); + assert_eq!(glass_has_reason(&h, "render.material_raytrace_required"), method == ImageMethod::Raster); + assert!(!glass_has_reason(&h, "render.appearance_editor.gpu_reason"), "Glass is shared by CPU and GPU; Maps keeps its own GPU reason"); + assert!(!glass_has_reason(&h, "render.appearance_editor.body_reason")); assert_eq!(h.app.session.doc.to_json(), before); assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "opening never installs temporary bindings"); } @@ -2534,6 +2574,7 @@ fn appearance_editor_e2_sections_are_ordered_collapsed_and_expand_for_each_metho } h.frames(3); assert!(h.widget(h.app.tr("render.appearance_editor.body_reason")).is_some()); + assert!(glass_has_reason(&h, "render.appearance_editor.body_reason"), "unsupported selections retain the whole-body reason for Glass"); for title in titles.into_iter().skip(1) { assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(title))).is_some()); } @@ -2751,7 +2792,7 @@ fn output_children_unsupported_controls_stay_visible_with_reason_and_cannot_edit assert_eq!(h.app.render_workspace.view.studio.adaptive, before.adaptive); h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); h.frames(3); - assert!(h.shapes.iter().any(|s| has_text(&s.shape, h.app.tr("render.children.effects_banner")))); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, h.app.tr("render.presentation_banner")))); let point = reveal_inspector_target(&mut h, "render:bloom-enable").center(); h.step(&json!({"click":[point.x,point.y]})).unwrap(); assert_eq!(h.app.render_workspace.view.studio.finishing, before.finishing); @@ -2832,6 +2873,1491 @@ fn output_children_check_diagnostics_are_collapsed_and_copy_the_current_request( assert_eq!(selected_editor(&h.app), Editor::Camera); } +// U10: reversible canonical budgets and separately acknowledged library specifications. +mod quality_button_contract { + use super::*; + + fn gpu_fixture() -> Harness { + let mut h = fixture(); + super::super::super::select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.cam.fov = 0.6; + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.frames(3); + h + } + + #[test] + fn quality_buttons_apply_all_three_actual_catalog_budgets_as_one_numerical_edit() { + for (index, id, width, height, samples, depth, denoise) in + [(0, "Q-001", 960, 540, 64, 4, false), (1, "Q-002", 1600, 900, 512, 8, true), (2, "Q-003", 2560, 1440, 2048, 12, true)] + { + let mut h = gpu_fixture(); + let before = setups::snapshot(&h.app).unwrap(); + let history = (h.app.session.revision, h.app.session.undo.len()); + let plan = h.app.run("render.quality.prepare", json!({"id":id,"variant":"fixed_samples_png","acknowledge_omissions":true})).unwrap(); + assert_eq!(plan["id"], id); + assert_eq!(plan["status"], "fixed_budget_projection_not_full_quality_profile"); + assert_eq!(plan["settings"], json!({"width":width,"height":height})); + assert_eq!(plan["gpu_options"], json!({"samples":samples,"max_depth":depth,"seed":21026,"denoise":denoise})); + assert!(plan["omitted"].as_array().unwrap().iter().any(|v| v == "convergence_certification")); + choose_quality(&mut h.app, index).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), (history.0 + 1, history.1 + 1)); + let mut after = setups::snapshot(&h.app).unwrap(); + assert_eq!((after.width, after.height), (width, height)); + let solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options, .. } = after.job.as_mut().unwrap() else { + panic!("GPU budget must keep its method") + }; + assert_eq!((options.samples, options.max_depth, options.seed, options.denoise), (samples, depth, 21026, denoise)); + // Normalise only the advertised fields: every other authored setting must survive. + let solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options: old, .. } = before.job.as_ref().unwrap() else { + panic!("GPU fixture") + }; + (options.samples, options.max_depth, options.seed, options.denoise) = (old.samples, old.max_depth, old.seed, old.denoise); + (after.width, after.height) = (before.width, before.height); + assert_eq!(after, before); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + } + } + + #[test] + fn quality_button_pointer_click_saves_one_current_shot_action_without_a_dialog() { + let mut h = gpu_fixture(); + h.app.render_workspace.view.studio.intensity = 0.42; + h.app.render_workspace.view.draft.exposure_ev = 1.23; + h.app.render_workspace.view.studio.ambient = [0.11, 0.22, 0.33]; + let camera = h.app.cam; + let shot = h.app.render_workspace.view.name.clone(); + let stage = h.app.render_workspace.view.stage; + let history = (h.app.session.revision, h.app.session.undo.len()); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:quality:balanced"}})).unwrap(); + h.frames(3); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert_eq!(h.app.session.revision, history.0 + 1); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1600, 900)); + assert_eq!((h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed), (512, 8, 21026)); + assert!(h.app.render_workspace.view.studio.denoise); + assert_eq!(h.app.render_workspace.view.name, shot); + assert_eq!(h.app.render_workspace.view.stage, stage); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.studio.intensity, 0.42); + assert_eq!(h.app.render_workspace.view.studio.ambient, [0.11, 0.22, 0.33]); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 1.23); + assert_eq!(h.app.session.doc.render.setups[&shot].width, 1600); + assert_eq!(quality_selection(&h.app), 1); + let summary = quality_summary(&h.app, 1600, 900, 512, 8, 21026, true); + assert!(h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == summary))); + assert!(crate::scenario::rect_of("render:review:acknowledge").is_none()); + assert!(h.app.render_workspace.view.job.is_none(), "choosing quality never starts a renderer"); + } + + #[test] + fn quality_highlight_derives_every_projected_field_and_returns_to_custom() { + let mut h = gpu_fixture(); + for index in 0..3 { + let plan = h + .app + .run( + "render.quality.prepare", + json!({"id":(["Q-001","Q-002","Q-003"][index]),"variant":"fixed_samples_png","acknowledge_omissions":true}), + ) + .unwrap(); + apply_quality(&mut h.app, &plan).unwrap(); + assert_eq!(quality_selection(&h.app), index); + for field in 0..6 { + let original = ( + h.app.render_workspace.view.draft.width, + h.app.render_workspace.view.draft.height, + h.app.render_workspace.view.samples, + h.app.render_workspace.view.max_depth, + h.app.render_workspace.view.seed, + h.app.render_workspace.view.studio.denoise, + ); + match field { + 0 => h.app.render_workspace.view.draft.width += 1, + 1 => h.app.render_workspace.view.draft.height += 1, + 2 => h.app.render_workspace.view.samples += 1, + 3 => h.app.render_workspace.view.max_depth += 1, + 4 => h.app.render_workspace.view.seed += 1, + _ => h.app.render_workspace.view.studio.denoise = !original.5, + } + assert_eq!(quality_selection(&h.app), 3, "changed projected field {field}"); + ( + h.app.render_workspace.view.draft.width, + h.app.render_workspace.view.draft.height, + h.app.render_workspace.view.samples, + h.app.render_workspace.view.max_depth, + h.app.render_workspace.view.seed, + h.app.render_workspace.view.studio.denoise, + ) = original; + } + h.app.render_workspace.view.draft.exposure_ev = 0.37; + assert_eq!(quality_selection(&h.app), index, "highlight describes the budget, not a complete scene-quality tier"); + } + } + + #[test] + fn quality_buttons_refuse_other_methods_and_invalid_choices_without_mutation() { + let mut h = gpu_fixture(); + for method in [ImageMethod::CpuRaytrace, ImageMethod::Raster] { + h.app.render_workspace.view.method = method; + h.app.render_workspace.view.raytrace.progressive = None; + let before = format!("{:?}", h.app.render_workspace.view.draft); + let doc = h.app.session.doc.to_json(); + for index in 0..3 { + assert!(choose_quality(&mut h.app, index).is_err()); + assert!(quality_reason(&h.app, index).is_some()); + } + assert_eq!(quality_selection(&h.app), 3); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(format!("{:?}", h.app.render_workspace.view.draft), before); + assert_eq!(h.app.session.doc.to_json(), doc); + assert!(h.app.render_workspace.view.library.review.is_none()); + } + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + assert!(choose_quality(&mut h.app, usize::MAX).is_err()); + assert!(h.app.render_workspace.view.library.review.is_none()); + } + + #[test] + fn imported_quality_review_stays_bound_to_captured_draft_shot_method_and_document() { + for change in 0..5 { + let mut h = gpu_fixture(); + library::review::quality(&mut h.app, "Q-001").unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:review:acknowledge"}})).unwrap(); + match change { + 0 => h.app.render_workspace.view.draft.width = 333, + 1 => h.app.render_workspace.view.name = "Different shot".into(), + 2 => h.app.render_workspace.view.method = ImageMethod::CpuRaytrace, + 3 => h.app.session.doc = Arc::new((*h.app.session.doc).clone()), + _ => h.app.cam.yaw += 0.25, + } + let doc = h.app.session.doc.to_json(); + let width = h.app.render_workspace.view.draft.width; + let history = (h.app.session.revision, h.app.session.undo.len()); + h.frames(3); + assert!(crate::scenario::rect_of("dialog:report:review:stale").is_some()); + let ok = crate::scenario::rect_of("dialog:ok").unwrap().center(); + h.step(&json!({"click":[ok.x,ok.y]})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), doc); + assert_eq!(h.app.render_workspace.view.draft.width, width); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len())); + assert!(h.app.render_workspace.view.library.review.is_some()); + } + } + + #[test] + fn canonical_quality_click_ignores_cached_comparison_plans() { + let mut h = gpu_fixture(); + prepare_quality_choices(&mut h.app); + let cache = h.app.render_workspace.view.inspector.quality_plans.as_mut().unwrap(); + let forged = cache[0].as_mut().unwrap(); + forged["settings"] = json!({"width":777,"height":333}); + forged["gpu_options"] = json!({"samples":7,"max_depth":2,"seed":999,"denoise":true}); + choose_quality(&mut h.app, 0).unwrap(); + let view = &h.app.render_workspace.view; + assert_eq!( + (view.draft.width, view.draft.height, view.samples, view.max_depth, view.seed, view.studio.denoise), + (960, 540, 64, 4, 21026, false) + ); + assert!(view.library.review.is_none()); + assert!(view.job.is_none()); + } + + #[test] + fn quality_custom_keeps_existing_sampling_navigation_on_all_methods() { + let mut h = gpu_fixture(); + for method in [ImageMethod::GpuRaytrace, ImageMethod::CpuRaytrace, ImageMethod::Raster] { + h.app.render_workspace.view.method = method; + let doc = h.app.session.doc.to_json(); + choose_quality(&mut h.app, 3).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, super::super::super::RenderSelection::Sampling); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.session.doc.to_json(), doc); + } + } + + #[test] + fn quality_button_repaint_and_imported_review_cancel_preserve_unsaved_draft_and_design() { + let mut h = gpu_fixture(); + h.app.render_workspace.view.draft.width = 777; + h.app.render_workspace.view.samples = 99; + let draft = serde_json::to_value(setups::snapshot(&h.app).unwrap()).unwrap(); + let doc = h.app.session.doc.to_json(); + let history = (h.app.session.revision, h.app.session.undo.len()); + h.frames(3); + assert_eq!(quality_selection(&h.app), 3); + library::review::quality(&mut h.app, "Q-003").unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert_eq!(serde_json::to_value(setups::snapshot(&h.app).unwrap()).unwrap(), draft); + assert_eq!(h.app.session.doc.to_json(), doc); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len())); + } + + #[test] + fn quality_budget_apply_preserves_saved_camera_navigation_and_one_step_undo() { + let mut h = gpu_fixture(); + setups::save(&mut h.app).unwrap(); + let shot = h.app.render_workspace.view.name.clone(); + let saved = h.app.session.doc.render.setups[&shot].clone(); + h.app.cancel_view_animation(); + h.app.cam.yaw += 0.4; + h.app.cam.distance *= 1.3; + h.frames(3); + let navigation = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len()); + choose_quality(&mut h.app, 1).unwrap(); + h.frames(3); + assert!(h.app.render_workspace.view.library.review.is_none()); + let updated = &h.app.session.doc.render.setups[&shot]; + assert_eq!(updated.camera, saved.camera, "a sample budget is not an Update shot action"); + assert_eq!((updated.width, updated.height), (1600, 900)); + assert_eq!(h.app.cam, navigation); + assert!(h.app.render_workspace.view.dirty, "the explicit camera draft remains unsaved"); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), (history.0 + 1, history.1 + 1)); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups[&shot], saved); + assert_eq!(h.app.cam, navigation); + } + + #[test] + fn incompatible_quality_budget_restores_the_entire_valid_draft_and_saved_baseline() { + use solidcraft_engine::render::job::adaptive::AdaptiveSampling; + let mut h = gpu_fixture(); + h.app.render_workspace.view.samples = 512; + h.app.render_workspace.view.studio.adaptive = Some(AdaptiveSampling { min_samples: 128, ..Default::default() }); + setups::save(&mut h.app).unwrap(); + h.frames(3); + let before = setups::snapshot(&h.app).unwrap(); + let clean = h.app.render_workspace.view.clean_setup.clone(); + let dirty = h.app.render_workspace.view.dirty; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let error = choose_quality(&mut h.app, 0).unwrap_err(); + assert!(error.contains("adaptive")); + assert_eq!(setups::snapshot(&h.app).unwrap(), before, "Draft64 must refuse an authored minimum128 without rewriting it"); + assert_eq!(h.app.render_workspace.view.clean_setup, clean); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert_eq!(h.app.render_workspace.view.samples, 512); + assert_eq!(h.app.render_workspace.view.studio.adaptive.unwrap().min_samples, 128); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn explicit_shot_thumbnail_restores_saved_cameras_and_keeps_dirty_current_shot_confirmation() { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.render_workspace.view.name = "A".into(); + let saved_a = solidcraft_engine::render::Camera { fov: 0.6, distance: 123.0, yaw: 0.7, roll: 0.2, ..h.app.cam }; + apply_camera_draft(&mut h.app, saved_a).unwrap(); + setups::save(&mut h.app).unwrap(); + let saved_b = solidcraft_engine::render::Camera { fov: 0.8, distance: 170.0, yaw: -0.2, up: solidcraft_engine::render::UpAxis::Y, ..saved_a }; + h.app.run("render.settings.set", json!({"name":"B","set":{"camera":saved_b,"width":321,"job":{"method":"gpu_path"}}})).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let navigated = solidcraft_engine::render::Camera { yaw: saved_a.yaw + 0.25, ..saved_a }; + apply_camera_draft(&mut h.app, navigated).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"shot","id":"A"})).unwrap(); + assert_eq!(h.app.cam, navigated, "programmatic editor focus stays distinct from shot activation"); + h.step(&json!({"click":{"handle":"render:shots:setup:A"}})).unwrap(); + assert!(confirmation_open(&h.app)); + assert_eq!(h.app.cam, navigated); + h.step(&json!({"widget":h.app.tr("render.keep_editing")})).unwrap(); + assert_eq!(h.app.cam, navigated); + h.step(&json!({"click":{"handle":"render:shots:setup:A"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + assert_eq!(h.app.cam, saved_a, "even the already-active thumbnail can restore its complete saved camera"); + assert!(!h.app.render_workspace.view.dirty); + assert!(!confirmation_open(&h.app)); + + // Focusing an already-restored camera cannot erase a separate numeric draft. + h.app.render_workspace.view.draft.width = 777; + h.frames(2); + h.step(&json!({"click":{"handle":"render:shots:setup:A"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.draft.width, 777); + assert!(!confirmation_open(&h.app)); + setups::load(&mut h.app); + h.frames(2); + h.step(&json!({"click":{"handle":"render:shots:setup:B"}})).unwrap(); + assert_eq!(h.app.cam, saved_b); + assert_eq!(h.app.ui.up_axis, saved_b.up); + assert!(h.app.ui.perspective); + assert_eq!(h.app.render_workspace.view.name, "B"); + assert_eq!(h.app.render_workspace.view.draft.width, 321); + assert!(!h.app.render_workspace.view.dirty); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn saved_numeric_reload_and_undo_do_not_activate_a_shot_camera() { + let mut h = fixture(); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + setups::save(&mut h.app).unwrap(); + let name = h.app.render_workspace.view.name.clone(); + let saved = h.app.session.doc.render.setups[&name].clone(); + let navigation = solidcraft_engine::render::Camera { yaw: h.app.cam.yaw + 0.4, distance: h.app.cam.distance * 1.2, ..h.app.cam }; + apply_camera_draft(&mut h.app, navigation).unwrap(); + let before = setups::draft(&h.app).unwrap(); + h.app.render_workspace.view.draft.width = 513; + setups::persist_editor(&mut h.app, &before).unwrap(); + assert_eq!(h.app.cam, navigation); + assert_eq!(h.app.session.doc.render.setups[&name].camera, saved.camera); + setups::load(&mut h.app); + assert_eq!(h.app.cam, navigation); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.cam, navigation); + assert_eq!(h.app.session.doc.render.setups[&name], saved); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn physical_tree_shot_activation_pairs_saved_cpu_lens_with_its_perspective_camera() { + use solidcraft_engine::render::job::ThinLens; + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, ImageMethod::Raster); + h.app.render_workspace.view.name = "A".into(); + apply_camera_draft(&mut h.app, solidcraft_engine::render::Camera::default()).unwrap(); + setups::save(&mut h.app).unwrap(); + let camera = solidcraft_engine::render::Camera { fov: 35f64.to_radians(), distance: 168.6, ..h.app.cam }; + let lens = ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 168.6 }; + h.app + .run( + "render.settings.set", + json!({"name":"Lens","set":{"width":8,"height":8,"camera":camera, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81},"lens":lens}}}}), + ) + .unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + h.frames(3); + assert_eq!(h.app.cam.fov, 0.0); + h.step(&json!({"click":{"handle":"render:tree:shot:Lens"}})).unwrap(); + h.frames(2); + assert!(!confirmation_open(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Lens"); + assert_eq!(h.app.cam, camera); + assert!(h.app.ui.perspective); + assert_eq!(h.app.render_workspace.view.studio.lens, lens); + assert!(h.app.render_workspace.view.studio.lens_enabled); + assert_eq!(setups::snapshot(&h.app).unwrap(), document.render.setups["Lens"]); + assert_eq!(super::super::image_request(&h.app).unwrap()["settings"]["camera"], json!(camera)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn explicit_revert_and_restore_clean_only_the_saved_camera_and_keep_real_numeric_and_runtime_edits() { + use solidcraft_engine::render::job::ReflectionMode; + for through_shot in [false, true] { + for kind in ["clean", "numeric", "runtime"] { + let mut h = fixture(); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "A".into(); + let camera = solidcraft_engine::render::Camera { fov: 0.6, distance: 168.6, ..h.app.cam }; + apply_camera_draft(&mut h.app, camera).unwrap(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{"job":{"method":"raster"}}})).unwrap(); + // The observed cold failure loads numeric intent against an ortho camera, + // making that transient camera the old clean baseline before Revert. + h.app.cam.fov = 0.0; + h.app.cam.yaw += 0.2; + setups::load(&mut h.app); + if kind == "numeric" { + h.app.render_workspace.view.draft.width = 777; + } else if kind == "runtime" { + super::super::cpu::set_reflection(&mut h.app, "Subject", Some(ReflectionMode::Mirror)).unwrap(); + } + let width = h.app.render_workspace.view.draft.width; + let reflections = h.app.render_workspace.view.raytrace.reflections.clone(); + let mut clean = h.app.render_workspace.view.clean_setup.clone().unwrap(); + clean.camera = camera; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + if through_shot { + super::super::shot::revert(&mut h.app, "A").unwrap(); + } else { + restore_camera(&mut h.app).unwrap(); + } + assert_eq!(h.app.cam, camera); + assert!(h.app.ui.perspective); + assert_eq!(h.app.render_workspace.view.clean_setup.as_ref(), Some(&clean)); + assert_eq!(h.app.render_workspace.view.draft.width, width); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, reflections); + assert_eq!(h.app.render_workspace.view.dirty, kind != "clean", "{through_shot}/{kind}"); + assert_eq!(setups::has_runtime_inputs(&h.app), kind == "runtime"); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + switch_shot(&mut h.app, "B".into()); + assert_eq!(confirmation_open(&h.app), kind != "clean", "{through_shot}/{kind}: only real edits require confirmation after Revert"); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } + } +} + +#[test] +fn scene_all_shots_readiness_uses_saved_shot_and_limit_reasons_without_starting_on_paint() { + let mut h = fixture(); + h.app.render_workspace.view.live_paused = true; + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + super::super::select_image_method(&mut h.app, ImageMethod::Raster); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + h.frames(3); + assert!(h.app.session.doc.render.setups.is_empty()); + assert!(h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == h.app.tr("render.batch_empty")))); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + h.step(&json!({"click":{"handle":"render:scene:all-shots"}})).unwrap(); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert_eq!(host.admitted_bytes(), 0); + 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(); + h.frames(3); + assert!(super::super::ribbon::action_ready(&h.app, "render.batch").is_ok()); + assert!(crate::scenario::rect_of("dialog:note:render:batch:reason").is_none()); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + for index in 0..31 { + h.app.run("render.settings.set", json!({"name":format!("Shot {index:02}"),"set":{"width":8,"height":8,"job":{"method":"raster"}}})).unwrap(); + } + assert_eq!(h.app.session.doc.render.setups.len(), 32); + h.app.session.doc.render.validate().unwrap(); + h.frames(3); + assert!(super::super::ribbon::action_ready(&h.app, "render.batch").is_ok()); + assert!(crate::scenario::rect_of("dialog:note:render:batch:reason").is_none()); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert_eq!(host.admitted_bytes(), 0); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let error = h.app.run("render.settings.set", json!({"name":"Hostile extra","set":{"width":8,"height":8,"job":{"method":"raster"}}})).unwrap_err(); + assert!(error.contains("maximum 32")); + 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); + // The public API refuses a 33rd row. Inject a hostile cloned document to + // exercise the defensive paint/button guard without weakening that API cap. + let mut hostile = (*document).clone(); + let extra = hostile.render.setups.values().next().unwrap().clone(); + assert!(Arc::make_mut(&mut hostile.render).setups.insert("Hostile extra".into(), extra).is_none()); + assert!(hostile.render.validate().is_err()); + h.app.session.doc = Arc::new(hostile); + let document = h.app.session.doc.clone(); + h.frames(3); + assert_eq!(h.app.session.doc.render.setups.len(), 33); + assert_eq!(super::super::ribbon::action_ready(&h.app, "render.batch").unwrap_err(), h.app.tr("render.batch_limit")); + assert!(h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == h.app.tr("render.batch_limit")))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert_eq!(host.admitted_bytes(), 0); + h.step(&json!({"click":{"handle":"render:scene:all-shots"}})).unwrap(); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert_eq!(host.admitted_bytes(), 0); + 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); +} + +#[test] +fn composed_cpu_environment_and_output_alpha_edits_preserve_gi_filter_and_master_flags() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::CpuPathOptions; + let mut h = fixture(); + h.call("ui.resize", json!({"width":1440,"height":1600})); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.path = Some(CpuPathOptions { max_depth: 3 }); + h.app.render_workspace.view.studio.denoise = true; + h.app.render_workspace.view.studio.linear_exr = true; + setups::save(&mut h.app).unwrap(); + let name = h.app.render_workspace.view.name.clone(); + let camera = h.app.cam; + let model = h.app.session.model.state(); + let undo = h.app.session.undo.len(); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("dialog:note:render.cpu_opaque_required").is_none()); + assert!(crate::scenario::rect_of("dialog:note:render.cpu_opaque_hint").is_none()); + reveal_inspector_target(&mut h, "render:environment:clear"); + h.step(&json!({"click":{"handle":"render:environment:clear"}})).unwrap(); + h.frames(2); + let RenderJob::CpuRaytrace { options, transparent_background } = h.app.session.doc.render.setups[&name].job.as_ref().unwrap() else { + panic!("CPU job") + }; + assert!(*transparent_background); + assert!(options.denoise && options.output.as_ref().unwrap().linear_exr); + assert_eq!(options.path, Some(CpuPathOptions { max_depth: 3 })); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.frames(3); + reveal_inspector_target(&mut h, "render:transparent-background"); + h.step(&json!({"click":{"handle":"render:transparent-background"}})).unwrap(); + h.frames(2); + let RenderJob::CpuRaytrace { options, transparent_background } = h.app.session.doc.render.setups[&name].job.as_ref().unwrap() else { + panic!("CPU job") + }; + assert!(!*transparent_background); + assert!(options.denoise && options.output.as_ref().unwrap().linear_exr); + assert_eq!(options.path, Some(CpuPathOptions { max_depth: 3 })); + assert_eq!(h.app.session.undo.len(), undo + 2); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.render.setups[&name].camera, camera); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert!(h.app.render_workspace.view.job.is_none()); +} + +mod cpu_quality_button_contract { + use super::*; + use solidcraft_engine::doc::render_settings::{RenderJob, RenderSetup}; + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions, adaptive::AdaptiveSampling}; + + fn cpu_fixture(indirect: bool) -> Harness { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + h.app.render_workspace.view.live_paused = true; + h.app.session.set_render_job_host(None).unwrap(); + h.app.cancel_view_animation(); + h.app.cam.fov = 0.6; + let mut options = json!({"budget":"compact","progressive":{"samples_per_pixel":8,"seed":91}, + "shadows":false,"lights":[],"denoise":true,"lens":{"aperture_radius_mm":0.1,"focus_distance_mm":100.0}, + "output":{"tone_map":"aces_fitted","linear_exr":true,"finishing":{"rgb_gain":[1.2,0.8,1.1], + "photographic":{"grain":0.03,"seed":42},"bloom":{"strength":0.2,"threshold":0.5,"radius":1}}}}); + if indirect { + options["budget"] = json!("workstation"); + options["progressive"] = json!({"samples_per_pixel":48,"seed":91}); + options["adaptive"] = json!({"pilot_samples":16,"min_samples":16,"relative_error":0.15,"absolute_error":0.01,"coverage_error":0.02}); + options["path"] = json!({"max_depth":5}); + options["shadows"] = json!(true); + // CPU alpha admits pointwise presentation and its spatial noise filter, + // while bloom/photographic finishing requires the separate opaque case. + options["output"]["finishing"] = json!({"rgb_gain":[1.2,0.8,1.1]}); + } + h.app + .run( + "render.settings.set", + json!({"name":"CPU costs","set":{"width":64,"height":32,"camera":h.app.cam,"exposure_ev":1.25, + "job":{"method":"cpu_raytrace","transparent_background":indirect,"options":options}}}), + ) + .unwrap(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":"CPU costs","replace_environment":true})).unwrap(); + if !indirect { + h.app + .run( + "render.optics.bind", + json!({"name":"CPU costs","body_index":0,"body_name":"Subject","expected_revision":h.app.session.revision, + "optics":{"boundary":"thin_sheet","thickness_mm":0.8,"ior":1.51,"absorption_per_mm":[0.1,0.2,0.0],"shadow_transmission":false}}), + ) + .unwrap(); + } + h.app.render_workspace.view.name = "CPU costs".into(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(h.app.render_workspace.view.library.review.is_none()); + h + } + + fn expected_budget(mut setup: RenderSetup, width: u32, height: u32, samples: u32, budget: CpuBudget) -> RenderSetup { + (setup.width, setup.height) = (width, height); + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job else { panic!("CPU method") }; + options.progressive = Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 21026 }); + options.budget = budget; + setup + } + + #[test] + fn cpu_quality_actual_chips_change_only_five_budgets_preserve_authored_optics_and_reopen_with_one_undo() { + for (handle, width, height, samples, budget) in + [("draft", 960, 540, 16, CpuBudget::Compact), ("balanced", 1600, 900, 32, CpuBudget::Studio), ("high", 2560, 1440, 64, CpuBudget::Studio)] + { + let mut h = cpu_fixture(false); + let before = h.app.session.doc.render.setups["CPU costs"].clone(); + assert_eq!(before.optics.len(), 1, "the preservation fixture includes actual bound glass"); + let Some(RenderJob::CpuRaytrace { options, transparent_background, .. }) = &before.job else { panic!("CPU") }; + assert!(!*transparent_background && options.denoise && options.lens.is_some() && options.hdr.is_some()); + assert!(options.output.as_ref().unwrap().linear_exr); + let presentation = json!(options.output); + assert_eq!(presentation["finishing"]["bloom"]["strength"], json!(0.2)); + assert_eq!(presentation["finishing"]["photographic"]["grain"], json!(0.03)); + h.app.cancel_view_animation(); + h.app.cam.yaw += 0.3; + let navigation = h.app.cam; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len()); + h.frames(3); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "revealing the presets never saves a draft"); + h.step(&json!({"click":{"handle":format!("render:quality:{handle}")}})).unwrap(); + h.frames(3); + let expected = expected_budget(before.clone(), width, height, samples, budget); + assert_eq!( + h.app.session.doc.render.setups["CPU costs"], expected, + "only width/height/production cap/seed/profile may change; HDR, optical binding, lens, alpha, filter and output intent survive" + ); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), (history.0 + 1, history.1 + 1)); + assert_eq!(h.app.cam, navigation); + assert!(h.app.render_workspace.view.dirty, "the unrelated navigated camera remains an explicit unsaved draft"); + let mut displayed = expected.clone(); + displayed.camera = navigation; + assert_eq!(setups::snapshot(&h.app).unwrap(), displayed); + assert_eq!( + quality_selection(&h.app), + match handle { + "draft" => 0, + "balanced" => 1, + _ => 2, + } + ); + let summary = cpu_quality_summary(&h.app, width, height, samples, 21026, budget); + assert!(h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == summary))); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert!(crate::scenario::rect_of("render:review:acknowledge").is_none()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["CPU costs"], before); + assert_eq!(h.app.cam, navigation); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["CPU costs"], expected); + let bytes = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&bytes).unwrap(); + assert_eq!(reopened.render.setups["CPU costs"], expected); + h.app.session = solidcraft_engine::Session::new(reopened); + crate::render_workspace::reset_document(&mut h.app); + h.app.render_workspace.view.name = "CPU costs".into(); + h.app.render_workspace.view.live_paused = true; + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), displayed); + } + } + + #[test] + fn cpu_quality_keeps_larger_profile_adaptive_policy_and_indirect_depth_without_enabling_other_transport() { + let mut h = cpu_fixture(true); + let before = h.app.session.doc.render.setups["CPU costs"].clone(); + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:quality:draft"}})).unwrap(); + h.frames(3); + let expected = expected_budget(before.clone(), 960, 540, 16, CpuBudget::Workstation); + assert_eq!(h.app.session.doc.render.setups["CPU costs"], expected); + let Some(RenderJob::CpuRaytrace { options, transparent_background, .. }) = &expected.job else { panic!("CPU") }; + assert!(*transparent_background && options.shadows); + let presentation = json!(options.output); + assert!(presentation["finishing"]["bloom"].is_null() && presentation["finishing"]["photographic"].is_null()); + assert_eq!(options.path.unwrap().max_depth, 5); + assert_eq!(options.adaptive.unwrap().min_samples, 16); + assert_eq!(options.adaptive.unwrap().pilot_samples, 16); + assert!(options.denoise); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(h.app.render_workspace.view.job.is_none()); + let bytes = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + assert_eq!(solidcraft_engine::io::read_design(&bytes).unwrap().render.setups["CPU costs"], expected); + } + + #[test] + fn cpu_quality_fixed_paint_then_explicit_adopt_refreshes_enabled_chips_without_changing_other_context() { + let mut h = cpu_fixture(false); + let mut fixed = h.app.session.doc.render.setups["CPU costs"].clone(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut fixed.job else { panic!("CPU") }; + options.progressive = None; + options.lens = None; + h.app.run("render.settings.set", json!({"name":"CPU costs","set":fixed})).unwrap(); + setups::load(&mut h.app); + h.frames(3); // Paint and cache the fixed-only refusal before explicit adoption. + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert!(quality_reason(&h.app, 0).unwrap().contains(h.app.tr("render.cpu_quality_progressive_required"))); + h.step(&json!({"click":{"handle":"render:quality:draft"}})).unwrap(); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len())); + if crate::scenario::rect_of("render:cpu-adopt-progressive").is_none() { + h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr("render.children.cpu"))}})).unwrap(); + } + h.frames(3); + let adopt = reveal_inspector_target(&mut h, "render:cpu-adopt-progressive"); + h.step(&json!({"click":[adopt.center().x,adopt.center().y]})).unwrap(); + h.frames(3); + assert!(h.app.render_workspace.view.raytrace.progressive.is_some()); + assert_eq!(h.app.render_workspace.view.raytrace.budget, CpuBudget::Compact); + assert!(h.app.render_workspace.view.studio.adaptive.is_none()); + assert!(quality_reason(&h.app, 0).is_none(), "fixed→progressive must invalidate the cached disabled plans"); + let adopted = h.app.session.doc.render.setups["CPU costs"].clone(); + let mut unchanged = adopted.clone(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &mut unchanged.job else { panic!("CPU") }; + options.progressive = None; + assert_eq!(unchanged, fixed, "only the explicit adoption may change fixed sampling"); + let chip = reveal_inspector_target(&mut h, "render:quality:draft"); + h.step(&json!({"click":[chip.center().x,chip.center().y]})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.doc.render.setups["CPU costs"], expected_budget(adopted, 960, 540, 16, CpuBudget::Compact)); + assert_eq!(h.app.session.undo.len(), history.1 + 2, "adoption and the budget are two explicit single-Undo actions"); + } + + #[test] + fn cpu_quality_incompatible_adaptive_and_hostile_plan_refuse_atomically_with_all_draft_flags() { + let mut h = cpu_fixture(true); + h.app.render_workspace.view.studio.adaptive = Some(AdaptiveSampling { pilot_samples: 16, min_samples: 32, ..Default::default() }); + setups::save(&mut h.app).unwrap(); + h.frames(3); + let before = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let clean = h.app.render_workspace.view.clean_setup.clone(); + let dirty = h.app.render_workspace.view.dirty; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert!(quality_reason(&h.app, 0).is_some()); + h.step(&json!({"click":{"handle":"render:quality:draft"}})).unwrap(); + assert!(choose_quality(&mut h.app, 0).unwrap_err().contains("adaptive")); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + let mut plan = h + .app + .run( + "render.quality.prepare", + json!({"id":"Q-002","variant":"cpu_progressive_png","acknowledge_omissions":true, + "cpu":{"minimum_budget":h.app.render_workspace.view.raytrace.budget,"adaptive":h.app.render_workspace.view.studio.adaptive}}), + ) + .unwrap(); + plan["settings"]["width"] = json!(0); + assert!(apply_quality_transaction(&mut h.app, &plan).is_err()); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.render_workspace.view.clean_setup, clean); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert!(h.app.render_workspace.view.job.is_none()); + } + + #[test] + fn cpu_quality_pointer_uses_fresh_canonical_plan_and_rejects_stale_profile_context() { + let mut h = cpu_fixture(false); + prepare_quality_choices(&mut h.app); + let source = h.app.render_workspace.view.inspector.quality_source; + let cache = h.app.render_workspace.view.inspector.quality_plans.as_mut().unwrap(); + let forged = cache[0].as_mut().unwrap(); + forged["settings"] = json!({"width":777,"height":333}); + forged["cpu_options"] = json!({"budget":"workstation","progressive":{"samples_per_pixel":7,"seed":999}}); + h.step(&json!({"click":{"handle":"render:quality:draft"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (960, 540)); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 21026 })); + assert_eq!(h.app.render_workspace.view.raytrace.budget, CpuBudget::Compact); + let stale = h + .app + .run( + "render.quality.prepare", + json!({"id":"Q-002","variant":"cpu_progressive_png","acknowledge_omissions":true, + "cpu":{"minimum_budget":"compact"}}), + ) + .unwrap(); + h.app.render_workspace.view.raytrace.budget = CpuBudget::Workstation; + let before = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + assert!(apply_quality_transaction(&mut h.app, &stale).is_err()); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + prepare_quality_choices(&mut h.app); + assert_ne!(h.app.render_workspace.view.inspector.quality_source, source); + assert_eq!( + h.app.render_workspace.view.inspector.quality_plans.as_ref().unwrap()[0].as_ref().unwrap()["cpu_options"]["budget"], + "workstation" + ); + } +} + +#[test] +fn cpu_glass_transport_offers_explicit_path_adoption_and_never_shows_gpu_strata_or_mutates_on_paint() { + for legacy in [false, true] { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + h.app.preferences.render_legacy_image_defaults = legacy; + super::super::select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.path = None; + h.app.render_workspace.view.draft.width = 8; + h.app.render_workspace.view.draft.height = 8; + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, super::super::RenderSelection::Sampling); + h.frames(3); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let mut expected = setups::snapshot(&h.app).unwrap(); + expected.camera = doc.render.setups.get(&h.app.render_workspace.view.name).map_or_else(Default::default, |setup| setup.camera); + let glass = h.app.tr("render.children.glass").to_string(); + let glass_section = format!("dialog:section:{glass}"); + reveal_inspector_target(&mut h, &glass_section); + h.step(&json!({"click":{"handle":glass_section}})).unwrap(); + h.frames(2); + assert!(h.widget(h.app.tr("render.children.fresnel")).is_none()); + assert!(crate::scenario::rect_of("render:nested-enable").is_none(), "CPU has no GPU-only nested flag"); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + assert!(std::sync::Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + reveal_inspector_target(&mut h, "render:cpu-glass-adopt-progressive"); + h.step(&json!({"click":{"handle":"render:cpu-glass-adopt-progressive"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 1); + let adopted = h.app.session.doc.clone(); + let saved = &adopted.render.setups[&h.app.render_workspace.view.name]; + let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut expected.job else { + panic!("CPU intent missing") + }; + options.progressive = Some(Default::default()); + options.primary_samples = 1; + assert_eq!(*saved, expected); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), history.1 + 1, "the explicit sampling adoption saves once"); + reveal_inspector_target(&mut h, "render:cpu-glass-enable-path"); + h.step(&json!({"click":{"handle":"render:cpu-glass-enable-path"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.raytrace.path.unwrap().max_depth, 8); + assert!(h.app.render_workspace.view.job.is_none()); + let completed = h.app.session.doc.clone(); + let saved = &completed.render.setups[&h.app.render_workspace.view.name]; + let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut expected.job else { + panic!("CPU intent missing") + }; + options.path = Some(Default::default()); + assert_eq!(*saved, expected); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), history.1 + 2, "enabling indirect transport is a second explicit edit"); + assert_eq!(completed.features, doc.features); + assert_eq!(completed.materials, doc.materials); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, adopted); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, doc); + h.app.run("edit.redo", json!({})).unwrap(); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, completed); + } +} + +mod saved_clear_coat_contract { + use super::*; + use solidcraft_engine::{Sel, doc::render_coat::CoatMaterial}; + + fn body_editor(gpu: bool, rich: bool) -> Harness { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1440,"height":2200})); + h.app.render_workspace.view.live_paused = true; + let mut options = if gpu { json!({"samples":4,"seed":81,"max_depth":2}) } else { json!({"progressive":{"samples_per_pixel":4,"seed":81}}) }; + let mut camera = h.app.cam; + camera.fov = 0.6; + if rich { + options["lens"] = json!({"aperture_radius_mm":0.2,"focus_distance_mm":100}); + options["denoise"] = json!(true); + options["aging"] = json!([{"kind":"dust","strength":0.2,"coverage":0.4}]); + if gpu { + options["linear_exr"] = json!(true); + options["tone_map"] = json!("aces_fitted"); + options["finishing"] = json!({"rgb_gain":[1.1,0.9,1.2],"contrast":1.1,"saturation":0.8}); + } else { + options["output"] = + json!({"linear_exr":true,"tone_map":"aces_fitted","finishing":{"rgb_gain":[1.1,0.9,1.2],"contrast":1.1,"saturation":0.8}}); + } + } + h.app + .run( + "render.settings.set", + json!({"name":"Coat","set":{"width":8,"height":8,"camera":camera,"exposure_ev":1.25, + "job":{"method":if gpu {"gpu_path"}else{"cpu_raytrace"},"options":options}}}), + ) + .unwrap(); + if rich { + h.app + .run( + "render.library.surface.bind", + json!({"name":"Coat","surface":{"id":"SURF-001","body_index":0,"body_name":"Subject","scale":10}}), + ) + .unwrap(); + } + // Activate the authored perspective shot; numerical reload deliberately + // leaves the previous camera alone and cannot make its saved lens usable. + activate_saved_shot(&mut h.app, "Coat".into()).unwrap(); + assert_eq!(h.app.cam, camera); + h.app.session.selection = vec![Sel::Body { name: "Subject".into() }]; + let selection = super::super::super::object_selection(&h.app); + super::super::super::selection_editor(&mut h.app, &selection); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + h + } + fn click(h: &mut Harness, handle: &str) { + let rect = reveal_inspector_target(h, handle); + assert!(crate::scenario::rect_of("render:inspector").unwrap().contains(rect.center())); + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.frames(3); + } + fn reveal_coat(h: &mut Harness) { + let handle = format!("dialog:section:{}", h.app.tr("render.appearance_editor.coat")); + click(h, &handle); + assert!(crate::scenario::rect_of("render:coat:enable").is_some()); + } + fn scalar(h: &mut Harness, handle: &str, value: &str, mixed: bool) { + let rect = reveal_inspector_target(h, handle); + // mixed_slider publishes its track+numeric field union. The rightmost + // ten points are in the actual scalar child; never send Tab from a track. + let at = if mixed { egui::pos2(rect.right() - 10.0, rect.center().y) } else { rect.center() }; + h.step(&json!({"click":[at.x,at.y],"double":true})).unwrap(); + h.step(&json!({"key":"A","cmd":true,"ctrl":true})).unwrap(); + h.step(&json!({"text":value})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(3); + } + fn authored(h: &Harness) -> CoatMaterial { + h.app.session.doc.render.setups["Coat"].coats.iter().next().unwrap().coat + } + #[test] + fn actual_cpu_and_gpu_coat_controls_save_all_numbers_reopen_hydrate_and_undo_without_paint_writes() { + for gpu in [false, true] { + let mut h = body_editor(gpu, false); + 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; + reveal_coat(&mut h); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + click(&mut h, "render:coat:enable"); + scalar(&mut h, "render:coat:weight", "0.63", true); + scalar(&mut h, "render:coat:roughness", "0.61", true); + scalar(&mut h, "render:coat:ior-field", "1.7", false); + let expected = CoatMaterial { weight: 0.63, roughness: 0.61, ior: 1.7 }; + let request = super::super::super::image_request(&h.app).unwrap(); + assert!(setups::has_runtime_inputs(&h.app), "portable coat drafts remain unsaved for review/navigation"); + assert!(!setups::requires_runtime_request(&h.app), "stable coat preview does not require ordinal override capture"); + assert_eq!(request["settings"]["coats"][0]["coat"], json!(expected)); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "all previewed coat edits are prospective"); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state()), "prospective coat edits preserve the exact immutable CAD model state"); + click(&mut h, "render:coat:save"); + assert_eq!(authored(&h), expected); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state()), "saving only coat intent preserves the exact immutable CAD model state"); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.features, before.features); + assert_eq!(h.app.session.doc.materials, before.materials); + let saved = h.app.session.doc.clone(); + click(&mut h, "render:coat:save"); + assert!(Arc::ptr_eq(&saved, &h.app.session.doc), "repeating the exact saved coat is a no-op"); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + let bytes = solidcraft_engine::io::write_design_container(&saved).unwrap(); + let loaded = solidcraft_engine::io::read_design(&bytes).unwrap(); + assert_eq!(loaded.render, saved.render); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.doc, before); + assert!(h.app.render_workspace.view.draft.coats.is_empty()); + assert!(super::super::super::image_request(&h.app).unwrap()["settings"].get("coats").is_none()); + h.app.run("edit.redo", json!({})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.doc, saved); + h.app.session = solidcraft_engine::Session::new(loaded); + setups::load(&mut h.app); + h.frames(3); + let reopened = h.app.session.doc.clone(); + h.frames(5); + assert!(Arc::ptr_eq(&reopened, &h.app.session.doc), "hydrating saved coat numbers never writes on paint"); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + assert_eq!(super::super::super::image_request(&h.app).unwrap()["settings"]["coats"][0]["coat"], json!(expected)); + } + } + #[test] + fn actual_saved_coat_numeric_replacement_requires_consent_and_removal_confirms_with_one_undo() { + let mut h = body_editor(false, false); + reveal_coat(&mut h); + click(&mut h, "render:coat:enable"); + click(&mut h, "render:coat:save"); + let saved = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + scalar(&mut h, "render:coat:ior-field", "1.8", false); + assert_eq!(super::super::super::image_request(&h.app).unwrap()["settings"]["coats"][0]["coat"]["ior"], json!(1.8)); + click(&mut h, "render:coat:save"); + assert!(Arc::ptr_eq(&saved, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + click(&mut h, "render:coat:replace"); + click(&mut h, "render:coat:save"); + assert_eq!(authored(&h).ior, 1.8); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.doc, saved); + // Undo clears model selection by contract. Explicitly reopen the same + // body editor before exercising the real saved-coat removal controls. + assert!(h.app.session.selection.is_empty()); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Subject".into() }]})).unwrap(); + h.frames(3); + assert!(Arc::ptr_eq(&saved, &h.app.session.doc)); + click(&mut h, "render:coat:remove"); + assert!(materials::confirmation_open(&h.app)); + assert!(h.widget(h.app.tr("render.coat_remove_title")).is_some()); + assert!(Arc::ptr_eq(&saved, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + h.frames(3); + assert!(Arc::ptr_eq(&saved, &h.app.session.doc)); + click(&mut h, "render:coat:remove"); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + h.frames(3); + assert!(h.app.session.doc.render.setups["Coat"].coats.is_empty()); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.doc, saved); + } + #[test] + fn actual_coat_save_keeps_saved_maps_aging_lens_filter_output_and_unsaved_camera_exact() { + for gpu in [false, true] { + let mut h = body_editor(gpu, true); + let original = h.app.session.doc.render.setups["Coat"].clone(); + assert_eq!(original.surfaces.len(), 1); + let physical = h.app.run("component.properties", json!({})).unwrap(); + h.app.cancel_view_animation(); + h.app.cam.yaw += 0.2; + let camera = h.app.cam; + let model = h.app.session.model.state(); + let undo = h.app.session.undo.len(); + reveal_coat(&mut h); + click(&mut h, "render:coat:enable"); + scalar(&mut h, "render:coat:ior-field", "1.7", false); + click(&mut h, "render:coat:save"); + let actual = h.app.session.doc.render.setups["Coat"].clone(); + let mut expected = original; + expected.coats = actual.coats.clone(); + assert_eq!(actual, expected, "coat authoring changes no other saved field"); + assert_eq!(authored(&h).ior, 1.7); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.run("component.properties", json!({})).unwrap(), physical); + let request = super::super::super::image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["coats"][0]["coat"]["ior"], json!(1.7)); + assert_eq!(request["settings"]["surfaces"], json!(expected.surfaces)); + } + } + + #[test] + fn actual_coat_save_discard_remove_and_undo_preserve_an_independent_local_map_draft() { + let mut h = body_editor(true, false); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "Subject").unwrap(); + materials::install_library_surface(&mut h.app, "SURF-001", target, "yz", 2.5, 0.0).unwrap(); + let maps = h.app.render_workspace.view.materials.bindings[0].maps.clone(); + reveal_coat(&mut h); + click(&mut h, "render:coat:enable"); + click(&mut h, "render:coat:save"); + let saved = h.app.session.doc.clone(); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, maps); + assert!(h.app.render_workspace.view.materials.bindings[0].maps_enabled); + let request = super::super::super::image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["coats"][0]["coat"]["ior"], json!(1.5)); + assert_eq!(request["raytrace"]["textures"][0]["base_color_srgb"], json!(maps.color)); + assert!(request["raytrace"].get("clear_coats").is_none(), "a stable coat must not be duplicated as an ordinal override"); + scalar(&mut h, "render:coat:ior-field", "1.8", false); + click(&mut h, "render:coat:discard"); + assert!(Arc::ptr_eq(&saved, &h.app.session.doc)); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, maps); + assert_eq!(super::super::super::image_request(&h.app).unwrap()["settings"]["coats"][0]["coat"]["ior"], json!(1.5)); + click(&mut h, "render:coat:remove"); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + h.frames(3); + assert!(h.app.session.doc.render.setups["Coat"].coats.is_empty()); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, maps); + assert!(!h.app.render_workspace.view.materials.bindings[0].coat_enabled); + assert!(super::super::super::image_request(&h.app).unwrap()["settings"].get("coats").is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.doc, saved); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, maps); + assert!( + h.app.render_workspace.view.materials.bindings[0].coat_enabled, + "saved Undo restores the actual stable coat without changing the map source" + ); + assert_eq!(super::super::super::image_request(&h.app).unwrap()["settings"]["coats"][0]["coat"]["ior"], json!(1.5)); + h.app.run("edit.redo", json!({})).unwrap(); + h.frames(3); + assert!(!h.app.render_workspace.view.materials.bindings[0].coat_enabled); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, maps); + assert!(super::super::super::image_request(&h.app).unwrap()["settings"].get("coats").is_none()); + } + + #[test] + fn actual_coat_revalidation_tracks_the_same_stable_source_after_an_ordinal_shift_without_duplicating_maps() { + let mut h = body_editor(true, false); + let removed = + materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "Subject").unwrap().stable_target.unwrap(); + h.app.run("solid.box", json!({"length":4,"width":4,"height":2,"corner":[20,0,0],"body_name":"Survivor"})).unwrap(); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "Survivor").unwrap(); + assert_eq!(target.ordinal, 1); + let stable = target.stable_target.clone().unwrap(); + materials::install_library_surface(&mut h.app, "SURF-001", target, "yz", 2.5, 0.0).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Survivor".into() }]; + let selection = super::super::super::object_selection(&h.app); + super::super::super::selection_editor(&mut h.app, &selection); + h.frames(3); + reveal_coat(&mut h); + click(&mut h, "render:coat:enable"); + click(&mut h, "render:coat:save"); + let maps = h.app.render_workspace.view.materials.bindings[0].maps.clone(); + h.app.run("timeline.delete", json!({"feature":removed.feature.to_string()})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Survivor".into() }]; + let selection = super::super::super::object_selection(&h.app); + super::super::super::selection_editor(&mut h.app, &selection); + h.frames(3); + assert_eq!(materials::read_targets(&mut h.app).unwrap()[0].ordinal, 0); + assert!(super::super::super::image_request(&h.app).is_err(), "a changed source is never silently revalidated on paint"); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let history = (h.app.session.revision, h.app.session.undo.len()); + click(&mut h, "render:coat:revalidate"); + let bindings = &h.app.render_workspace.view.materials.bindings; + assert_eq!(bindings.len(), 1, "the old captured ordinal is replaced, not duplicated"); + assert_eq!(bindings[0].target.ordinal, 0); + assert_eq!(bindings[0].target.stable_target.as_ref(), Some(&stable)); + assert_eq!(bindings[0].maps, maps); + let request = super::super::super::image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["coats"][0]["target"], json!(stable)); + assert_eq!(request["raytrace"]["textures"][0]["body_index"], json!(0)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), history); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state()), "explicit target revalidation preserves the exact immutable CAD model state"); + } + + #[test] + fn transient_map_origin_preserves_the_full_authored_domain_on_paint_and_unrelated_pointer_edit() { + for origin in [[1e8, -1e8, 0.0], [-1e9, 1e9, 1e9]] { + let mut h = body_editor(true, false); + reveal_coat(&mut h); + click(&mut h, "render:coat:enable"); + click(&mut h, "render:coat:save"); + let saved = h.app.session.doc.render.setups["Coat"].clone(); + assert_eq!(saved.coats.len(), 1); + // A separate saved built-in binding is an independent preservation + // sentinel. Runtime map drafts cannot be mixed with saved maps in + // the active shot, so do not invent that unsupported request. + h.app.run("render.settings.set", json!({"name":"Saved map sentinel","set":saved.clone()})).unwrap(); + h.app + .run( + "render.library.surface.bind", + json!({"name":"Saved map sentinel", + "surface":{"id":"SURF-001","body_index":0,"body_name":"Subject","scale":10}}), + ) + .unwrap(); + assert_eq!(h.app.session.doc.render.setups["Saved map sentinel"].surfaces.len(), 1); + h.app.render_workspace.view.name = "Coat".into(); + setups::load(&mut h.app); + h.app.session.selection = vec![Sel::Body { name: "Subject".into() }]; + let selected = super::super::super::object_selection(&h.app); + super::super::super::selection_editor(&mut h.app, &selected); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "Subject").unwrap(); + materials::install_library_surface(&mut h.app, "SURF-001", target, "yz", 2.5, 0.0).unwrap(); + h.app.render_workspace.view.materials.bindings[0].maps.frame.origin = origin; + let maps = h.app.render_workspace.view.materials.bindings[0].maps.clone(); + maps.frame.validate().unwrap(); + let request = super::super::super::image_request(&h.app).unwrap(); + assert_eq!(request["raytrace"]["textures"][0]["frame"], json!(maps.frame)); + assert_eq!(request["settings"]["coats"], json!(saved.coats)); + let document = 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 selection = h.app.session.selection.clone(); + h.frames(3); + let header = format!("dialog:section:{}", h.app.tr("render.appearance_editor.maps")); + click(&mut h, &header); + assert_eq!( + h.app.render_workspace.view.materials.bindings[0].maps, maps, + "opening the real Maps controls must not clamp a valid authored origin" + ); + assert_eq!(super::super::super::image_request(&h.app).unwrap(), request); + h.frames(4); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, maps); + // Edit a different, real visible control. Only that field may change + // in the runtime request; origin and both repeat vectors stay exact. + let label = h.app.tr("render.appearance_editor.v_up"); + let tree = h.output.accesskit_update.as_ref().unwrap(); + let node = tree + .nodes + .iter() + .rev() + .find(|(_, node)| node.role() == egui::accesskit::Role::CheckBox && node.label() == Some(label)) + .unwrap() + .1 + .clone(); + assert!(!node.is_disabled()); + let bounds = node.bounds().unwrap(); + let flip = egui::Rect::from_min_max(egui::pos2(bounds.x0 as f32, bounds.y0 as f32), egui::pos2(bounds.x1 as f32, bounds.y1 as f32)); + assert!(crate::scenario::rect_of("render:inspector").unwrap().contains_rect(flip)); + assert!(flip.top() > crate::scenario::rect_of("render:inspector:header").unwrap().bottom()); + h.step(&json!({"click":[flip.center().x,flip.center().y]})).unwrap(); + h.frames(3); + let mut expected_maps = maps.clone(); + expected_maps.flip_v = !maps.flip_v; + let mut expected_request = request.clone(); + expected_request["raytrace"]["textures"][0]["flip_v"] = json!(expected_maps.flip_v); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].maps, expected_maps); + assert_eq!(super::super::super::image_request(&h.app).unwrap(), expected_request); + assert!(Arc::ptr_eq(&document, &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!(h.app.session.selection, selection); + assert_eq!(h.app.session.doc.render.setups["Coat"], saved); + assert!(h.app.render_workspace.view.job.is_none()); + } + } +} + +#[test] +fn gpu_check_keeps_pending_setup_distinct_from_a_failed_device_without_starting_work() { + fn has_text(shape: &egui::Shape, text: &str) -> bool { + match shape { + egui::Shape::Text(s) => s.galley.text().contains(text), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, text)), + _ => false, + } + } + let mut h = fixture(); + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.run("view.render_select", json!({"kind":"check"})).unwrap(); + h.frames(3); + let doc = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let state = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let request = super::super::image_request(&h.app).unwrap(); + // Keep the preparation channel alive without starting a driver or worker. + // These are real UI renders/clicks of the three host lifecycle states. + let (sender, receiver) = std::sync::mpsc::channel(); + let mut receiver = Some(receiver); + let failure = "driver setup rejected the fixture device"; + enum SetupPhase { + NotStarted, + Preparing, + Failed, + } + for phase in [SetupPhase::NotStarted, SetupPhase::Preparing, SetupPhase::Failed] { + let (host, label, phase) = match phase { + SetupPhase::NotStarted => (super::super::PathHost::NotStarted, h.app.tr("render.gpu_path_not_started").to_string(), "not_started"), + SetupPhase::Preparing => ( + super::super::PathHost::Preparing(receiver.take().unwrap(), std::time::Instant::now()), + h.app.tr("render.gpu_path_preparing").to_string(), + "preparing", + ), + SetupPhase::Failed => { + (super::super::PathHost::Failed(failure.into()), format!("{}: {failure}", h.app.tr("render.gpu_path_failed")), "failed") + } + }; + h.app.render_workspace.path_host = host; + h.frames(3); + let lines = check_lines(&h.app); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].label, label); + assert_eq!(lines[0].status, if phase == "failed" { ui_kit::CheckStatus::Error } else { ui_kit::CheckStatus::Warning }); + assert!(h.shapes.iter().any(|shape| has_text(&shape.shape, &label)), "the actual Check editor must show {phase}"); + let report = check_report(&h.app).unwrap(); + let marker = if phase == "failed" { "×" } else { "!" }; + assert!(report.contains(&format!("{marker} {label}"))); + assert!(!report.contains(h.app.tr("render.gpu_unavailable")), "pending/failed setup must keep its precise lifecycle reason"); + for action in ["render.preflight", "render.start"] { + assert_eq!(super::super::ribbon::action_ready(&h.app, action).unwrap_err(), label); + assert!(!super::super::interactive_command_info(&h.app, solidcraft_engine::find_command(action).unwrap()).enabled); + } + if phase != "failed" { + assert!(crate::scenario::rect_of("render:check:go-to:0").is_none(), "waiting for setup has no corrective settings action"); + } + let target = reveal_inspector_target(&mut h, "render:check"); + h.step(&json!({"click":[target.center().x,target.center().y]})).unwrap(); + assert!(h.app.render_workspace.view.inspector.checked.is_none(), "a disabled Check cannot manufacture a successful report"); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.retained.is_empty()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.cam, camera); + assert_eq!(super::super::image_request(&h.app).unwrap(), request); + assert_eq!(state, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + } + drop(sender); +} + +#[test] +fn check_capability_notes_are_method_specific_painted_accessible_and_read_only() { + fn painted(h: &Harness, expected: &str) -> bool { + fn text(shape: &egui::Shape, expected: &str, clip: egui::Rect) -> bool { + match shape { + egui::Shape::Text(value) if value.galley.text() == expected => { + let rect = value.galley.rect.translate(value.pos.to_vec2()); + rect.is_positive() && !value.galley.elided && clip.contains_rect(rect) + } + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| text(shape, expected, clip)), + _ => false, + } + } + h.shapes.iter().any(|shape| text(&shape.shape, expected, shape.clip_rect.intersect(h.ctx.content_rect()))) + } + fn accessible(h: &Harness, expected: &str) -> bool { + h.output.accesskit_update.as_ref().unwrap().nodes.iter().any(|(_, node)| { + node.role() == egui::accesskit::Role::Label + && node.value() == Some(expected) + && node.bounds().is_some_and(|bounds| bounds.x1 > bounds.x0 && bounds.y1 > bounds.y0) + }) + } + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.render_workspace.view.live_paused = true; + h.app.session.set_render_job_host(None).unwrap(); + h.app.render_workspace.view.method = method; + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.run("view.render_select", json!({"kind":"check"})).unwrap(); + h.frames(3); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let selection = h.app.session.selection.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = super::super::image_request(&h.app).unwrap(); + let raytrace = h.app.render_workspace.view.raytrace.clone(); + let under_hood = format!("dialog:section:{}", h.app.tr("render.children.under_hood")); + reveal_inspector_target(&mut h, &under_hood); + h.step(&json!({"click":{"handle":under_hood}})).unwrap(); + h.frames(3); + let glass = match method { + ImageMethod::Raster => "render.output_raytrace_only", + ImageMethod::CpuRaytrace => "render.check_glass_cpu", + ImageMethod::GpuRaytrace => "render.check_glass_gpu", + }; + let mut expected = vec![glass, "render.check_media_remaining"]; + if method != ImageMethod::Raster { + expected.push("render.check_media_scope"); + } + for key in expected { + reveal_inspector_target(&mut h, &format!("dialog:note:{key}")); + let value = h.app.tr(key); + assert!(painted(&h, value), "the visible Check panel must paint the complete {key} note"); + assert!(accessible(&h, value), "the same {key} note must be available through accessibility"); + } + for key in ["render.transmission_scope", "render.advanced_material_scope"] { + assert!(!accessible(&h, h.app.tr(key)), "obsolete blanket capability copy must not remain in Check"); + } + for (key, owner) in [("render.check_glass_cpu", ImageMethod::CpuRaytrace), ("render.check_glass_gpu", ImageMethod::GpuRaytrace)] { + if method != owner { + assert!(!accessible(&h, h.app.tr(key)), "a method must not display the other method's Glass contract"); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.raytrace, raytrace); + assert_eq!(super::super::image_request(&h.app).unwrap(), request); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn gpu_environment_browser_labels_explicit_constants_including_black_without_paint_writes() { + fn painted(shape: &egui::Shape, expected: &str, scope: egui::Rect, clip: egui::Rect) -> bool { + match shape { + egui::Shape::Text(text) if text.galley.text() == expected => { + let rect = text.galley.rect.translate(text.pos.to_vec2()); + rect.is_positive() && !text.galley.elided && scope.contains_rect(rect) && clip.contains_rect(rect) + } + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| painted(shape, expected, scope, clip)), + _ => false, + } + } + for (environment, explicit, ambient, key) in [ + (studio::Environment::None, false, [0.55; 3], "render.tree_fixed_studio"), + (studio::Environment::None, true, [0.55; 3], "render.tree_constant"), + (studio::Environment::None, true, [0.0; 3], "render.tree_constant"), + (studio::Environment::Sky, true, [0.55; 3], "render.tree_sky"), + (studio::Environment::Hdr, true, [0.55; 3], "render.tree_no_environment"), + ] { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1440,"height":1200})); + h.app.render_workspace.view.live_paused = true; + h.app.session.set_render_job_host(None).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.studio.environment = environment; + h.app.render_workspace.view.studio.lighting_enabled = explicit; + h.app.render_workspace.view.studio.ambient = ambient; + h.app.render_workspace.view.studio.hdr = super::super::hdr::Input::Empty; + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + h.frames(3); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let selection = h.app.session.selection.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = super::super::image_request(&h.app); + let expected = h.app.tr(key).to_owned(); + let (actual, detail) = super::super::scene::environment(&h.app); + assert_eq!(actual, expected); + if environment == studio::Environment::None && explicit { + assert!(detail.is_empty(), "constant RGB radiance has no authored scalar intensity/rotation detail"); + assert_eq!(request.as_ref().unwrap()["settings"]["job"]["options"]["lighting"]["environment"], json!(ambient)); + } + h.frames(3); + let row = crate::scenario::rect_of("render:tree:environment:current").unwrap(); + assert!( + h.shapes.iter().any(|shape| painted(&shape.shape, &expected, row, shape.clip_rect.intersect(h.ctx.content_rect()))), + "the actual Environment Browser row must paint {expected}" + ); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert_eq!(h.app.render_workspace.view.studio.environment, environment); + assert_eq!(h.app.render_workspace.view.studio.lighting_enabled, explicit); + assert_eq!(h.app.render_workspace.view.studio.ambient, ambient); + assert_eq!(super::super::image_request(&h.app), request); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + #[test] fn output_children_focus_survives_clearing_an_object_pick() { let mut h = fixture(); diff --git a/crates/ui-egui/src/render_workspace_library.rs b/crates/ui-egui/src/render_workspace_library.rs index 48c2e9c2c..31e2d802a 100644 --- a/crates/ui-egui/src/render_workspace_library.rs +++ b/crates/ui-egui/src/render_workspace_library.rs @@ -634,7 +634,8 @@ fn light_panel(app: &mut SolveApp, ui: &mut egui::Ui) { return; } catalog_search(app, ui, &mut view, "render.stage_panels.search_studios"); - let reason = if view.light_scope == 3 { Some(app.tr("render.library_specification_only").to_string()) } else { light_reason(app, &view.kind) }; + let reason = + if view.light_scope == 3 { Some(app.tr("render.library_specification_only").to_string()) } else { selected_light_reason(app, &view) }; let layout = ui_kit::CatalogLayout::new(ui, "render:light:catalog", 0); layout.body(ui, |ui| { let identities: Vec<_> = view.entries.iter().map(|e| format!("render:light:{}", e["id"].as_str().unwrap_or(""))).collect(); @@ -780,16 +781,48 @@ fn surface_panel(app: &mut SolveApp, ui: &mut egui::Ui) { }); restore_view(app, view); } -fn light_reason(app: &SolveApp, kind: &str) -> Option { - if matches!(kind, "native_scenes" | "rigs") && app.render_workspace.view.method != ImageMethod::GpuRaytrace { - return Some(app.tr("render.stage_panels.gpu_required").into()); - } +fn light_reason(app: &SolveApp, _kind: &str) -> Option { if app.render_workspace.view.method == ImageMethod::Raster { return Some(app.tr("render.environment_tiles_require_raytrace").into()); } patch(app).err() } +/// Catalogue availability only; the typed engine projection remains authoritative. +fn selected_light_reason(app: &SolveApp, view: &View) -> Option { + if let Some(reason) = light_reason(app, &view.kind) { + return Some(reason); + } + if app.render_workspace.view.method == ImageMethod::CpuRaytrace && view.kind == "rigs" { + let maximum = view + .details + .as_ref() + .and_then(|detail| detail["resource"]["lights"].as_array()) + .into_iter() + .flatten() + .filter(|light| light["type"] == "rectangular_area") + .filter_map(|light| light["emission"]["rgb"].as_array()) + .flatten() + .filter_map(Value::as_f64) + .fold(0.0, f64::max); + if maximum > 64.0 { + return Some(crate::i18n::format("render.cpu_studio_radiance_limit", &[("radiance", &maximum.to_string())])); + } + } + None +} + +/// The button uses the same portable numerical validator as saving. Stable +/// identities distinguish an unrelated optical body from this map target. +fn cpu_maps_supported(app: &SolveApp, view: &View) -> bool { + let Some(target) = view.target.as_ref().and_then(|target| target.stable_target.as_ref()) else { return false }; + let Ok(setup) = setups::snapshot(app) else { return false }; + let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &setup.job else { return false }; + (setup.optics.is_empty() || options.path.is_some()) + && !setup.optics.iter().any(|optical| &optical.target == target) + && options.validate_surface_maps(setup.exposure_ev).is_ok() +} + fn surface_controls(app: &mut SolveApp, ui: &mut egui::Ui, view: &mut View, id: &str) { let picked = app.session.selection.iter().find_map(|selection| match selection { solidcraft_engine::Sel::Body { name } | solidcraft_engine::Sel::Face { body: name, .. } => Some(name.clone()), @@ -843,6 +876,8 @@ fn surface_controls(app: &mut SolveApp, ui: &mut egui::Ui, view: &mut View, id: .is_some_and(|detail| matches!(detail["projection"]["status"].as_str(), Some("implemented_pending_batch_validation" | "native_appearance"))); let enabled = supported && current_target(app, view); let gpu = app.render_workspace.view.method == ImageMethod::GpuRaytrace; + let cpu = app.render_workspace.view.method == ImageMethod::CpuRaytrace; + let cpu_maps = cpu && cpu_maps_supported(app, view); let mut requested = None; ui.horizontal(|ui| { if ui_kit::button(ui, app.tr("render.stage_panels.use_uniform"), ui_kit::Button::Enabled(enabled)).clicked() { @@ -853,13 +888,16 @@ fn surface_controls(app: &mut SolveApp, ui: &mut egui::Ui, view: &mut View, id: } }); let raytrace = app.render_workspace.view.method != ImageMethod::Raster; - if ui_kit::button(ui, app.tr("render.stage_panels.save_maps"), ui_kit::Button::Enabled(enabled && raytrace && patch(app).is_ok())).clicked() { + let save = + ui_kit::button(ui, app.tr("render.stage_panels.save_maps"), ui_kit::Button::Enabled(enabled && (gpu || cpu_maps) && patch(app).is_ok())); + crate::scenario::publish_target("render:surface:save-maps", save.rect); + if save.clicked() { requested = Some(2); } if !raytrace { ui_kit::text(ui, app.tr("render.surface_import.raytrace_required"), ui_kit::Text::Note("surface:gpu:reason")); - } else if !gpu { - ui_kit::text(ui, app.tr("render.surface_import.saved_cpu"), ui_kit::Text::Note("surface:cpu:reason")); + } else if cpu { + ui_kit::text(ui, app.tr("render.cpu_maps_saved_help"), ui_kit::Text::Note("render.cpu_maps_saved_help")); } if !supported { ui_kit::text(ui, app.tr("render.library_specification_only"), ui_kit::Text::Note("surface:reference:reason")); @@ -881,9 +919,17 @@ fn surface_controls(app: &mut SolveApp, ui: &mut egui::Ui, view: &mut View, id: let surface = json!({"id":id,"body_index":target.ordinal,"body_name":target.name,"scale":view.mapping_scale,"plane":plane,"rotation_rad":rotation_rad}); let plan = app.run("render.library.surface.prepare", surface.clone())?; let action = if mode == 2 { + let mut set = patch(app)?; + if (cpu || app.session.doc.render.setups.contains_key(&app.render_workspace.view.name)) + && let Some(fields) = set.as_object_mut() + { + // Binding maps saves full visible numerical/job intent, but + // camera navigation remains an explicit shot-camera action. + fields.remove("camera"); + } review::Apply::Command { id: "render.library.surface.bind".into(), - params: json!({"name":app.render_workspace.view.name,"set":patch(app)?,"surface":surface,"replace":true}), + params: json!({"name":app.render_workspace.view.name,"set":set,"surface":surface,"replace":true}), } } else { review::Apply::Maps { id: id.into(), target, plane: plane.into(), scale: view.mapping_scale, rotation_rad } @@ -1491,7 +1537,7 @@ fn resource_controls(app: &mut SolveApp, ui: &mut egui::Ui, view: &mut View, id: "physical_profiles" => physical_controls(app, ui, view, id, &detail), "surfaces" | "selene_appearances" => surface_controls(app, ui, view, id), "hdr" | "rigs" => { - let reason = light_reason(app, &view.kind); + let reason = selected_light_reason(app, view); if let Some(reason) = &reason { ui_kit::text(ui, reason, ui_kit::Text::Note("render:light:reason")); } @@ -1827,6 +1873,547 @@ mod studio_browser_tests { assert!(!h.app.file_picker_busy()); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn cpu_path_surface_pointer_save_accepts_an_unrelated_glass_target_and_preserves_targeted_aging_without_paint_writes() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.preferences.render_legacy_image_defaults = false; + for (name, corner) in [("Glass", [0, 0, 0]), ("Panel", [20, 0, 0])] { + h.app.run("solid.box", json!({"body_name":name,"length":10,"width":10,"height":5,"corner":corner,"operation":"new"})).unwrap(); + } + let targets = materials::read_targets(&mut h.app).unwrap(); + let glass = targets.iter().find(|target| target.name == "Glass").unwrap().clone(); + let panel = targets.iter().find(|target| target.name == "Panel").unwrap().clone(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{ + "progressive":{"samples_per_pixel":4,"seed":9},"path":{"max_depth":4}, + "aging":[{"kind":"dust","target":panel.stable_target}] + }}}}), + ) + .unwrap(); + h.app + .run( + "render.optics.bind", + json!({"name":"Studio","body_index":glass.ordinal,"body_name":glass.name,"expected_revision":h.app.session.revision, + "optics":{"ior":1.5,"boundary":"closed_mesh"}}), + ) + .unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Glass".into()}]})).unwrap(); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = before.render.setups["Studio"].camera; + // Surface source controls live in the explicit Surfaces/References + // catalog mode; merely changing a captured resource does not navigate UI. + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-panel"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.library.look_tab, 1); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + choose(&mut h.app, &mut view, "surfaces", "SURF-001").unwrap(); + refresh_targets(&mut h.app, &mut view).unwrap(); + view.target = view.targets.iter().find(|target| target.name == "Glass").cloned(); + assert!(view.target.as_ref().unwrap().stable_target.is_some()); + assert!(!cpu_maps_supported(&h.app, &view), "a map cannot share the Glass target"); + h.app.render_workspace.view.library = view; + h.frames(4); + h.step(&json!({"click":{"handle":"render:surface:save-maps"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_none(), "the actual same-target button stays disabled"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + let model = h.app.session.model.state(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Panel".into()}]})).unwrap(); + let selected = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert_eq!(selected, (history.0 + 1, history.1, history.2), "explicit selection advances only the transient display revision"); + assert_eq!(h.app.session.selection, vec![solidcraft_engine::Sel::Body { name: "Panel".into() }]); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + h.frames(4); + assert!(cpu_maps_supported(&h.app, &h.app.render_workspace.view.library)); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "selection, hydration and repeated paint cannot save a binding"); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state()), "target hydration and repeated paint cannot replace geometry"); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), selected); + h.frames(4); + 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()), selected); + assert!(h.app.render_workspace.view.job.is_none()); + h.step(&json!({"click":{"handle":"render:surface:save-maps"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_some(), "the actual different-target button opens review"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"render:review:acknowledge"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + let saved = h.app.session.doc.clone(); + let setup = &saved.render.setups["Studio"]; + assert_eq!(setup.surfaces.len(), 1); + assert_eq!(setup.surfaces.iter().next().unwrap().target, panel.stable_target.unwrap()); + assert_eq!(setup.optics, before.render.setups["Studio"].optics); + assert_eq!(setup.job, before.render.setups["Studio"].job, "targeted aging and all visible numerical intent survive map binding"); + assert_eq!(setup.camera, camera, "map editing cannot silently save viewport navigation"); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + assert_eq!(saved.appearances, before.appearances); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(solidcraft_engine::doc::Document::from_json(&saved.to_json()).unwrap(), *saved); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, saved); + } + fn library_camera_fixture(method: ImageMethod, saved: bool) -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Sample"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Sample".into()}]})).unwrap(); + let camera = solidcraft_engine::render::Camera { + distance: 73.0, + target: solidcore_record::Vec3::new(10.0, 7.5, 5.0), + yaw: 0.3, + pitch: -0.2, + ..Default::default() + }; + if saved { + let job = match method { + ImageMethod::CpuRaytrace => { + Some(json!({"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":2,"seed":47},"area_samples":4,"seed":731}})) + } + ImageMethod::GpuRaytrace => Some(json!({"method":"gpu_path","options":{"samples":17,"seed":731}})), + ImageMethod::Raster => None, + } + .unwrap(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"width":16,"height":12,"background":[17,31,47],"exposure_ev":0.375,"camera":camera,"job":job}}), + ) + .unwrap(); + } + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, method); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 12; + h.frames(4); + let navigation = solidcraft_engine::render::Camera { distance: 92.0, yaw: 0.75, ..camera }; + h.app.cam = navigation; + h.frames(2); + assert_eq!(h.app.cam, navigation); + assert_eq!(h.app.session.doc.render.setups.contains_key("Studio"), saved); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert!(super::super::setups::snapshot(&h.app).is_ok()); + h + } + + fn library_nonlighting_intent(setup: &solidcraft_engine::doc::render_settings::RenderSetup) -> Value { + let mut value = serde_json::to_value(setup).unwrap(); + for field in ["camera", "stage", "exposure_ev"] { + value.as_object_mut().unwrap().remove(field); + } + for field in ["lighting", "hdr", "environment", "sky", "preset", "lights", "punctual_lights", "area_lights", "sun"] { + value["job"]["options"].as_object_mut().unwrap().remove(field); + } + value + } + + fn assert_library_camera_transaction(mut h: Harness, kind: &str, id: &str, saved: bool) { + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let navigation = h.app.cam; + let expected_camera = if saved { before.render.setups["Studio"].camera } else { navigation }; + if saved { + assert_ne!(navigation, expected_camera, "the fixture must navigate away from the saved shot"); + } + let prospective = super::super::setups::snapshot(&h.app).unwrap(); + if kind == "surfaces" { + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-panel"}})).unwrap(); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + choose(&mut h.app, &mut view, kind, id).unwrap(); + refresh_targets(&mut h.app, &mut view).unwrap(); + view.target = view.targets.iter().find(|target| target.name == "Sample").cloned(); + assert!(current_target(&h.app, &view)); + h.app.render_workspace.view.library = view; + h.frames(4); + h.step(&json!({"click":{"handle":"render:surface:save-maps"}})).unwrap(); + } else { + let mut view = View::default(); + choose(&mut h.app, &mut view, kind, id).unwrap(); + refresh_targets(&mut h.app, &mut view).unwrap(); + review::light(&mut h.app, &view, id).unwrap(); + h.frames(2); + } + assert!(h.app.render_workspace.view.library.review.is_some(), "{kind}/{id}"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"render:review:acknowledge"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_none(), "{kind}/{id}"); + let after = h.app.session.doc.clone(); + let setup = &after.render.setups["Studio"]; + assert_eq!(setup.camera, expected_camera, "{kind}/{id}: a review must not implicitly save navigation over an existing shot"); + assert_eq!(h.app.cam, navigation, "{kind}/{id}: applying must leave the live camera alone"); + assert_eq!(h.app.session.undo.len(), undo + 1); + if kind == "surfaces" { + let mut expected = prospective.clone(); + expected.camera = expected_camera; + expected.surfaces = setup.surfaces.clone(); + assert_eq!(*setup, expected, "only the reviewed maps and the existing camera policy may differ"); + assert_eq!(setup.surfaces.len(), 1); + } else { + assert_eq!(library_nonlighting_intent(setup), library_nonlighting_intent(&prospective)); + if kind == "hdr" { + assert_eq!(setup.stage, prospective.stage); + } else { + assert!(!setup.stage.is_empty()); + } + if kind != "native_scenes" { + assert_eq!(setup.exposure_ev, prospective.exposure_ev); + } + } + assert_eq!(after.features, before.features); + assert_eq!(after.materials, before.materials); + assert_eq!(after.appearances, before.appearances); + 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, navigation); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, after); + assert_eq!(h.app.cam, navigation); + } + + #[test] + fn cpu_hdr_library_review_keeps_saved_and_live_cameras_independent() { + assert_library_camera_transaction(library_camera_fixture(ImageMethod::CpuRaytrace, true), "hdr", "HDR-001", true); + } + + #[test] + fn gpu_native_studio_review_keeps_saved_and_live_cameras_independent() { + assert_library_camera_transaction(library_camera_fixture(ImageMethod::GpuRaytrace, true), "native_scenes", "NATIVE-STUDIO-001", true); + } + + #[test] + fn gpu_rig_review_keeps_saved_and_live_cameras_independent() { + assert_library_camera_transaction(library_camera_fixture(ImageMethod::GpuRaytrace, true), "rigs", "RIG-001", true); + } + + #[test] + fn gpu_hdr_library_review_keeps_saved_and_live_cameras_independent() { + assert_library_camera_transaction(library_camera_fixture(ImageMethod::GpuRaytrace, true), "hdr", "HDR-001", true); + } + + #[test] + fn gpu_saved_maps_review_keeps_saved_and_live_cameras_independent() { + assert_library_camera_transaction(library_camera_fixture(ImageMethod::GpuRaytrace, true), "surfaces", "SURF-001", true); + } + + #[test] + fn library_reviews_keep_new_setup_camera_creation_policy() { + for (method, kind, id) in [ + (ImageMethod::CpuRaytrace, "hdr", "HDR-001"), + (ImageMethod::GpuRaytrace, "native_scenes", "NATIVE-STUDIO-001"), + (ImageMethod::GpuRaytrace, "rigs", "RIG-001"), + (ImageMethod::GpuRaytrace, "hdr", "HDR-001"), + (ImageMethod::GpuRaytrace, "surfaces", "SURF-001"), + ] { + assert_library_camera_transaction(library_camera_fixture(method, false), kind, id, false); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn cpu_saved_builtin_maps_use_real_review_pointer_save_undo_reopen_and_native_render() { + use solidcraft_engine::doc::render_settings::{RenderJob, RenderSetup}; + use solidcraft_engine::render::job::{CpuHost, Integrator, Phase}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + let host = CpuHost::for_platform().unwrap(); + let available = host.descriptor_for(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.preferences.render_legacy_image_defaults = false; + h.app.run("solid.box", json!({"length":10,"width":10,"height":5,"body_name":"Sample"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Sample".into()}]})).unwrap(); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + super::super::select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.draft.width = 8; + h.app.render_workspace.view.draft.height = 8; + h.app.render_workspace.view.studio.linear_exr = true; + h.frames(4); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let old_camera = h.app.session.doc.render.setups.get("Studio").map_or(RenderSetup::default().camera, |s| s.camera); + // Surface source controls live in the explicit Surfaces/References + // catalog mode; merely changing a captured resource does not navigate UI. + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-panel"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.library.look_tab, 1); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + choose(&mut h.app, &mut view, "surfaces", "SURF-001").unwrap(); + refresh_targets(&mut h.app, &mut view).unwrap(); + view.target = view.targets.iter().find(|target| target.name == "Sample").cloned(); + assert!(current_target(&h.app, &view)); + h.app.render_workspace.view.library = view; + h.frames(4); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.render_workspace.view.job.is_none()); + h.step(&json!({"click":{"handle":"render:surface:save-maps"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_some()); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"render:review:acknowledge"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + let saved = h.app.session.doc.clone(); + let setup = &saved.render.setups["Studio"]; + assert_eq!(setup.surfaces.len(), 1); + assert_eq!(setup.camera, old_camera, "binding maps cannot silently save viewport navigation"); + assert!( + matches!(&setup.job,Some(RenderJob::CpuRaytrace{options,..})if options.progressive.is_some()&&options.output.as_ref().is_some_and(|o|o.linear_exr)) + ); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + assert_eq!(saved.appearances, before.appearances); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + super::super::setups::load(&mut h.app); + assert_eq!(h.app.session.doc, saved); + let reopened = solidcraft_engine::doc::Document::from_json(&saved.to_json()).unwrap(); + h.app.session = solidcraft_engine::Session::new(reopened); + h.app.session.set_render_job_host(Some(host)).unwrap(); + super::super::reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "Studio".into(); + super::super::setups::load(&mut h.app); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.frames(4); + assert_eq!(h.app.render_workspace.view.draft.surfaces, setup.surfaces); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = super::super::image_request(&h.app).unwrap(); + if available { + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + assert_eq!(checked["textures"]["bodies"], 1); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + assert!(frame.linear_exr().is_some()); + assert!(!frame.png().is_empty()); + } else { + assert!(h.app.session.execute("render.preflight", &request).is_err(), "offline drafts cannot falsely claim a CPU producer"); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn cpu_native_studio_review_pointer_preserves_camera_and_cold_capture_for_hdr_and_area_rigs() { + use solidcraft_engine::doc::render_settings::{RenderJob, RenderSetup}; + use solidcraft_engine::render::job::{CpuHost, Integrator, Phase}; + for id in ["NATIVE-STUDIO-001", "NATIVE-STUDIO-004"] { + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + let available = host.descriptor_for(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Sample"})).unwrap(); + let saved_camera = + solidcraft_engine::render::Camera { distance: 60.0, target: solidcore_record::Vec3::new(10.0, 7.5, 5.0), ..Default::default() }; + h.app.run("render.settings.set",json!({"name":"Studio","set":{"width":8,"height":8,"camera":saved_camera,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":2,"seed":47},"area_samples":4,"seed":731,"output":{"linear_exr":true}}}}})).unwrap(); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(4); + h.app.cam.distance += 7.0; + let old_camera = h.app.session.doc.render.setups["Studio"].camera; + let navigation = h.app.cam; + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(light_reason(&h.app, "native_scenes").is_none()); + let mut view = View::default(); + choose(&mut h.app, &mut view, "native_scenes", id).unwrap(); + review::light(&mut h.app, &view, id).unwrap(); + h.frames(2); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + h.step(&json!({"click":{"handle":"render:review:acknowledge"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, navigation); + let saved = h.app.session.doc.clone(); + let setup = &saved.render.setups["Studio"]; + assert_eq!(setup.camera, old_camera); + assert_eq!(setup.width, 8); + assert_eq!(setup.height, 8); + let Some(RenderJob::CpuRaytrace { options, .. }) = &setup.job else { panic!("CPU method lost") }; + assert_eq!((options.progressive.unwrap().samples_per_pixel, options.progressive.unwrap().seed), (2, 47)); + assert_eq!((options.area_samples, options.seed), (Some(4), Some(731))); + assert!(options.output.as_ref().unwrap().linear_exr); + assert!(options.hdr.is_some()); + assert_eq!(options.area_lights.as_ref().unwrap().len(), if id.ends_with("004") { 3 } else { 0 }); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, saved); + let reopened = solidcraft_engine::doc::Document::from_json(&saved.to_json()).unwrap(); + h.app.session = solidcraft_engine::Session::new(reopened); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + super::super::reset_document(&mut h.app); + h.app.render_workspace.view.name = "Studio".into(); + super::super::setups::load(&mut h.app); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.frames(4); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = super::super::image_request(&h.app).unwrap(); + let captured: RenderSetup = serde_json::from_value(request["settings"].clone()).unwrap(); + assert_eq!(captured.job, setup.job); + assert_eq!(captured.stage, setup.stage); + assert_eq!(captured.camera, setup.camera); + if available { + h.app.session.execute("render.preflight", &request).unwrap(); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + let frame = handle.frame().unwrap().unwrap(); + assert!(frame.png().starts_with(b"\x89PNG\r\n\x1a\n")); + assert!(frame.linear_exr().unwrap().starts_with(&[0x76, 0x2f, 0x31, 0x01])); + } else { + assert!(h.app.session.execute("render.preflight", &request).is_err()); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + } + } + + #[test] + fn cpu_sun_rig_review_requires_explicit_adoption_pointer_and_preserves_authored_budget() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1600})); + h.app.run("render.settings.set",json!({"name":"Studio","set":{"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"primary_samples":4,"shadows":false,"area_samples":64,"seed":731}}}})).unwrap(); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + super::super::setups::load(&mut h.app); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + let mut view = View::default(); + choose(&mut h.app, &mut view, "rigs", "RIG-020").unwrap(); + let source = &view.details.as_ref().unwrap()["resource"]["lights"][0]; + assert_eq!(source["type"], "uniform_distant_disk"); + let expected_sun = solidcraft_engine::render::job::Sun { + direction: std::array::from_fn(|i| -source["incoming_photon_direction"][i].as_f64().unwrap()), + angular_radius_rad: source["angular_diameter_rad"].as_f64().unwrap() * 0.5, + radiance: serde_json::from_value(source["emission"]["rgb"].clone()).unwrap(), + }; + assert_eq!(expected_sun.radiance, [14721.3402896; 3], "the authored finite Sun is above the unrelated rectangle limit"); + expected_sun.validate().unwrap(); + assert!(selected_light_reason(&h.app, &view).is_none(), "a valid Sun keeps its own shared radiance domain"); + review::light(&mut h.app, &view, "RIG-020").unwrap(); + h.frames(3); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"render:review:acknowledge"}})).unwrap(); + h.frames(2); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(0.0)); + h.step(&json!({"click":{"handle":"render:review:enable-indirect"}})).unwrap(); + h.frames(2); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(1.0)); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + let job = h.app.render_workspace.view.raytrace.clone(); + assert_eq!(job.path.unwrap().max_depth, 8); + assert_eq!(job.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(job.primary_samples, 1); + assert!(job.shadows); + assert_eq!((job.area_samples, job.seed), (Some(64), Some(731)), "explicit GI adoption preserves authored unrelated sampling fields"); + assert_eq!(job.sun.as_deref(), Some(&expected_sun), "review applies the exact Sun radiance/direction/radius without clamping or splitting"); + let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &h.app.session.doc.render.setups["Studio"].job + else { + panic!("CPU method lost"); + }; + assert_eq!(options.sun, Some(expected_sun)); + assert!(options.area_lights.as_ref().unwrap().is_empty(), "a finite Sun is not reinterpreted as rectangle intensity"); + assert!(h.app.render_workspace.view.studio.sun_enabled); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + super::super::setups::load(&mut h.app); + h.app.render_workspace.view.draft.width = 2048; + h.app.render_workspace.view.draft.height = 2048; + // The fixed Compact image is valid; prospective progressive16 adoption + // crosses its pixel limit. The refusal offers Studio, never adopts it. + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let sampling = CpuProgressiveOptions::default(); + assert_eq!(sampling.samples_per_pixel, 16); + let sampling = Some(sampling); + assert!(CpuBudget::Compact.validate_image(2048, 2048, None).is_ok()); + assert_eq!(CpuBudget::Compact.limits().max_progressive_pixels, 1_048_576); + assert!(CpuBudget::Compact.validate_image(2048, 2048, sampling).is_err()); + assert!(CpuBudget::Studio.validate_image(2048, 2048, sampling).is_ok()); + let draft = super::super::setups::draft(&h.app).unwrap(); + let options = h.app.render_workspace.view.raytrace.clone(); + assert_eq!(options.budget, CpuBudget::Compact); + assert!(options.path.is_none() && options.progressive.is_none()); + let model = h.app.session.model.state(); + let state = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let error = review::light(&mut h.app, &view, "RIG-020").unwrap_err(); + assert!(error.contains("render output 2048 × 2048 exceeds the image limits"), "{error}"); + assert!(error.contains("1048576 pixels in all"), "{error}"); + assert!(error.contains("largest image at this aspect is 1024 × 1024"), "{error}"); + assert!(error.contains("choose the Studio CPU resource profile, or a smaller size"), "{error}"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), state); + assert!(Arc::ptr_eq(&h.app.session.model.state(), &model), "refusal must retain the exact evaluated model"); + assert_eq!(super::super::setups::draft(&h.app).unwrap(), draft); + assert_eq!(h.app.render_workspace.view.raytrace, options); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.library.review.is_none()); + } + + #[test] + fn cpu_authored_rig_over_domain_is_visible_and_cannot_open_an_apply_review() { + let mut h = Harness::new(); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"cpu_raytrace","options":{}}}})).unwrap(); + super::super::enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut view = View::default(); + choose(&mut h.app, &mut view, "rigs", "RIG-006").unwrap(); + view.light_scope = 1; + assert!(selected_light_reason(&h.app, &view).unwrap().contains("994.052329239")); + h.app.render_workspace.view.library = view; + h.frames(4); + h.step(&json!({"click":{"handle":"render:light:review"}})).unwrap(); + assert!(h.app.render_workspace.view.library.review.is_none()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + } + #[test] fn appearance_cards_select_inspect_switch_layout_and_keep_explicit_apply() { let mut h = Harness::new(); @@ -2010,6 +2597,7 @@ mod studio_browser_tests { h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Sample"})).unwrap(); super::super::enter(&mut h.app, true).unwrap(); let unchanged = h.app.session.doc.to_json(); + super::super::select_image_method(&mut h.app, ImageMethod::Raster); assert!(light_reason(&h.app, "native_scenes").is_some()); super::super::select_image_method(&mut h.app, ImageMethod::GpuRaytrace); h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); diff --git a/crates/ui-egui/src/render_workspace_library_review.rs b/crates/ui-egui/src/render_workspace_library_review.rs index 95840b9b7..e8ec67fb6 100644 --- a/crates/ui-egui/src/render_workspace_library_review.rs +++ b/crates/ui-egui/src/render_workspace_library_review.rs @@ -18,6 +18,7 @@ pub(in crate::render_workspace) struct Draft { pub acknowledged: bool, pub bounds: bool, pub emitters_only: bool, + pub enable_indirect: bool, pub center: [f64; 3], pub extent: f64, revision: u64, @@ -47,6 +48,7 @@ pub(in crate::render_workspace) fn open(app: &mut SolveApp, variant: &'static st acknowledged: false, bounds: true, emitters_only: false, + enable_indirect: false, center: [0.0; 3], extent: 1000.0, revision: app.session.revision, @@ -67,10 +69,20 @@ pub(in crate::render_workspace) fn quality(app: &mut SolveApp, id: &str) -> Resu } pub(in crate::render_workspace) fn light(app: &mut SolveApp, view: &View, id: &str) -> Result<(), String> { - if let Some(reason) = light_reason(app, &view.kind) { + if let Some(reason) = selected_light_reason(app, view) { return Err(reason); } - let set = patch(app)?; + let mut set = patch(app)?; + if matches!(view.kind.as_str(), "native_scenes" | "rigs" | "hdr") + && (app.session.doc.render.setups.contains_key(&app.render_workspace.view.name) + || (app.render_workspace.view.method == ImageMethod::CpuRaytrace && view.kind != "hdr")) + { + // A lighting transaction preserves the saved shot camera; viewport + // navigation is not an implicit camera-save action. + if let Some(fields) = set.as_object_mut() { + fields.remove("camera"); + } + } let name = app.render_workspace.view.name.clone(); let label = view.details.as_ref().and_then(|d| d["resource"]["name"].as_str()).unwrap_or(id).to_string(); match view.kind.as_str() { @@ -93,7 +105,12 @@ pub(in crate::render_workspace) fn light(app: &mut SolveApp, view: &View, id: &s ), "rigs" => { let rig = json!({"id":id,"variant":"complete","center_mm":view.center,"subject_extent_mm":view.extent}); - let plan = app.run("render.library.studio.prepare", rig.clone())?; + let mut prepare = rig.clone(); + if app.render_workspace.view.method == ImageMethod::CpuRaytrace { + prepare["name"] = json!(name); + prepare["set"] = set.clone(); + } + let plan = app.run("render.library.studio.prepare", prepare)?; open( app, "rig", @@ -101,7 +118,7 @@ pub(in crate::render_workspace) fn light(app: &mut SolveApp, view: &View, id: &s plan, Apply::Command { id: "render.library.studio.apply".into(), - params: json!({"rig":rig,"name":name,"set":set,"replace_lighting_and_environment":true,"replace_stage":true}), + params: json!({"rig":rig,"name":name,"set":set,"expected_revision":app.session.revision,"replace_lighting_and_environment":true,"replace_stage":true}), }, )?; if let Some(draft) = &mut app.render_workspace.view.library.review { @@ -132,7 +149,14 @@ fn apply(app: &mut SolveApp, draft: &mut Draft) -> Result<(), String> { params["rig"]["center_mm"] = json!(draft.center); params["rig"]["subject_extent_mm"] = json!(draft.extent); params["rig"]["variant"] = json!(if draft.emitters_only { "emitters_only" } else { "complete" }); - app.run("render.library.studio.prepare", params["rig"].clone())?; + let mut prepare = params["rig"].clone(); + if draft.method == ImageMethod::CpuRaytrace { + prepare["name"] = params["name"].clone(); + prepare["set"] = params["set"].clone(); + prepare["enable_indirect"] = json!(draft.enable_indirect); + params["enable_indirect"] = json!(draft.enable_indirect); + } + app.run("render.library.studio.prepare", prepare)?; } app.run(id, params.clone())?; if id.as_str() != "render.library.appearance.apply" { @@ -142,10 +166,7 @@ fn apply(app: &mut SolveApp, draft: &mut Draft) -> Result<(), String> { Apply::Maps { id, target, plane, scale, rotation_rad } => { materials::install_library_surface(app, id, target.clone(), plane, *scale, *rotation_rad)? } - Apply::Quality(plan) => { - super::super::inspector::apply_quality(app, plan)?; - setups::save(app)?; - } + Apply::Quality(plan) => super::super::inspector::apply_quality_transaction(app, plan)?, Apply::Physical(_) => {} } Ok(()) @@ -174,13 +195,18 @@ pub(in crate::render_workspace) fn dialog(app: &mut SolveApp, ctx: &egui::Contex _ => "render.stage_panels.acknowledge", }) .to_string(); + let needs_indirect = draft.plan["requires_indirect"] == true; let apply_label = app - .tr(match draft.variant { - "studio" => "render.stage_panels.apply_studio", - "rig" => "render.stage_panels.fit_save", - "physical" => "ui.close", - "quality" => "render.stage_panels.use_budget", - _ => "render.stage_panels.apply", + .tr(if needs_indirect { + "render.cpu_studio_enable_apply" + } else { + match draft.variant { + "studio" => "render.stage_panels.apply_studio", + "rig" => "render.stage_panels.fit_save", + "physical" => "ui.close", + "quality" => "render.stage_panels.use_budget", + _ => "render.stage_panels.apply", + } }) .to_string(); let physical_notice = app.tr("render.physical_plan_only").to_string(); @@ -195,10 +221,16 @@ pub(in crate::render_workspace) fn dialog(app: &mut SolveApp, ctx: &egui::Contex copy: draft.variant == "physical", notice: (draft.variant == "physical").then_some(physical_notice.as_str()), }; - let (closed, answer) = review.show(ctx, current, &mut draft.acknowledged, |ui| { + let can_apply = current && (!needs_indirect || draft.enable_indirect); + let (closed, answer) = review.show(ctx, can_apply, &mut draft.acknowledged, |ui| { if !current { ui_kit::text(ui, app.tr("render.review_stale"), ui_kit::Text::Error("review:stale")); } + if needs_indirect { + ui_kit::text(ui, app.tr("render.cpu_studio_indirect_help"), ui_kit::Text::Note("review:cpu-indirect")); + let response = ui_kit::checkbox(ui, app.tr("render.cpu_studio_enable"), &mut draft.enable_indirect); + crate::scenario::publish_target("render:review:enable-indirect", response.rect); + } match draft.variant { "rig" => { let mut changed = false; @@ -248,6 +280,11 @@ pub(in crate::render_workspace) fn dialog(app: &mut SolveApp, ctx: &egui::Contex ui_kit::Text::Inline, ); }); + ui_kit::row(ui, app.tr("render.children.seed"), |ui| { + ui_kit::text(ui, &draft.plan["gpu_options"]["seed"].to_string(), ui_kit::Text::Inline); + }); + let denoise = if draft.plan["gpu_options"]["denoise"] == true { "render.quality_denoise_on" } else { "render.quality_denoise_off" }; + ui_kit::text(ui, app.tr(denoise), ui_kit::Text::Inline); ui_kit::text(ui, app.tr("render.stage_panels.omits"), ui_kit::Text::Note("review:omits")); ui_kit::text(ui, app.tr("render.stage_panels.quality_omissions"), ui_kit::Text::Note("review:omissions")); } diff --git a/crates/ui-egui/src/render_workspace_light.rs b/crates/ui-egui/src/render_workspace_light.rs index dd804d296..db896bcfb 100644 --- a/crates/ui-egui/src/render_workspace_light.rs +++ b/crates/ui-egui/src/render_workspace_light.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use solidcraft_engine::doc::render_settings::{CpuJob, GpuJob, RenderJob, RenderSetup, SkyEnvironment}; use solidcraft_engine::geom::prelude::*; use solidcraft_engine::render::job::{AreaLights, StudioLighting}; -use solidcraft_engine::schema::render_lights::{Geometry, Light, Visibility}; +use solidcraft_engine::schema::render_lights::{Geometry, Light, LightIdRemap, Visibility}; #[derive(Clone, Debug, Default)] pub(super) struct View { @@ -15,6 +15,26 @@ pub(super) struct View { aim: Option<[f64; 3]>, draft: Option, review: Option, + source: Option, + numeric_history: Option, +} + +#[derive(Clone, Debug)] +struct Source { + settings: std::sync::Weak, + method: ImageMethod, +} +#[derive(Clone, Debug)] +struct NumericHistory { + before: std::sync::Weak, + after: std::sync::Weak, +} +impl NumericHistory { + fn connects(&self, a: &Source, b: &Source) -> bool { + a.method == b.method + && ((self.before.ptr_eq(&a.settings) && self.after.ptr_eq(&b.settings)) + || (self.after.ptr_eq(&a.settings) && self.before.ptr_eq(&b.settings))) + } } #[derive(Clone, Debug)] @@ -47,6 +67,9 @@ struct Draft { reference: f64, minimum: f64, aim: [f64; 3], + emitted_axis: [f64; 3], + inner_angle: f64, + outer_angle: f64, } /// Lighting-only read snapshot also works with unsaved HDR paths and temporary bindings. @@ -55,19 +78,28 @@ fn settings(app: &SolveApp) -> Result { let job = match view.method { ImageMethod::Raster => RenderJob::Raster { transparent_background: false }, ImageMethod::CpuRaytrace => RenderJob::CpuRaytrace { - options: CpuJob { + transparent_background: false, + options: Box::new(CpuJob { + budget: view.raytrace.budget, + sun: view.studio.sun_enabled.then_some(view.studio.sun), + path: view.raytrace.path, + progressive: view.raytrace.progressive, + primary_samples: view.raytrace.primary_samples, + shadows: view.raytrace.shadows, lights: view.raytrace.lights.clone(), preset: view.raytrace.preset, punctual_lights: view.raytrace.punctual_lights.clone(), area_lights: view.raytrace.area_lights.clone(), ..Default::default() - }, + }), }, ImageMethod::GpuRaytrace => RenderJob::GpuPath { transparent_background: false, options: Box::new(GpuJob { lighting: if view.studio.lighting_enabled { Some(StudioLighting { + punctual_lights: view.studio.punctual_lights, + directional_lights: view.studio.directional_lights, sun: view.studio.sun_enabled.then_some(view.studio.sun), environment: view.studio.ambient, area_lights: AreaLights::new(&view.studio.area_lights).map_err(|e| e.to_string())?, @@ -85,7 +117,107 @@ fn settings(app: &SolveApp) -> Result { }), }, }; - Ok(RenderSetup { camera: app.cam, job: Some(job), ..Default::default() }) + Ok(RenderSetup { camera: app.cam, width: 1, height: 1, job: Some(job), ..Default::default() }) +} + +/// Copy the common analytic rig without inventing a backend's implicit studio. +/// This is a pure prospective conversion; the caller publishes only after full validation. +pub(super) fn celestial_method(app: &SolveApp, next: &mut super::ViewState, method: ImageMethod) -> Result<(), String> { + let sources = rows(app)?; + let mut setup = RenderSetup { + camera: app.cam, + width: 1, + height: 1, + job: Some(match method { + ImageMethod::CpuRaytrace => RenderJob::CpuRaytrace { + transparent_background: false, + options: Box::new(CpuJob { + budget: next.raytrace.budget, + sun: next.studio.sun_enabled.then_some(next.studio.sun), + path: next.raytrace.path, + progressive: next.raytrace.progressive, + primary_samples: next.raytrace.primary_samples, + shadows: next.raytrace.shadows, + ..Default::default() + }), + }, + ImageMethod::GpuRaytrace => RenderJob::GpuPath { + transparent_background: false, + options: Box::new(GpuJob { + lighting: Some(StudioLighting { sun: next.studio.sun_enabled.then_some(next.studio.sun), ..Default::default() }), + ..Default::default() + }), + }, + ImageMethod::Raster => return Ok(()), + }), + ..Default::default() + }; + solidcraft_engine::render_lights::write(&mut setup, &sources)?; + let converted = solidcraft_engine::render_lights::inspect(&setup)?; + if sources.len() != converted.len() + || sources.iter().any(|source| { + !converted.iter().any(|target| { + source.id == target.id + && source.geometry.kind() == target.geometry.kind() + && matches!(source.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. }) + == matches!(target.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. }) + }) + }) + { + return Err(app.tr("render.cpu_celestial_switch").into()); + } + match setup.job { + Some(RenderJob::CpuRaytrace { options, .. }) => { + next.raytrace.sun = options.sun.map(Box::new); + next.studio.sun_enabled = options.sun.is_some(); + if let Some(sun) = options.sun { + next.studio.sun = sun; + } + next.raytrace.preset = options.preset; + next.raytrace.lights = options.lights; + next.raytrace.punctual_lights = options.punctual_lights; + next.raytrace.area_lights = options.area_lights; + } + Some(RenderJob::GpuPath { options, .. }) => { + if let Some(lighting) = options.lighting { + next.studio.lighting_enabled = true; + next.studio.directional_lights = lighting.directional_lights; + next.studio.punctual_lights = lighting.punctual_lights; + next.studio.area_lights = lighting.area_lights.iter().copied().collect(); + next.studio.sun_enabled = lighting.sun.is_some(); + if let Some(sun) = lighting.sun { + next.studio.sun = sun; + } + } + } + _ => return Err(app.tr("render.cpu_celestial_switch").into()), + } + Ok(()) +} + +/// The caller has just executed celestial_method's address-preserving conversion. +/// Preserve transient visibility only when its prior Arc/method source is proven; +/// equal row values or counts alone never establish identity. +pub(super) fn celestial_method_applied( + app: &mut SolveApp, + before: &std::sync::Weak, + method: ImageMethod, +) { + let valid = app.render_workspace.view.lights.scope == app.render_workspace.view.name + && app.render_workspace.view.lights.source.as_ref().is_some_and(|source| source.method == method && source.settings.ptr_eq(before)); + let source = Source { settings: std::sync::Arc::downgrade(&app.session.doc.render), method: app.render_workspace.view.method }; + let scope = app.render_workspace.view.name.clone(); + let view = &mut app.render_workspace.view.lights; + view.scope = scope; + view.source = Some(source); + view.numeric_history = None; + view.draft = None; + if !valid { + view.visibility = Visibility::default(); + if matches!(app.render_workspace.view.selection, RenderSelection::Light(_)) { + app.render_workspace.view.selection = RenderSelection::Nothing; + } + } } pub(super) fn rows(app: &SolveApp) -> Result, String> { @@ -96,6 +228,43 @@ pub(super) fn name(app: &SolveApp, light: &Light) -> String { if light.number <= 3 { app.tr(&light.name_key).into() } else { crate::i18n::format(&light.name_key, &[("number", &light.number.to_string())]) } } +/// A known volume-only/transport adoption preserves the analytic rig's addresses. +/// Equal values alone are insufficient: prove both the cached pre-command Arc +/// and its saved rows, then retain only this one exact Undo/Redo edge. +pub(super) fn volume_edited( + app: &mut SolveApp, + before: &std::sync::Weak, + method: ImageMethod, + draft: &RenderSetup, + rig: &[Light], +) { + let valid = app.render_workspace.view.method == method + && app.render_workspace.view.lights.scope == app.render_workspace.view.name + && app.render_workspace.view.lights.source.as_ref().is_some_and(|source| source.method == method && source.settings.ptr_eq(before)) + && before + .upgrade() + .and_then(|settings| { + // A first numerical edit creates the setup from this exact + // controller draft; no unknown source replacement is inferred. + let setup = settings.setups.get(&app.render_workspace.view.name).unwrap_or(draft); + solidcraft_engine::render_lights::inspect(setup).ok() + }) + .as_deref() + == Some(rig) + && rows(app).ok().as_deref() == Some(rig); + if !valid { + loaded(app); + return; + } + let after = std::sync::Arc::downgrade(&app.session.doc.render); + let view = &mut app.render_workspace.view.lights; + if !before.ptr_eq(&after) { + view.numeric_history = Some(NumericHistory { before: before.clone(), after: after.clone() }); + } + view.source = Some(Source { settings: after, method }); + view.draft = None; +} + pub(crate) fn validate_visibility(app: &SolveApp, params: &Value) -> Result<(), String> { if let Some(id) = params.get("id").and_then(Value::as_str) && !rows(app)?.iter().any(|light| light.id == id) @@ -120,9 +289,27 @@ pub(crate) fn apply_visibility(app: &mut SolveApp, command: &str, reply: &Value) } pub(super) fn loaded(app: &mut SolveApp) { - if app.render_workspace.view.lights.scope != app.render_workspace.view.name { + let scope_changed = app.render_workspace.view.lights.scope != app.render_workspace.view.name; + if scope_changed { app.render_workspace.view.lights = View { scope: app.render_workspace.view.name.clone(), ..Default::default() }; } + let source = Source { settings: std::sync::Arc::downgrade(&app.session.doc.render), method: app.render_workspace.view.method }; + let view = &mut app.render_workspace.view.lights; + let unknown = scope_changed + || view.source.as_ref().is_some_and(|previous| { + !(previous.method == source.method && previous.settings.ptr_eq(&source.settings)) + && !view.numeric_history.as_ref().is_some_and(|proof| proof.connects(previous, &source)) + }); + view.source = Some(source); + if unknown { + // Undo/Redo, checkpoint and arbitrary replacements do not carry an edit + // identity map. Never infer identity from equal kind/count/value lists. + view.visibility = Visibility::default(); + view.draft = None; + if matches!(app.render_workspace.view.selection, RenderSelection::Light(_)) { + app.render_workspace.view.selection = RenderSelection::Nothing; + } + } if let Ok(lights) = rows(app) { let view = &mut app.render_workspace.view.lights; view.visibility.muted.retain(|id| lights.iter().any(|light| &light.id == id)); @@ -133,20 +320,73 @@ pub(super) fn loaded(app: &mut SolveApp) { } /// Runs after successful command dispatch, including programmatic control-channel edits. -pub(crate) fn edited(app: &mut SolveApp, params: &Value, reply: &Value) { +pub(crate) fn edited(app: &mut SolveApp, command: &str, params: &Value, reply: &Value) { let Some(name) = reply.get("name").and_then(Value::as_str) else { return }; if name != app.render_workspace.view.name { return; } - let visibility = app.render_workspace.view.lights.visibility.clone(); + let before = rows(app).unwrap_or_default(); + let remap = reply + .get("id_remap") + .filter(|value| value.as_array().is_some_and(|array| array.len() <= 20)) + .and_then(|value| serde_json::from_value::>(value.clone()).ok()) + .unwrap_or_default(); + let remap_id = |id: &str| { + remap.iter().find(|entry| entry.before.id == id && before.iter().any(|light| light == &entry.before)).map(|entry| entry.after_id.clone()) + }; + // One bounded provenance proof keeps the latest verified numerical edit's + // Undo/Redo on the same source. It is not an independent history journal. + // The saved source must match the actual pre-edit draft, not merely its shape. + let history = (|| { + if command != "render.lights.set" || remap.len() != before.len() { + return None; + } + let previous = app.session.undo.last()?; + if previous.label != solidcraft_engine::find_command(command)?.label { + return None; + } + let saved = previous.doc.render.setups.get(name)?; + if solidcraft_engine::render_lights::inspect(saved).ok()? != before { + return None; + } + let cached = app.render_workspace.view.lights.source.as_ref()?; + let source = std::sync::Arc::downgrade(&previous.doc.render); + if !cached.settings.ptr_eq(&source) { + return None; + } + let after = solidcraft_engine::render_lights::inspect(app.session.doc.render.setups.get(name)?).ok()?; + let kind = |light: &Light| (light.geometry.kind(), matches!(light.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. })); + if before.iter().any(|light| { + !remap.iter().any(|entry| { + entry.before == *light && entry.after_id == light.id && after.iter().any(|new| new.id == entry.after_id && kind(new) == kind(light)) + }) + }) { + return None; + } + Some(NumericHistory { before: source, after: std::sync::Arc::downgrade(&app.session.doc.render) }) + })(); + if let Some(history) = history { + app.render_workspace.view.lights.numeric_history = Some(history); + } + let previous = &app.render_workspace.view.lights.visibility; + let visibility = + Visibility { solo: previous.solo.as_deref().and_then(remap_id), muted: previous.muted.iter().filter_map(|id| remap_id(id)).collect() }; + let selection = match &app.render_workspace.view.selection { + RenderSelection::Light(id) => remap_id(id).map_or(RenderSelection::Nothing, RenderSelection::Light), + other => other.clone(), + }; setups::load(app); app.render_workspace.view.lights.visibility = visibility; + // Parameter drafts are keyed by old address/revision. Never hand one to a + // different source that now occupies that address after canonicalization. + app.render_workspace.view.lights.draft = None; loaded(app); if let Some(aim) = params.get("set").and_then(|set| set.get("aim_at")) { app.render_workspace.view.lights.aim = serde_json::from_value(aim.clone()).ok(); } - app.render_workspace.view.selection = - reply.get("id").and_then(Value::as_str).map_or(RenderSelection::Nothing, |id| RenderSelection::Light(id.into())); + // Add/set/duplicate select the command's actual result. Removing another + // source preserves an unrelated selected source through its explicit map. + app.render_workspace.view.selection = reply.get("id").and_then(Value::as_str).map_or(selection, |id| RenderSelection::Light(id.into())); } fn product_centre(app: &SolveApp) -> [f64; 3] { @@ -234,19 +474,26 @@ pub(crate) fn filter_request(app: &SolveApp, mut request: Value) -> Result 1; if raster { note(app, ui, "render.method_limit_raster"); } @@ -353,8 +599,7 @@ pub(super) fn lighting(app: &mut SolveApp, ui: &mut egui::Ui) { let mut chosen = usize::from(custom); let labels = [app.tr("render.lighting_preset").to_string(), app.tr("render.lighting_custom").to_string()]; let reason = app.tr("render.lighting_preset_cpu").to_string(); - let legacy_reason = app.tr("render.light_backend_limit").to_string(); - let disabled = [(!cpu).then_some(reason.as_str()), legacy_gpu.then_some(legacy_reason.as_str())]; + let disabled = [(!cpu).then_some(reason.as_str()), None]; ui.add_enabled_ui(!raster, |ui| { let label = app.tr("render.lighting_source").to_string(); ui_kit::row(ui, &label, |ui| { @@ -413,9 +658,6 @@ pub(super) fn lighting(app: &mut SolveApp, ui: &mut egui::Ui) { if !cpu { note(app, ui, "render.lighting_preset_cpu"); } - if legacy_gpu { - note(app, ui, "render.light_backend_limit"); - } // RenderSetup has no saved rig identity. Do not invent a Rig row. }); let title = app.tr("render.lighting_shadows_section").to_string(); @@ -455,16 +697,14 @@ pub(super) fn lighting(app: &mut SolveApp, ui: &mut egui::Ui) { }); let title = app.tr("render.lighting_budget").to_string(); ui_kit::section(ui, "render:lighting:budget", &title, true, |ui| { - for (kind, key, limit) in [ - ("directional", if gpu { "render.light_type_sun" } else { "render.tree_directional" }, if gpu { 1 } else { 8 }), - ("area", "render.light_type_area", 4), - ("point", "render.light_type_point", 8), - ] { + for (kind, key, limit) in + [("directional", "render.tree_directional", 8), ("area", "render.light_type_area", 4), ("point", "render.light_type_point", 8)] + { let count = lights .iter() .filter(|l| if kind == "point" { matches!(l.geometry.kind(), "point" | "spot") } else { l.geometry.kind() == kind }) .count(); - let unsupported = raster || (gpu && kind == "point"); + let unsupported = raster; let label = app.tr(key).to_string(); ui.add_enabled_ui(!unsupported, |ui| { ui_kit::row(ui, &label, |ui| { @@ -492,9 +732,6 @@ pub(super) fn lighting(app: &mut SolveApp, ui: &mut egui::Ui) { }); }) }); - if gpu && kind == "point" { - note(app, ui, "render.light_gpu_punctual"); - } } note(app, ui, "render.lighting_budget_help"); add_menu(app, ui); @@ -506,41 +743,57 @@ pub(super) fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) { let gpu = app.render_workspace.view.method == ImageMethod::GpuRaytrace; let raster = app.render_workspace.view.method == ImageMethod::Raster; let lights = rows(app).unwrap_or_default(); - let legacy = gpu && lights.iter().filter(|l| l.geometry.kind() == "directional").count() > 1; let label = app.tr("render.tree_add_light").to_string(); - ui.add_enabled_ui(!raster && !legacy, |ui| { + ui.add_enabled_ui(!raster, |ui| { ui_kit::dropdown_menu(ui, "render:lighting:add", &label, |ui| { for (kind, key, cap) in [ ("area", "render.light_type_area", 4), ("point", "render.light_type_point", 8), - ("directional", if gpu { "render.light_type_sun" } else { "render.tree_directional" }, if gpu { 1 } else { 8 }), + ("spot", "render.light_type_spot", 8), + ("directional", "render.tree_directional", 8), ] { let count = lights .iter() - .filter(|l| if kind == "point" { matches!(l.geometry.kind(), "point" | "spot") } else { l.geometry.kind() == kind }) + .filter( + |l| if matches!(kind, "point" | "spot") { matches!(l.geometry.kind(), "point" | "spot") } else { l.geometry.kind() == kind }, + ) .count(); - let enabled = count < cap && !(gpu && kind == "point"); + let enabled = count < cap; let response = ui.add_enabled_ui(enabled, |ui| ui_kit::list_picker(ui, kind, app.tr(key), false)).inner; + crate::scenario::publish_target(&format!("render:lighting:add:{kind}"), response.rect); + if response.on_hover_text(app.tr("render.lighting_budget_help")).clicked() { + dispatch(app, "render.lights.add", None, Some(json!({"kind":kind}))); + ui.close(); + } + } + { + let compatible = gpu || app.render_workspace.view.raytrace.path.is_some(); + let directional = lights.iter().filter(|l| l.geometry.kind() == "directional").count(); + let finite = lights.iter().any(|l| matches!(l.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. })); + let response = ui + .add_enabled_ui(compatible && !finite && directional < 8, |ui| { + ui_kit::list_picker(ui, "sun", app.tr("render.light_type_sun"), false) + }) + .inner; + crate::scenario::publish_target("render:lighting:add:sun", response.rect); if response - .backing_on_hover_text(app.tr(if gpu && kind == "point" { "render.light_gpu_punctual" } else { "render.lighting_budget_help" })) + .backing_on_hover_text(app.tr(if compatible { "render.directional_sun_limit" } else { "render.cpu_celestial_path_required" })) .clicked() { - dispatch(app, "render.lights.add", None, Some(json!({"kind":kind}))); + let softness = (0.02 - 0.001) / (std::f64::consts::FRAC_PI_2 - 0.001); + dispatch(app, "render.lights.add", None, Some(json!({"kind":"directional","softness":softness}))); ui.close(); } } }); }); - if legacy { - note(app, ui, "render.light_backend_limit"); - } } fn review_preset(app: &mut SolveApp, preset: solidcraft_engine::render::job::LightingPreset) { match setups::snapshot(app) { Ok(mut setup) => { let source = setup.clone(); - if let Some(RenderJob::CpuRaytrace { options }) = &mut setup.job { + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job { options.lights = None; options.preset = Some(preset); app.render_workspace.view.lights.review = Some(Review { @@ -558,19 +811,16 @@ fn review_preset(app: &mut SolveApp, preset: solidcraft_engine::render::job::Lig } fn save_lighting(app: &mut SolveApp, setup: RenderSetup) -> Result<(), String> { - let selection = app.render_workspace.view.selection.clone(); - let visibility = app.render_workspace.view.lights.visibility.clone(); app.run("render.settings.set", json!({"name":app.render_workspace.view.name,"set":setup}))?; + // Full settings replacement has no source map. Respect loaded()'s proven- + // provenance policy instead of restoring visibility by reused ordinal IDs. setups::load(app); - app.render_workspace.view.selection = selection; - app.render_workspace.view.lights.visibility = visibility; - loaded(app); Ok(()) } fn update_cpu(app: &mut SolveApp, update: impl FnOnce(&mut CpuJob)) { let result = (|| { let mut setup = setups::snapshot(app)?; - if let Some(RenderJob::CpuRaytrace { options }) = &mut setup.job { + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job { update(options); } save_lighting(app, setup) @@ -626,14 +876,26 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { crate::scenario::publish_target("render:light:editor", ui.available_rect_before_wrap()); let kind = light.geometry.kind(); let gpu = app.render_workspace.view.method == ImageMethod::GpuRaytrace; - let blocked = app.render_workspace.view.method == ImageMethod::Raster - || (gpu && lights.iter().filter(|light| light.geometry.kind() == "directional").count() > 1); - let maximum_ev = if gpu { if kind == "area" { 1e6_f64.log2() } else { 1e8_f64.log2() } } else { 6.0 }; + let blocked = app.render_workspace.view.method == ImageMethod::Raster; + let finite_sun = matches!(light.geometry, Geometry::Directional { angular_radius_rad: Some(_), .. }); + let maximum_ev = if gpu && kind == "area" { + 1e6_f64.log2() + } else if finite_sun { + 1e8_f64.log2() + } else { + 6.0 + }; let type_key = match kind { "area" => "render.light_type_area", "spot" => "render.light_type_spot", "point" => "render.light_type_point", - _ => "render.light_type_sun", + _ => { + if finite_sun { + "render.light_type_sun" + } else { + "render.tree_directional" + } + } }; let aim = app.render_workspace.view.lights.aim.unwrap_or_else(|| product_centre(app)); let subject_size = subject_size(app); @@ -646,6 +908,12 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { (position_mm, [0.0; 3], [0.0; 3], [0.0; 3], reference_distance_mm, minimum_distance_mm) } }; + let (emitted_axis, inner_angle, outer_angle) = match light.geometry { + Geometry::Spot { emitted_axis, inner_half_angle_radians, outer_half_angle_radians, .. } => { + (emitted_axis, inner_half_angle_radians.to_degrees(), outer_half_angle_radians.to_degrees()) + } + _ => ([0.0, 0.0, -1.0], 0.2_f64.to_degrees(), 0.5_f64.to_degrees()), + }; let width = length(u); let softness = match light.geometry { Geometry::Directional { angular_radius_rad: Some(radius), .. } => radius.to_degrees(), @@ -672,31 +940,35 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { reference, minimum, aim, + emitted_axis, + inner_angle, + outer_angle, }); ui_kit::scope(ui, |ui| { ui_kit::row(ui, &name(app, light), |ui| { ui.add_enabled_ui(false, |ui| ui_kit::choice_chip(ui, "render:light:badge", app.tr(type_key), true)); }); if blocked { - note(app, ui, "render.light_backend_limit"); + note(app, ui, "render.method_limit_raster"); } ui.add_enabled_ui(!blocked, |ui| { let labels = [ app.tr("render.light_type_area").to_string(), app.tr("render.light_type_point").to_string(), - app.tr("render.light_type_sun").to_string(), + app.tr("render.light_type_spot").to_string(), + app.tr(if finite_sun { "render.light_type_sun" } else { "render.tree_directional" }).to_string(), ]; - let kinds = ["area", "point", "directional"]; + let kinds = ["area", "point", "spot", "directional"]; let mut selected = kinds.iter().position(|value| *value == kind).unwrap_or(1); - let reason = app.tr("render.light_gpu_punctual").to_string(); let budget_reason = app.tr("render.lighting_budget_help").to_string(); let areas = lights.iter().filter(|l| l.geometry.kind() == "area").count(); let points = lights.iter().filter(|l| matches!(l.geometry.kind(), "point" | "spot")).count(); let suns = lights.iter().filter(|l| l.geometry.kind() == "directional").count(); let disabled = [ (kind != "area" && areas >= 4).then_some(budget_reason.as_str()), - if gpu { Some(reason.as_str()) } else { (kind != "point" && kind != "spot" && points >= 8).then_some(budget_reason.as_str()) }, - (kind != "directional" && suns >= if gpu { 1 } else { 8 }).then_some(budget_reason.as_str()), + (kind != "point" && kind != "spot" && points >= 8).then_some(budget_reason.as_str()), + (kind != "point" && kind != "spot" && points >= 8).then_some(budget_reason.as_str()), + (kind != "directional" && suns >= 8).then_some(budget_reason.as_str()), ]; if ui_kit::segmented( ui, @@ -705,7 +977,7 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { ui_kit::Segments { compact: true, disabled: &disabled, - targets: &["render:light:type:area", "render:light:type:point", "render:light:type:directional"], + targets: &["render:light:type:area", "render:light:type:point", "render:light:type:spot", "render:light:type:directional"], ..Default::default() }, ) && let Some(chosen) = kinds.get(selected) @@ -713,12 +985,6 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { { dispatch(app, "render.lights.set", Some(id), Some(json!({"kind":chosen}))); } - if gpu { - note(app, ui, "render.light_gpu_punctual"); - } - if kind == "spot" { - note(app, ui, "render.lighting_spot_preserved"); - } slider_field(app, ui, id, "render.light_intensity", "intensity_ev", &mut draft.ev, -20.0..=maximum_ev, |v| format!("{v:+.1} EV"), true); slider_field( app, @@ -732,7 +998,7 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { true, ); note(app, ui, "render.light_temperature_help"); - let soft = kind == "area" || (kind == "directional" && gpu); + let soft = kind == "area" || finite_sun; let sun = kind == "directional"; // A sun displays its actual angular radius; areas display the size adapter. slider_field( @@ -742,7 +1008,13 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { "render.light_softness", if sun { "angular_radius_deg" } else { "softness" }, &mut draft.softness, - if sun { 0.001_f64.to_degrees()..=90.0 } else { 0.0..=1.0 }, + if finite_sun { + 0.001_f64.to_degrees()..=90.0 + } else if sun { + 0.0..=90.0 + } else { + 0.0..=1.0 + }, if sun { |v| format!("{v:.2}°") } else { |v| format!("{v:.2}") }, soft, ); @@ -849,6 +1121,15 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { vector_field(app, ui, id, "render.lighting_edge_v", "edge_v_mm", &mut draft.v, if gpu { -2e6..=2e6 } else { -1e6..=1e6 }, " mm"); }); } + if kind == "spot" { + let title = app.tr("render.spot_cone").to_string(); + ui_kit::section(ui, "render:light:cone", &title, true, |ui| { + vector_field(app, ui, id, "render.spot_axis", "emitted_axis", &mut draft.emitted_axis, -1e9..=1e9, ""); + field(app, ui, id, "render.spot_inner", "inner_half_angle_radians", &mut draft.inner_angle, 0.0..=90.0, 0.1, "°", true); + field(app, ui, id, "render.spot_outer", "outer_half_angle_radians", &mut draft.outer_angle, 0.0..=90.0, 0.1, "°", true); + note(app, ui, if gpu { "render.spot_gpu_help" } else { "render.spot_help" }); + }); + } if matches!(kind, "point" | "spot") { let title = app.tr("render.lighting_falloff").to_string(); ui_kit::section(ui, "render:light:falloff", &title, true, |ui| { @@ -892,21 +1173,15 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { let _ = app.run("render.lights.mute", json!({"id":id,"mute":muted})); } ui.horizontal(|ui| { - let cap = if kind == "area" { - 4 - } else if gpu { - 1 - } else { - 8 - }; + let cap = if kind == "area" { 4 } else { 8 }; let count = lights .iter() .filter( |l| if matches!(kind, "point" | "spot") { matches!(l.geometry.kind(), "point" | "spot") } else { l.geometry.kind() == kind }, ) .count(); - if ui_kit::button(ui, app.tr("render.light_duplicate"), ui_kit::Button::Enabled(!blocked && count < cap)) - .backing_on_hover_text(app.tr("render.lighting_budget_help")) + if ui_kit::button(ui, app.tr("render.light_duplicate"), ui_kit::Button::Enabled(!blocked && !finite_sun && count < cap)) + .backing_on_hover_text(app.tr(if finite_sun { "render.directional_sun_limit" } else { "render.lighting_budget_help" })) .clicked() { dispatch(app, "render.lights.duplicate", Some(id), None); @@ -974,19 +1249,20 @@ fn vector_field( suffix: &str, ) { let label = app.tr(label).to_string(); - ui_kit::row(ui, &label, |ui| { - let mut changed = false; - ui.horizontal(|ui| { - for (index, component) in value.iter_mut().enumerate() { - let response = ui_kit::number_field(ui, component, range.clone(), 0.1, suffix); - crate::scenario::publish_target(&format!("render:light:{key}:{index}"), response.rect); - changed |= accepted(&response); - } + // Each coordinate needs the full control column: three content-sized + // DragValues can extend beyond a narrow inspector as their text grows. + // Separate axis rows retain the standard parser, focus and accessible label. + let mut changed = false; + for ((index, component), axis) in value.iter_mut().enumerate().zip(["X", "Y", "Z"]) { + ui_kit::row(ui, &format!("{label} {axis}"), |ui| { + let response = ui_kit::number_field(ui, component, range.clone(), 0.1, suffix); + crate::scenario::publish_target(&format!("render:light:{key}:{index}"), response.rect); + changed |= accepted(&response); }); - if changed && value.iter().all(|v| v.is_finite() && range.contains(v)) { - dispatch(app, "render.lights.set", Some(id), Some(json!({(key):*value}))); - } - }); + } + if changed && value.iter().all(|v| v.is_finite() && range.contains(v)) { + dispatch(app, "render.lights.set", Some(id), Some(json!({(key):*value}))); + } } fn accepted(response: &egui::Response) -> bool { response.drag_stopped() || (response.changed() && (response.has_focus() || response.lost_focus())) @@ -1016,9 +1292,20 @@ fn field( let response = ui_kit::number_field(ui, value, range.clone(), speed, suffix); crate::scenario::publish_target(&format!("render:light:{key}"), response.rect); if accepted(&response) && value.is_finite() && range.contains(value) { - let patch = if key == "distance_size" { json!({"distance_mm":*value * subject_size(app)}) } else { json!({(key):*value}) }; + let patch = if key == "distance_size" { + json!({"distance_mm":*value * subject_size(app)}) + } else if matches!(key, "inner_half_angle_radians" | "outer_half_angle_radians") { + json!({(key):value.to_radians()}) + } else { + json!({(key):*value}) + }; dispatch(app, "render.lights.set", Some(id), Some(patch)); } }) }); } + +#[cfg(test)] +pub(super) fn editor_draft(app: &SolveApp) -> Option<(String, u64, f64, f64)> { + app.render_workspace.view.lights.draft.as_ref().map(|draft| (draft.id.clone(), draft.revision, draft.ev, draft.softness)) +} diff --git a/crates/ui-egui/src/render_workspace_live.rs b/crates/ui-egui/src/render_workspace_live.rs new file mode 100644 index 000000000..554f0b974 --- /dev/null +++ b/crates/ui-egui/src/render_workspace_live.rs @@ -0,0 +1,673 @@ +//! Automatic, isolated product-image feedback. The original session owns final results only. +//! A scratch session reuses the same commands, immutable model and installed host pools. +use std::hash::{Hash, Hasher}; +use std::sync::{ + Arc, Weak, + atomic::{AtomicBool, Ordering}, + mpsc, +}; + +use egui::{Context, Rect, TextureHandle, emath::GuiRounding as _}; +use serde_json::{Value, json}; +use solidcraft_engine::{ + Session, + doc::Document, + render::job::{CpuProgressiveOptions, JobHandle, JobId, Phase}, +}; + +use super::{ImageMethod, ribbon}; +use crate::{SolveApp, ui_kit}; + +const LONGEST_EDGE: u32 = 512; +const EDIT_DELAY_SECONDS: f64 = 0.2; + +#[derive(Clone)] +struct Identity { + document: Weak, + revision: u64, + model: Weak, + moves: std::collections::BTreeMap, + visibility: u64, + shot: String, + request: Value, +} +impl Identity { + fn same(&self, other: &Self) -> bool { + Weak::ptr_eq(&self.document, &other.document) + && self.revision == other.revision + && Weak::ptr_eq(&self.model, &other.model) + && self.moves == other.moves + && self.visibility == other.visibility + && self.shot == other.shot + && self.request == other.request + } +} + +struct OwnedJob { + // Keep the scratch session alive: dropping its Jobs cancels its live handles. + _owner: Session, + handle: JobHandle, + generation: u64, + revision: u64, + target: u32, +} +struct Pending { + receiver: mpsc::Receiver>, + cancelled: Arc, + generation: u64, +} +struct Picture { + generation: u64, + job: JobId, + sequence: u32, + samples: u32, + complete: bool, + adaptive: Option, + executor: solidcraft_engine::render::ExecutorId, + /// Captured alongside this texture from the same validated immutable frame. + scene_generation: u64, + size: [u32; 2], + texture: TextureHandle, +} +#[derive(Default)] +pub(crate) struct State { + identity: Option, + generation: u64, + due: f64, + attempted: bool, + pending: Option, + running: Option, + picture: Option, + error: Option, + suspended: bool, + draining: Vec, + final_request: Option, +} +impl Drop for State { + fn drop(&mut self) { + self.cancel_work(); + } +} +impl State { + pub(super) fn retire_document(&mut self) { + self.reset(); + self.final_request = None; + self.suspended = true; + } + fn cancel_work(&mut self) { + if let Some(pending) = &self.pending { + pending.cancelled.store(true, Ordering::Release); + } + if let Some(job) = self.running.take() { + let _ = job.handle.cancel(); + self.draining.push(job.handle.clone()); + } + } + fn reset(&mut self) { + self.cancel_work(); + self.identity = None; + self.attempted = false; + self.picture = None; + self.error = None; + } + fn observe(&mut self, identity: Identity, now: f64) { + if self.identity.as_ref().is_some_and(|old| old.same(&identity)) { + return; + } + self.cancel_work(); + self.generation = self.generation.saturating_add(1); + self.identity = Some(identity); + self.due = now + EDIT_DELAY_SECONDS; + self.attempted = false; + self.error = None; + } + fn poll_capture(&mut self) { + let Some(pending) = &self.pending else { return }; + let answer = match pending.receiver.try_recv() { + Ok(answer) => answer, + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => Err(crate::i18n::tr("render.live.worker_stopped").into()), + }; + let generation = pending.generation; + let cancelled = pending.cancelled.load(Ordering::Acquire); + self.pending = None; + match answer { + Ok(job) if generation == self.generation && !cancelled && !self.suspended => self.running = Some(job), + Ok(job) => { + let _ = job.handle.cancel(); + self.draining.push(job.handle.clone()); + } + Err(error) if generation == self.generation && !cancelled && !self.suspended => self.error = Some(error), + Err(_) => {} + } + } + fn reap_draining(&mut self) { + self.draining.retain(|handle| !handle.work_released()); + } + fn poll_pixels(&mut self, ctx: &Context) { + let Some(job) = &self.running else { return }; + if job.generation != self.generation { + return; + } + let result = (|| -> Result, String> { + let status = job.handle.status().map_err(|e| e.to_string())?; + if status.job != job.handle.id() || status.scene_generation != job.revision { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + if let Some(error) = &status.error { + return Err(error.to_string()); + } + let limits = if status.resolved.executor.as_str() == "gpu-path" { + solidcraft_engine::render::job::GPU_PATH_LIMITS + } else { + super::captured_image_limits(&status.request) + }; + let current = self.picture.as_ref().filter(|picture| picture.generation == job.generation && picture.job == job.handle.id()); + let load = |info: &solidcraft_engine::render::job::FrameInfo, png: &[u8], sequence, samples, complete, adaptive| { + if info.job != job.handle.id() + || info.scene_generation != job.revision + || info.executor != status.resolved.executor + || (info.width, info.height) != (status.request.width, status.request.height) + { + return Err(crate::i18n::tr("render.error_provisional_identity").to_string()); + } + let image = super::decode_render_image(png, info.width, info.height, limits, ctx.input(|i| i.max_texture_side))?; + Ok(Picture { + generation: job.generation, + job: info.job, + sequence, + samples, + complete, + adaptive, + executor: info.executor.clone(), + scene_generation: info.scene_generation, + size: [info.width, info.height], + texture: ctx.load_texture("sc_render_live", image, egui::TextureOptions::LINEAR), + }) + }; + if let Some(frame) = job.handle.frame().map_err(|e| e.to_string())? { + if current.is_some_and(|picture| picture.complete) { + return Ok(None); + } + let adaptive = super::captured_adaptive_preview(&status, job.target)?; + return load(&frame.info, frame.png(), current.map_or(1, |picture| picture.sequence), job.target, true, adaptive).map(Some); + } + if let Some(preview) = job.handle.preview().map_err(|e| e.to_string())? { + if current.is_some_and(|picture| picture.sequence >= preview.info.frame_sequence) { + return Ok(None); + } + let adaptive = super::captured_adaptive_preview(&status, preview.info.samples_per_pixel)?; + if preview.info.frame_sequence == 0 + || preview.info.samples_per_pixel == 0 + || preview.info.samples_per_pixel >= job.target + || preview.info.adaptive != adaptive + { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + return load(&preview.info.frame, preview.png(), preview.info.frame_sequence, preview.info.samples_per_pixel, false, adaptive) + .map(Some); + } + if let Some(reason) = status.preview_unavailable_reason { + return Err(reason.into()); + } + if matches!(status.progress.phase, Phase::Cancelled | Phase::Failed) { + return Err(crate::i18n::tr("render.live.stopped").into()); + } + Ok(None) + })(); + match result { + Ok(Some(picture)) => { + self.picture = Some(picture); + ctx.request_repaint(); + } + Ok(None) => {} + Err(error) => { + self.error = Some(error); + self.cancel_work(); + } + } + } +} + +fn enabled(app: &SolveApp) -> bool { + !cfg!(target_arch = "wasm32") && !app.preferences.render_legacy_image_defaults && app.render_workspace.view.method != ImageMethod::Raster +} +fn rounded_size(rect: Rect) -> [u32; 2] { + let width = f64::from(rect.width().max(1.0)); + let height = f64::from(rect.height().max(1.0)); + let longest = width.max(height); + let scale = (f64::from(LONGEST_EDGE) / longest).min(1.0); + [(width * scale).round().clamp(1.0, f64::from(LONGEST_EDGE)) as u32, (height * scale).round().clamp(1.0, f64::from(LONGEST_EDGE)) as u32] +} +fn size(app: &SolveApp, rect: Rect) -> [u32; 2] { + let [width, height] = [app.render_workspace.view.draft.width, app.render_workspace.view.draft.height]; + if width == 0 || height == 0 { + // Request validates original intent before any temporary live-size copy. + return rounded_size(rect); + } + let (mut a, mut b) = (width, height); + while b != 0 { + (a, b) = (b, a % b); + } + let unit = [width / a, height / a]; + let maximum_scale = LONGEST_EDGE / unit[0].max(unit[1]); + if maximum_scale > 0 { + // Exact common ratios (e.g. 160:120→4:3) stay identical through every + // free-canvas shape. Never round width/height independently when an + // admitted integer multiple can preserve the output camera exactly. + let scale = (f64::from(rect.width()) / f64::from(unit[0])) + .min(f64::from(rect.height()) / f64::from(unit[1])) + .floor() + .clamp(1.0, f64::from(maximum_scale)) as u32; + return [unit[0] * scale, unit[1] * scale]; + } + // Coprime authored dimensions can exceed the 512-pixel live ceiling even + // though the final job is valid. Use the nearest bounded pixel dimensions; + // projection_rect applies that captured aspect too, without stretching. + rounded_size(super::shot::frame_rect(f64::from(width) / f64::from(height), rect).unwrap_or(rect)) +} + +/// Match product navigation, picking and pixels to the exact integer live-capture aspect. +/// At most a pixel of letterboxing is introduced instead of stretching the rendered image. +pub(crate) fn projection_rect(app: &SolveApp, rect: Rect) -> Rect { + if !enabled(app) || !rect.is_finite() || !rect.is_positive() { + return rect; + } + let [width, height] = size(app, rect); + super::shot::frame_rect(f64::from(width) / f64::from(height), rect).unwrap_or(rect) +} + +/// Build a separate, labelled live-size request. Final size, AA and saved intent are restored +/// before returning, including on refusal. Effects are never removed to obtain a preview. +fn request(app: &mut SolveApp) -> Result { + super::image_host(app, app.render_workspace.view.method)?; + if app.session.model.is_stale() { + return Err(app.tr("render.image_scene_stale").into()); + } + let old_size = [app.render_workspace.view.draft.width, app.render_workspace.view.draft.height]; + if old_size.contains(&0) { + return Err(app.tr("render.live.invalid_size").into()); + } + // A labelled low-resolution live copy must not make invalid authored output + // dimensions/sampling appear valid. Refuse original intent before scaling. + let original = (u64::from(old_size[0]), u64::from(old_size[1])); + if super::cpu::image_limits(app).fit(original.0, original.1, None) != Some(original) { + return Err(super::inspector::size_limit_reason(app, old_size[0], old_size[1])); + } + super::cpu::validate_progressive_image(app)?; + let old_sampling = app.render_workspace.view.raytrace.progressive; + let old_primary = app.render_workspace.view.raytrace.primary_samples; + let old_reflection_samples = app.render_workspace.view.raytrace.reflections.as_ref().map(|options| options.samples); + let viewport = + app.viewport.rect.filter(|rect| rect.is_finite() && rect.is_positive()).ok_or_else(|| app.tr("render.live.waiting_canvas").to_string())?; + let canvas = super::shot::render_rect(app, viewport); + let live_size = size(app, canvas); + app.render_workspace.view.draft.width = live_size[0]; + app.render_workspace.view.draft.height = live_size[1]; + if app.render_workspace.view.method == ImageMethod::CpuRaytrace && old_sampling.is_none() { + app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions::default()); + app.render_workspace.view.raytrace.primary_samples = 1; + if let Some(reflections) = &mut app.render_workspace.view.raytrace.reflections { + // A live film ordinal supplies a fresh reflected camera sample. Preserve the + // authored fixed image's attempt count when this temporary copy is restored. + reflections.samples = 1; + } + } + let result = super::image_request(app); + app.render_workspace.view.draft.width = old_size[0]; + app.render_workspace.view.draft.height = old_size[1]; + app.render_workspace.view.raytrace.progressive = old_sampling; + app.render_workspace.view.raytrace.primary_samples = old_primary; + if let (Some(reflections), Some(samples)) = (&mut app.render_workspace.view.raytrace.reflections, old_reflection_samples) { + reflections.samples = samples; + } + result +} +fn target(request: &Value) -> u32 { + let samples = request + .pointer("/settings/job/options/progressive/samples_per_pixel") + .or_else(|| request.pointer("/raytrace/progressive/samples_per_pixel")) + .or_else(|| request.pointer("/settings/job/options/samples")) + .or_else(|| request.get("samples")) + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .unwrap_or(1); + let pilots = request + .pointer("/settings/job/options/adaptive/pilot_samples") + .or_else(|| request.pointer("/raytrace/adaptive/pilot_samples")) + .or_else(|| request.pointer("/adaptive/pilot_samples")) + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .unwrap_or(0); + samples.checked_add(pilots).unwrap_or(0) +} + +#[cfg(not(target_arch = "wasm32"))] +fn capture(app: &SolveApp, identity: &Identity, generation: u64) -> Result { + let mut owner = app.session.scratch(); + let request = identity.request.clone(); + let revision = identity.revision; + let target = target(&request); + let scope = solidcraft_engine::io::vfs::current_scope(); + let cancelled = Arc::new(AtomicBool::new(false)); + let stop = cancelled.clone(); + let (sender, receiver) = mpsc::channel(); + solidcraft_engine::kernel::kernel_thread("render-live-capture") + .spawn(move || { + let result = solidcraft_engine::io::vfs::scoped(scope, || { + if stop.load(Ordering::Acquire) { + return Err(crate::i18n::tr("render.live.stopped").to_string()); + } + let reply = owner.execute("render.start", &request).map_err(|e| e.to_string())?; + let id = serde_json::from_value(reply["job"].clone()).map_err(|e| format!("{e}"))?; + let handle = owner.render_job_handle(id).map_err(|e| e.to_string())?; + if stop.load(Ordering::Acquire) { + let _ = handle.cancel(); + } + // The UI must keep this handle until work_released, even if cancellation + // raced submission. A terminal/cancelled status alone does not release work. + Ok(OwnedJob { _owner: owner, handle, generation, revision, target }) + }); + let _ = sender.send(result); + }) + .map_err(|e| e.to_string())?; + Ok(Pending { receiver, cancelled, generation }) +} + +pub(crate) fn tick(app: &mut SolveApp, ctx: &Context) { + let now = ctx.input(|input| input.time); + tick_at(app, ctx, now); +} +fn tick_at(app: &mut SolveApp, ctx: &Context, now: f64) { + let mut state = std::mem::take(&mut app.render_workspace.live); + state.poll_capture(); + state.reap_draining(); + if state.final_request.is_some() { + state.cancel_work(); + state.suspended = true; + if state.pending.is_none() && state.draining.is_empty() { + let pending = state.final_request.take(); + app.render_workspace.live = state; + if let Some(pending) = pending + && let Err(error) = ribbon::submit_deferred(app, pending) + { + app.set_status(error, true); + } + } else { + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + app.render_workspace.live = state; + } + return; + } + if !enabled(app) || !super::active(app) { + state.reset(); + state.suspended = true; + state.poll_capture(); + if state.pending.is_some() || !state.draining.is_empty() { + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + } + app.render_workspace.live = state; + return; + } + let request = request(app); + let mut visibility = std::collections::hash_map::DefaultHasher::new(); + app.session.visibility.hidden_bodies.hash(&mut visibility); + app.session.visibility.hidden_occurrences.hash(&mut visibility); + let identity = Identity { + document: Arc::downgrade(&app.session.doc), + revision: app.session.revision, + model: Arc::downgrade(&app.session.model.state()), + moves: app.session.pending_moves.clone(), + visibility: visibility.finish(), + shot: app.render_workspace.view.name.clone(), + request: request.as_ref().cloned().unwrap_or_else(|error| json!({"error":error})), + }; + state.observe(identity, now); + let suspended = app.render_workspace.view.live_paused + || ribbon::busy(app) + || app.render_workspace.view.result + || app.render_workspace.view.compare.is_some() + || app.file_load.busy() + || app.file_picker.is_some() + || app.saving.is_some() + || app.tool.is_some() + || app.dialog.is_some(); + if suspended { + state.cancel_work(); + state.attempted = false; + state.suspended = true; + state.poll_capture(); + if state.pending.is_some() || !state.draining.is_empty() { + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + } + app.render_workspace.live = state; + return; + } + state.suspended = false; + state.poll_capture(); + if let Err(error) = request { + state.error = Some(error); + state.attempted = true; + } + state.poll_pixels(ctx); + if state.pending.is_none() && state.running.is_none() && state.draining.is_empty() && !state.attempted && now >= state.due { + state.attempted = true; + #[cfg(not(target_arch = "wasm32"))] + if let Some(identity) = &state.identity { + match capture(app, identity, state.generation) { + Ok(pending) => state.pending = Some(pending), + Err(error) => state.error = Some(error), + } + } + } + if state.pending.is_some() + || !state.draining.is_empty() + || (state.running.is_some() && !state.picture.as_ref().is_some_and(|picture| picture.complete && picture.generation == state.generation)) + || !state.attempted + { + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + } + app.render_workspace.live = state; +} + +pub(crate) fn set_paused(app: &mut SolveApp, paused: bool) { + app.render_workspace.view.live_paused = paused; + if paused { + app.render_workspace.live.cancel_work(); + } else { + app.render_workspace.live.identity = None; + app.render_workspace.live.attempted = false; + } +} +/// Preparation owns the same live-release priority as an explicit final. The +/// original pending/running owners stay here until their release acknowledgements. +pub(super) fn suspend_for_preparation(app: &mut SolveApp) { + let state = &mut app.render_workspace.live; + state.cancel_work(); + state.suspended = true; + state.identity = None; + state.attempted = false; + state.poll_capture(); + state.reap_draining(); +} +pub(super) fn preparation_ready(app: &SolveApp) -> bool { + let state = &app.render_workspace.live; + state.pending.is_none() && state.running.is_none() && state.draining.is_empty() +} +pub(super) fn defer_final(app: &mut SolveApp, request: ribbon::PendingFinal) -> bool { + let state = &mut app.render_workspace.live; + state.cancel_work(); + state.suspended = true; + state.identity = None; + state.attempted = false; + state.reap_draining(); + if state.pending.is_some() || !state.draining.is_empty() { + state.final_request = Some(request); + true + } else { + false + } +} +pub(super) fn final_pending(app: &SolveApp) -> bool { + app.render_workspace.live.final_request.is_some() +} +pub(super) fn cancel_final(app: &mut SolveApp) -> bool { + app.render_workspace.live.final_request.take().is_some() +} +fn picture_current(app: &SolveApp) -> bool { + let state = &app.render_workspace.live; + let Some(identity) = &state.identity else { return false }; + let Some(viewport) = app.viewport.rect.filter(|rect| rect.is_finite() && rect.is_positive()) else { return false }; + let [width, height] = size(app, super::shot::render_rect(app, viewport)); + let mut visibility = std::collections::hash_map::DefaultHasher::new(); + app.session.visibility.hidden_bodies.hash(&mut visibility); + app.session.visibility.hidden_occurrences.hash(&mut visibility); + // Navigation runs after the frame's lifecycle tick. Check geometry/camera again before + // picking or painting feedback, so this frame cannot overlay a new camera on old pixels. + enabled(app) + && state.picture.as_ref().is_some_and(|picture| picture.generation == state.generation) + && state.error.is_none() + && Weak::ptr_eq(&identity.document, &Arc::downgrade(&app.session.doc)) + && identity.revision == app.session.revision + && Weak::ptr_eq(&identity.model, &Arc::downgrade(&app.session.model.state())) + && identity.moves == app.session.pending_moves + && identity.visibility == visibility.finish() + && identity.request.pointer("/settings/camera") == Some(&json!(app.cam)) + && identity.request.pointer("/settings/width").and_then(Value::as_u64) == Some(u64::from(width)) + && identity.request.pointer("/settings/height").and_then(Value::as_u64) == Some(u64::from(height)) +} +pub(crate) fn picking_current(app: &SolveApp) -> bool { + let state = &app.render_workspace.live; + !enabled(app) || state.picture.is_none() || picture_current(app) +} +/// Terminal status precedes native cleanup. Live admission waits for that final work too. +pub(super) fn drain_final(app: &mut SolveApp, handle: JobHandle) { + if !handle.work_released() { + app.render_workspace.live.draining.push(handle); + } +} +pub(crate) fn paint(app: &mut SolveApp, ui: &egui::Ui, rect: Rect) { + if !enabled(app) { + return; + } + if let Some(picture) = &app.render_workspace.live.picture { + let aspect = f64::from(picture.size[0]) / f64::from(picture.size[1].max(1)); + if let Some(image) = super::shot::frame_rect(aspect, rect) { + let source = super::displayed::Source { + job: picture.job, + scene_generation: picture.scene_generation, + width: picture.size[0], + height: picture.size[1], + kind: if picture.complete { super::displayed::Kind::LiveFinal } else { super::displayed::Kind::LivePreview }, + frame_sequence: Some(picture.sequence), + samples_per_pixel: Some(picture.samples), + adaptive: picture.adaptive, + }; + egui::Image::new(&picture.texture).paint_at(ui, image); + // Image::paint_at rounds to physical pixels before emitting its image shape. + app.render_workspace.displayed.record(ui.painter(), image.round_to_pixels(ui.pixels_per_point()), source); + } + } +} +pub(crate) fn has_picture(app: &SolveApp) -> bool { + enabled(app) && app.render_workspace.live.picture.is_some() +} +/// Describe the image that is actually painted, including a retained previous capture. +/// The selected draft method cannot rename pixels produced by another executor. +pub(crate) fn source_note(app: &SolveApp) -> (String, &'static str) { + let Some(picture) = app.render_workspace.live.picture.as_ref().filter(|_| has_picture(app)) else { + return (app.tr("render.stage_preview_note").into(), "render.preview_lighting_help"); + }; + let method_matches = matches!( + (picture.executor.as_str(), app.render_workspace.view.method), + ("cpu-raytrace", ImageMethod::CpuRaytrace) | ("gpu-path", ImageMethod::GpuRaytrace) + ); + let current = method_matches && picture_current(app); + (source_text(app, picture.executor.as_str(), current), if current { "render.live.quality_help" } else { "render.live.source_outdated_help" }) +} + +pub(super) fn source_text(app: &SolveApp, executor: &str, current: bool) -> String { + let method = match executor { + "cpu-raytrace" => app.tr("render.method_cpu"), + "gpu-path" => app.tr("render.method_gpu"), + _ => executor, + }; + crate::i18n::format(if current { "render.live.source_current" } else { "render.live.source_outdated" }, &[("method", method)]) +} + +pub(crate) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + if !enabled(app) { + return; + } + let state = &app.render_workspace.live; + let status = if app.render_workspace.view.live_paused { + app.tr(if state.picture.as_ref().is_some_and(|picture| picture.generation != state.generation) { + "render.live.paused_outdated" + } else { + "render.live.paused" + }) + .to_string() + } else if let Some(error) = &state.error { + crate::i18n::format("render.live.refused", &[("reason", error)]) + } else if let Some(picture) = &state.picture { + if picture.generation == state.generation && !state.suspended { + if let Some(adaptive) = picture.adaptive { + crate::i18n::format( + "render.live.adaptive", + &[ + ("width", &picture.size[0].to_string()), + ("height", &picture.size[1].to_string()), + ("progress", &super::adaptive_preview_label(app, adaptive)), + ], + ) + } else { + let target = state.running.as_ref().map_or(picture.samples, |job| job.target); + crate::i18n::format( + "render.live.samples", + &[ + ("current", &picture.samples.to_string()), + ("target", &target.to_string()), + ("width", &picture.size[0].to_string()), + ("height", &picture.size[1].to_string()), + ], + ) + } + } else { + app.tr("render.live.updating").into() + } + } else { + app.tr("render.live.updating").into() + }; + let paused = app.render_workspace.view.live_paused; + let label = app.tr(if paused { "render.live.resume" } else { "render.live.pause" }).to_string(); + let response = ui_kit::button(ui, &label, ui_kit::Button::Normal); + crate::scenario::publish_target("render:live:pause", response.rect); + if response.clicked() { + let _ = app.run("view.render_live", json!({"paused":!paused})); + } + let max_width = ui.available_width().min(crate::theme::Tokens::get().control_height * 10.0); + let mut help = format!("{status}\n\n{}", app.tr("render.live.quality_help")); + if app.render_workspace.live.picture.as_ref().is_some_and(|picture| picture.adaptive.is_some()) { + help.push_str("\n\n"); + help.push_str(app.tr("render.adaptive.preview_help")); + } + let note = ui_kit::StageBar::note_bounded(ui, &status, max_width).on_hover_text(help); + crate::scenario::publish_target("render:live:status", note.rect); + ui_kit::StageBar::separator(ui); +} + +pub(super) fn inspect(app: &SolveApp) -> Value { + let state = &app.render_workspace.live; + let is_current = picture_current(app); + json!({"enabled":enabled(app),"paused":app.render_workspace.view.live_paused,"generation":state.generation,"draining":state.draining.len(),"final_pending":state.final_request.is_some(),"suspended":state.suspended,"pending":state.pending.is_some(),"running":state.running.is_some(),"error":state.error, + "target":state.running.as_ref().map(|job|job.target).or_else(||state.identity.as_ref().map(|identity|target(&identity.request))), + "current":state.picture.as_ref().map(|picture|picture.samples),"is_current":is_current,"stale":state.picture.is_some() && !is_current, + "job":state.running.as_ref().map(|job|job.handle.id()).or_else(||state.picture.as_ref().map(|picture|picture.job)),"samples":state.picture.as_ref().map(|picture|picture.samples), + "sequence":state.picture.as_ref().map(|picture|picture.sequence),"request":state.identity.as_ref().map(|identity| &identity.request), + "adaptive":state.picture.as_ref().and_then(|picture|picture.adaptive), + "hash":state.running.as_ref().and_then(|job| job.handle.frame().ok().flatten()).map(|frame| frame.info.png_sha256.clone()),"complete":is_current && state.picture.as_ref().is_some_and(|picture|picture.complete)}) +} +#[cfg(test)] +pub(super) fn advance(app: &mut SolveApp, ctx: &Context, now: f64) { + tick_at(app, ctx, now); +} diff --git a/crates/ui-egui/src/render_workspace_materials.rs b/crates/ui-egui/src/render_workspace_materials.rs index 687975841..f2a93fb84 100644 --- a/crates/ui-egui/src/render_workspace_materials.rs +++ b/crates/ui-egui/src/render_workspace_materials.rs @@ -1,5 +1,5 @@ -//! Transient body-level optical overrides for the captured GPU image request. -//! The model's appearances, physical material cards and saved setups are not changed. +//! Shared body-level optical editing: transient request overlays and explicit +//! stable saved bindings. Engineering geometry/materials never change here. use solidcore_record::Vec3; use std::sync::{Arc, Weak}; @@ -97,7 +97,7 @@ impl Default for Coat { } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub(super) struct Maps { pub color: String, pub normal: String, @@ -136,6 +136,9 @@ pub(super) struct Binding { pub maps_enabled: bool, pub maps: Maps, replace_saved_optics: bool, + saved_source: Option, + saved_coat_source: Option, + coat_edited: bool, } impl Binding { pub(super) fn new(target: Target, app: &SolveApp) -> Self { @@ -151,14 +154,101 @@ impl Binding { maps_enabled: false, maps: Maps::default(), replace_saved_optics: false, + saved_source: None, + saved_coat_source: None, + coat_edited: false, + } + } + pub(super) fn from_saved(target: Target, app: &SolveApp, optics: solidcraft_engine::doc::render_optics::OpticalMaterial) -> Self { + let mut binding = Self::new(target, app); + binding.saved_source = Some(optics); + binding.glass_enabled = true; + binding.glass = Glass { + recipe: None, + ior: optics.ior, + absorption: optics.absorption_per_mm, + boundary: match optics.boundary { + solidcraft_engine::doc::render_optics::OpticalBoundary::ThinSheet => Boundary::Thin, + solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedBox => Boundary::Box, + solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedMesh => Boundary::Closed, + }, + thickness: if optics.boundary == solidcraft_engine::doc::render_optics::OpticalBoundary::ThinSheet { optics.thickness_mm } else { 1.0 }, + shadows: optics.shadow_transmission, + subsurface: optics.subsurface, + }; + binding + } + fn hydrate_coat(&mut self, coat: solidcraft_engine::doc::render_coat::CoatMaterial) { + self.saved_coat_source = Some(coat); + self.coat_edited = false; + self.coat_enabled = true; + self.coat = Coat { weight: coat.weight, roughness: coat.roughness, ior: coat.ior }; + } + fn coat_has_local_changes(&self) -> bool { + self.coat_edited + || if let Some(saved) = self.saved_coat_source { + !self.enabled || !self.coat_enabled || self.glass_enabled || self.coat_material() != saved + } else { + self.coat_enabled + } + } + fn has_local_map_intent(&self) -> bool { + self.maps_enabled || self.maps != Maps::default() + } + fn coat_material(&self) -> solidcraft_engine::doc::render_coat::CoatMaterial { + solidcraft_engine::doc::render_coat::CoatMaterial { weight: self.coat.weight, roughness: self.coat.roughness, ior: self.coat.ior } + } + fn optics(&self) -> solidcraft_engine::doc::render_optics::OpticalMaterial { + solidcraft_engine::doc::render_optics::OpticalMaterial { + ior: self.glass.ior, + absorption_per_mm: self.glass.absorption, + boundary: match self.glass.boundary { + Boundary::Thin => solidcraft_engine::doc::render_optics::OpticalBoundary::ThinSheet, + Boundary::Box => solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedBox, + Boundary::Closed => solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedMesh, + }, + thickness_mm: if self.glass.boundary == Boundary::Thin { self.glass.thickness } else { 0.0 }, + shadow_transmission: self.glass.shadows, + subsurface: self.glass.subsurface, } } fn current(&self, app: &SolveApp) -> bool { self.revision == app.session.revision && Weak::ptr_eq(&self.document, &Arc::downgrade(&app.session.doc)) && !app.session.model.is_stale() } fn active(&self) -> bool { + if let Some(saved) = self.saved_source { + // Saved edits become a prospective stable request overlay, never + // an ordinal override or a silent return to the old saved values. + return !self.enabled || !self.glass_enabled || self.coat_enabled || self.maps_enabled || self.optics() != saved; + } + if let Some(saved) = self.saved_coat_source { + return !self.enabled || !self.coat_enabled || self.glass_enabled || self.maps_enabled || self.coat_material() != saved; + } self.enabled && (self.glass_enabled || self.coat_enabled || self.maps_enabled) } + pub(super) fn has_unsaved_coat_intent(&self) -> bool { + // Unchanged saved coats never allocate a local binding on paint. A row + // retained here carries a coat edit or independent local map draft. + self.coat_enabled || self.saved_coat_source.is_some() || self.coat_edited + } + pub(super) fn has_runtime_intent(&self) -> bool { + // Stable Glass uses the same prospective settings capture as coats. + // Unknown identities and file maps retain the ordinal runtime route. + if self.saved_source.is_none() && self.glass_enabled && self.target.stable_target.is_some() && !self.coat_enabled && !self.maps_enabled { + return false; + } + if self.saved_coat_source.is_some() || self.coat_enabled || self.coat_edited { + self.saved_source.is_none() && (self.glass_enabled || self.maps_enabled) + } else { + self.saved_source.is_none() + } + } + fn stable_optics(&self) -> bool { + self.saved_source.is_some() || (self.glass_enabled && self.target.stable_target.is_some()) + } + pub(super) fn has_unsaved_optics_intent(&self) -> bool { + self.stable_optics() && (self.saved_source.is_none() || self.active()) + } } #[derive(Clone, Debug, Default)] @@ -178,6 +268,7 @@ pub(super) struct View { #[derive(Clone, Debug)] struct PendingRemoval { + coat: bool, name: String, target: solidcraft_engine::doc::render_surface::RenderBodyTarget, revision: u64, @@ -204,7 +295,16 @@ pub(super) fn read_targets(app: &mut SolveApp) -> Result, String> { pub(super) fn revalidate(app: &mut SolveApp, binding: &mut Binding) -> Result<(), String> { let targets = read_targets(app)?; - if !targets.contains(&binding.target) { + if (binding.coat_enabled || binding.saved_coat_source.is_some() || binding.coat_edited) + && let Some(stable) = &binding.target.stable_target + { + let mut matches = targets.iter().filter(|target| target.stable_target.as_ref() == Some(stable)); + let target = matches.next().cloned().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; + if matches.next().is_some() { + return Err(app.tr("render.material_target_missing").into()); + } + binding.target = target; + } else if !targets.contains(&binding.target) { return Err(app.tr("render.material_target_missing").to_string()); } binding.revision = app.session.revision; @@ -228,33 +328,170 @@ pub(super) fn refresh_render_revision(app: &mut SolveApp) { .iter() .map(|binding| sources.same_model_source(app, &binding.document) && targets.contains(&binding.target)) .collect(); + let saved = app.session.doc.render.setups.get(&app.render_workspace.view.name).map(|setup| &setup.coats); for (binding, eligible) in app.render_workspace.view.materials.bindings.iter_mut().zip(eligible) { if eligible { binding.revision = app.session.revision; binding.document = Arc::downgrade(&app.session.doc); + // Stable source identity was proved above. Only unedited coat fields + // may follow saved Undo/Redo/replacement; independent map drafts stay. + if !binding.coat_has_local_changes() && !binding.glass_enabled { + let current = + saved.and_then(|rows| rows.iter().find(|row| binding.target.stable_target.as_ref() == Some(&row.target))).map(|row| row.coat); + if let Some(coat) = current { + binding.hydrate_coat(coat); + } else if binding.saved_coat_source.is_some() { + binding.saved_coat_source = None; + binding.coat_enabled = false; + } + } } } } +/// Overlay stable Glass drafts into a captured request only. Explicit binding +/// remains the sole save action; ordinal inputs never replace these rows. +pub(super) fn overlay_saved(app: &SolveApp, setup: &mut solidcraft_engine::doc::render_settings::RenderSetup) -> Result<(), String> { + overlay_coats(app, setup)?; + overlay_optics(app, setup) +} + +fn overlay_optics(app: &SolveApp, setup: &mut solidcraft_engine::doc::render_settings::RenderSetup) -> Result<(), String> { + let view = &app.render_workspace.view.materials; + for binding in + view.bindings.iter().filter(|binding| binding.stable_optics() && binding.active() && (view.enabled || binding.saved_source.is_some())) + { + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + let target = binding.target.stable_target.as_ref().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; + let baseline = app.render_workspace.view.draft.optics.iter().find(|saved| &saved.target == target).map(|saved| saved.optics); + if baseline != binding.saved_source { + return Err(app.tr("render.material_revalidate_needed").into()); + } + let source = setup.optics.iter().find(|saved| &saved.target == target).map(|saved| saved.optics); + let prospective = (binding.enabled && binding.glass_enabled).then(|| binding.optics()); + // An already-overlaid request is idempotent. A row in the actual draft + // still needs its exact saved-source proof, even if its values coincide. + if source != baseline && source != prospective { + return Err(app.tr("render.material_revalidate_needed").into()); + } + if binding.coat_enabled || binding.maps_enabled { + return Err(app.tr("render.material_saved_edit_pending").into()); + } + if !binding.enabled || !binding.glass_enabled { + setup.optics.remove(target); + } else { + setup + .optics + .set( + solidcraft_engine::doc::render_optics::SavedOptics { target: target.clone(), optics: binding.optics() }, + binding.saved_source.is_some(), + ) + .map_err(|error| error.to_string())?; + } + } + Ok(()) +} + +/// Stable coat edits use the same captured settings for CPU and GPU. This is a +/// pure overlay; generic Save still requires the explicit coat binding action. +pub(super) fn overlay_coats(app: &SolveApp, setup: &mut solidcraft_engine::doc::render_settings::RenderSetup) -> Result<(), String> { + if !app.render_workspace.view.materials.enabled { + return Ok(()); + } + for binding in &app.render_workspace.view.materials.bindings { + if !binding.coat_enabled && binding.saved_coat_source.is_none() && !binding.coat_edited { + continue; + } + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + let target = binding.target.stable_target.as_ref().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; + if let Some(expected) = binding.saved_coat_source { + let current = setup.coats.iter().find(|saved| &saved.target == target).map(|saved| saved.coat); + if current != Some(expected) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + } else if setup.coats.iter().any(|saved| &saved.target == target) { + return Err(app.tr("render.coat_revalidate_saved").into()); + } + if binding.glass_enabled && binding.coat_enabled { + return Err(app.tr("render.material_glass_exclusive").into()); + } + if !binding.enabled || !binding.coat_enabled { + if binding.saved_coat_source.is_some() { + setup.coats.remove(target); + } + } else { + setup + .coats + .set(solidcraft_engine::doc::render_coat::SavedCoat { target: target.clone(), coat: binding.coat_material() }, true) + .map_err(|error| error.to_string())?; + } + } + Ok(()) +} + +/// Pure prospective compatibility: no request, resources, host or document mutation. +pub(super) fn path_compatibility(app: &SolveApp) -> Result<(), String> { + // This is the same pure stable-target overlay used by image/live capture. + // A user's explicit unsaved removal of an unsupported flag must already be + // reflected by the availability of the transport it makes compatible. + let mut prospective = solidcraft_engine::doc::render_settings::RenderSetup { + optics: app.render_workspace.view.draft.optics.clone(), + coats: app.render_workspace.view.draft.coats.clone(), + ..Default::default() + }; + overlay_saved(app, &mut prospective)?; + prospective.optics.validate_for_cpu_path(true).map_err(|e| e.to_string())?; + if app.render_workspace.view.studio.denoise && prospective.optics.iter().any(|b| b.optics.subsurface.is_some_and(|s| s.active())) { + return Err(app.tr("render.cpu_subsurface_denoise_reason").into()); + } + for binding in app.render_workspace.view.materials.bindings.iter().filter(|b| b.saved_source.is_none() && b.active() && b.glass_enabled) { + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + binding.optics().validate_for_cpu_path(true).map_err(|e| e.to_string())?; + if app.render_workspace.view.studio.denoise && binding.glass.subsurface.is_some_and(|s| s.active()) { + return Err(app.tr("render.cpu_subsurface_denoise_reason").into()); + } + } + Ok(()) +} /// Called for every Check and Start through the one shared image request builder. /// No files are read until the engine captures the actual request. pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { let view = &app.render_workspace.view.materials; - if !view.enabled || !view.bindings.iter().any(Binding::active) { + // A file HDR can select this lane even when every Glass row is stable. + // Preserve those rows in settings, not a second ordinal representation. + if view.bindings.iter().any(|binding| binding.stable_optics() && binding.active() && (view.enabled || binding.saved_source.is_some())) { + let mut settings = serde_json::from_value(params["settings"].clone()).map_err(|error| error.to_string())?; + overlay_optics(app, &mut settings)?; + params["settings"] = json!(settings); + } + if !view.enabled || !view.bindings.iter().any(|binding| binding.active() && !binding.stable_optics()) { return Ok(()); } - if app.render_workspace.view.method != super::ImageMethod::GpuRaytrace { - return Err(app.tr("render.material_gpu_required").to_string()); + let cpu = app.render_workspace.view.method == super::ImageMethod::CpuRaytrace; + if app.render_workspace.view.method == super::ImageMethod::Raster { + return Err(app.tr("render.material_raytrace_required").to_string()); + } + if cpu && !app.render_workspace.view.draft.optics.is_empty() { + return Err(app.tr("render.material_cpu_saved_runtime_conflict").into()); } if view.bindings.len() > MAX_BINDINGS { return Err(app.tr("render.material_limits").to_string()); } - let (mut glass, mut coats, mut textures) = (Vec::new(), Vec::new(), Vec::new()); + let (mut glass, mut textures) = (Vec::new(), Vec::new()); let mut seen = std::collections::BTreeSet::new(); - for binding in view.bindings.iter().filter(|b| b.active()) { + for binding in view.bindings.iter().filter(|b| b.active() && !b.stable_optics()) { if !binding.current(app) { return Err(app.tr("render.material_revalidate_needed").to_string()); } + if binding.saved_source.is_some() { + return Err(app.tr("render.material_saved_edit_pending").into()); + } let target = &binding.target; if target.ordinal >= solidcraft_engine::render::job::MAX_GPU_PATH_BODIES || target.name.is_empty() @@ -267,8 +504,18 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { if binding.glass_enabled && (binding.coat_enabled || binding.maps_enabled) { return Err(app.tr("render.material_glass_exclusive").to_string()); } + if cpu && binding.maps_enabled { + return Err(app.tr("render.material_cpu_glass_only").into()); + } let identity = || json!({"body_index":target.ordinal,"body_name":target.name}); - if binding.glass_enabled { + if cpu && binding.glass_enabled { + let optical = binding.optics(); + glass.push(json!( + optical + .to_cpu_for_path(target.ordinal, &target.name, app.render_workspace.view.raytrace.path.is_some()) + .map_err(|error| error.to_string())? + )); + } else if binding.glass_enabled { let value = &binding.glass; OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, value.ior).map_err(|e| e.to_string())?; let [r, g, b] = value.absorption; @@ -292,11 +539,8 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { if binding.coat_enabled { let value = &binding.coat; ClearCoat::new(value.weight, value.roughness, value.ior).map_err(|e| e.to_string())?; - let mut wire = identity(); - wire["weight"] = json!(value.weight); - wire["roughness"] = json!(value.roughness); - wire["ior"] = json!(value.ior); - coats.push(wire); + // The stable coat overlay already captured these exact numbers. + // Never duplicate it as an ordinal runtime override. } if binding.maps_enabled { let value = &binding.maps; @@ -335,7 +579,16 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { { return Err(app.tr("render.material_limits").to_string()); } - params["raytrace"] = json!({"dielectrics":glass,"clear_coats":coats,"textures":textures}); + if cpu { + // Preserve all CPU lights, output, lens and sampling. This is the same + // numerical override type produced by stable saved-optics lowering. + params["raytrace"]["dielectrics"] = json!(glass); + let options: solidcraft_engine::render::job::RaytraceOptions = + serde_json::from_value(params["raytrace"].clone()).map_err(|error| error.to_string())?; + options.validate().map_err(|error| error.to_string())?; + } else { + params["raytrace"] = json!({"dielectrics":glass,"textures":textures}); + } Ok(()) } @@ -449,7 +702,11 @@ pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { } fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { - if ui_kit::checkbox(ui, app.tr("render.appearance_editor.glass_enable"), &mut binding.glass_enabled).changed() && binding.glass_enabled { + let cpu = app.render_workspace.view.method == super::ImageMethod::CpuRaytrace; + let path = app.render_workspace.view.raytrace.path.is_some(); + let enabled = ui_kit::checkbox(ui, app.tr("render.appearance_editor.glass_enable"), &mut binding.glass_enabled); + crate::scenario::publish_target("render:glass:enable", enabled.rect); + if enabled.changed() && binding.glass_enabled { binding.coat_enabled = false; binding.maps_enabled = false; } @@ -493,41 +750,71 @@ fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) 2 => Boundary::Box, _ => Boundary::Closed, }; - glass.shadows = glass.boundary == Boundary::Thin; - if glass.boundary == Boundary::Thin { - glass.subsurface = None; + if !cpu { + glass.shadows = glass.boundary == Boundary::Thin; } changed = true; } }); - changed |= - ui_kit::row(ui, app.tr("render.appearance_editor.ior"), |ui| ui_kit::number_field(ui, &mut glass.ior, 1.0..=3.0, 0.01, "")).changed(); + changed |= ui_kit::row(ui, app.tr("render.appearance_editor.ior"), |ui| { + let response = ui_kit::number_field(ui, &mut glass.ior, 1.0..=3.0, 0.01, ""); + crate::scenario::publish_target("render:glass:ior-field", response.rect); + response + }) + .changed(); ui.add_enabled_ui(glass.boundary == Boundary::Thin, |ui| { changed |= ui_kit::row(ui, app.tr("render.appearance_editor.thickness"), |ui| { - ui_kit::number_field(ui, &mut glass.thickness, 0.001..=10000.0, 0.1, " mm") + let response = ui_kit::number_field_preserving(ui, &mut glass.thickness, 0.0..=10000.0, 0.1, " mm"); + crate::scenario::publish_target("render:glass:thickness-field", response.rect); + response }) .changed(); }); - changed |= vector(app, ui, "render.appearance_editor.absorption", &mut glass.absorption, 0.0..=100.0, " /mm"); - changed |= ui_kit::checkbox(ui, app.tr("render.material_shadow"), &mut glass.shadows).changed(); - ui.add_enabled_ui(glass.boundary != Boundary::Thin, |ui| { + let absorption = app.tr("render.appearance_editor.absorption").to_owned(); + // Each suffixed DragValue needs the full control column. Three cells + // can expand a narrow inspector despite their individual clip rects. + for ((axis, value), channel) in glass.absorption.iter_mut().enumerate().zip(["R", "G", "B"]) { + changed |= ui_kit::row(ui, &format!("{absorption} {channel}"), |ui| { + let field = ui_kit::number_field(ui, value, 0.0..=100.0, 0.01, " /mm"); + crate::scenario::publish_target(&format!("dialog:vector:{absorption}:{axis}"), field.rect); + field + }) + .changed(); + } + ui.add_enabled_ui(!cpu || (path && glass.boundary == Boundary::Thin) || glass.shadows, |ui| { + changed |= ui_kit::checkbox(ui, app.tr("render.material_shadow"), &mut glass.shadows).changed(); + }); + // Existing unsupported choices remain removable. Positive CPU scattering + // requires the explicit closed-medium Path, never silent adoption. + ui.add_enabled_ui((glass.boundary != Boundary::Thin && (!cpu || path)) || glass.subsurface.is_some(), |ui| { let mut scatter = glass.subsurface.is_some(); - if ui_kit::checkbox(ui, app.tr("render.subsurface_enable"), &mut scatter).changed() { + let toggle = ui_kit::checkbox(ui, app.tr("render.subsurface_enable"), &mut scatter); + crate::scenario::publish_target("render:glass:subsurface-enable", toggle.rect); + if toggle.changed() { glass.subsurface = scatter.then_some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); changed = true; } if let Some(subsurface) = &mut glass.subsurface { - changed |= ui_kit::row(ui, app.tr("render.subsurface_rate"), |ui| { - ui_kit::number_field(ui, &mut subsurface.scattering_per_mm, 0.0..=100.0, 0.001, " /mm") - }) - .changed(); - changed |= ui_kit::row(ui, app.tr("render.volume_anisotropy"), |ui| { - ui_kit::number_field(ui, &mut subsurface.anisotropy, -0.95..=0.95, 0.01, "") - }) - .changed(); + ui.add_enabled_ui(!cpu || (path && glass.boundary != Boundary::Thin), |ui| { + changed |= ui_kit::row(ui, app.tr("render.subsurface_rate"), |ui| { + let field = ui_kit::number_field_preserving(ui, &mut subsurface.scattering_per_mm, 0.0..=100.0, 0.001, " /mm"); + crate::scenario::publish_target("render:glass:subsurface-rate", field.rect); + field + }) + .changed(); + changed |= ui_kit::row(ui, app.tr("render.volume_anisotropy"), |ui| { + let field = ui_kit::number_field_preserving(ui, &mut subsurface.anisotropy, -0.95..=0.95, 0.01, ""); + crate::scenario::publish_target("render:glass:subsurface-g", field.rect); + field + }) + .changed(); + }); } }); + if cpu { + note(app, ui, "render.cpu_subsurface_help"); + } if glass.boundary != Boundary::Thin { note(app, ui, "render.appearance_editor.thickness_reason"); } @@ -539,20 +826,37 @@ fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) glass.recipe = None; } note(app, ui, "render.appearance_editor.glass_note"); - note(app, ui, "render.material_certification"); + note(app, ui, if cpu { "render.cpu_material_certification" } else { "render.material_certification" }); } -fn coat_controls(app: &SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { - ui_kit::checkbox(ui, app.tr("render.material_coat_enable"), &mut binding.coat_enabled); +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); + let mut changed = enabled.changed(); ui.add_enabled_ui(binding.coat_enabled, |ui| { for (key, value, range) in [ ("render.appearance_editor.weight", &mut binding.coat.weight, 0.0..=1.0), ("appearance.roughness", &mut binding.coat.roughness, 0.045..=1.0), ] { - ui_kit::row(ui, app.tr(key), |ui| ui_kit::mixed_slider(ui, value, range, None)); + changed |= ui_kit::row(ui, app.tr(key), |ui| { + let response = ui_kit::mixed_slider(ui, value, range, None); + crate::scenario::publish_target( + if key == "render.appearance_editor.weight" { "render:coat:weight" } else { "render:coat:roughness" }, + response.rect, + ); + response + }) + .changed(); } - ui_kit::row(ui, app.tr("render.appearance_editor.ior"), |ui| ui_kit::number_field(ui, &mut binding.coat.ior, 1.0..=3.0, 0.01, "")); + changed |= ui_kit::row(ui, app.tr("render.appearance_editor.ior"), |ui| { + let response = ui_kit::number_field_preserving(ui, &mut binding.coat.ior, 1.0..=3.0, 0.01, ""); + crate::scenario::publish_target("render:coat:ior-field", response.rect); + response + }) + .changed(); }); + binding.coat_edited |= changed; + saved_coat_controls(app, ui, binding) } #[derive(Clone, Copy)] @@ -656,6 +960,12 @@ pub(super) fn install_library_surface( } else { Binding::new(target, app) }; + if binding.saved_coat_source.is_none() + && !binding.coat_has_local_changes() + && let Some(saved) = app.render_workspace.view.draft.coats.iter().find(|saved| binding.target.stable_target.as_ref() == Some(&saved.target)) + { + binding.hydrate_coat(saved.coat); + } binding.maps = maps; binding.maps_enabled = true; binding.enabled = true; @@ -690,7 +1000,7 @@ fn map_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { } }); } - vector(app, ui, "render.appearance_editor.origin", &mut binding.maps.frame.origin, -1e6..=1e6, " mm"); + vector(app, ui, "render.appearance_editor.origin", &mut binding.maps.frame.origin, -1e9..=1e9, " mm"); vector(app, ui, "render.appearance_editor.u_repeat", &mut binding.maps.frame.u, -1e6..=1e6, " mm"); vector(app, ui, "render.appearance_editor.v_repeat", &mut binding.maps.frame.v, -1e6..=1e6, " mm"); ui_kit::row(ui, app.tr("render.appearance_editor.normal_strength"), |ui| { @@ -704,6 +1014,151 @@ fn map_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { }); } +fn save_coat(app: &mut SolveApp, binding: &Binding) -> Result<(), String> { + if !binding.current(app) { + return Err(app.tr("render.material_revalidate_needed").into()); + } + let saved = app + .session + .doc + .render + .setups + .get(&app.render_workspace.view.name) + .and_then(|setup| setup.coats.iter().find(|saved| binding.target.stable_target.as_ref() == Some(&saved.target))) + .map(|saved| saved.coat); + if saved != binding.saved_coat_source { + return Err(app.tr("render.coat_revalidate_saved").into()); + } + let mut local = std::mem::take(&mut app.render_workspace.view.materials); + let preserve_maps = binding.has_local_map_intent(); + if preserve_maps && !local.bindings.iter().any(|old| old.target == binding.target) { + if local.bindings.len() >= MAX_BINDINGS { + app.render_workspace.view.materials = local; + return Err(app.tr("render.material_limits").into()); + } + let count = local.bindings.len() + 1; + let mut reserved = Vec::new(); + if reserved.try_reserve_exact(count).is_err() || reserved.capacity() != count { + app.render_workspace.view.materials = local; + return Err(app.tr("render.error_binding_allocation").into()); + } + reserved.append(&mut local.bindings); + local.bindings = reserved; + } + let setup = super::setups::snapshot(app); + app.render_workspace.view.materials = local; + let mut setup = setup?; + let name = app.render_workspace.view.name.clone(); + if let Some(saved) = app.session.doc.render.setups.get(&name) { + setup.camera = saved.camera; + } + app.run( + "render.coat.bind", + json!({"name":name,"set":setup,"body_index":binding.target.ordinal,"body_name":binding.target.name, + "coat":binding.coat_material(),"replace":binding.replace_saved_optics,"expected_revision":app.session.revision}), + )?; + let mut local = std::mem::take(&mut app.render_workspace.view.materials); + super::setups::load(app); + if preserve_maps { + let mut retained = binding.clone(); + retained.saved_coat_source = Some(binding.coat_material()); + retained.coat_edited = false; + retained.revision = app.session.revision; + retained.document = Arc::downgrade(&app.session.doc); + if let Some(old) = local.bindings.iter_mut().find(|old| old.target == binding.target) { + *old = retained; + } else { + // This exact slot was fallibly reserved before the document command. + local.bindings.push(retained); + } + } + app.render_workspace.view.materials = local; + Ok(()) +} + +fn saved_coat_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) -> bool { + let saved = + binding.target.stable_target.as_ref().and_then(|target| app.render_workspace.view.draft.coats.iter().find(|saved| &saved.target == target)); + let target = saved.map(|saved| saved.target.clone()); + note(app, ui, "render.coat_saved_help"); + if !binding.current(app) { + note(app, ui, "render.material_revalidate_needed"); + let response = ui_kit::button(ui, app.tr("render.appearance_editor.revalidate"), ui_kit::Button::Normal); + crate::scenario::publish_target("render:coat:revalidate", response.rect); + if response.clicked() + && let Err(error) = revalidate(app, binding) + { + app.set_status(error, true); + } + } + let can_save = binding.enabled + && binding.coat_enabled + && !binding.glass_enabled + && binding.current(app) + && binding.target.stable_target.is_some() + && (target.is_some() || app.render_workspace.view.draft.coats.len() < solidcraft_engine::doc::render_coat::MAX_COAT_BINDINGS) + && matches!(app.render_workspace.view.method, super::ImageMethod::CpuRaytrace | super::ImageMethod::GpuRaytrace); + let mut discard = false; + ui.horizontal(|ui| { + let save = ui_kit::button(ui, app.tr("render.coat_save"), ui_kit::Button::Enabled(can_save)); + crate::scenario::publish_target("render:coat:save", save.rect); + if save.clicked() { + match save_coat(app, binding) { + Ok(()) => { + binding.saved_coat_source = Some(binding.coat_material()); + binding.coat_edited = false; + binding.revision = app.session.revision; + binding.document = Arc::downgrade(&app.session.doc); + discard = !binding.has_local_map_intent(); + } + Err(error) => app.set_status(error, true), + } + } + let remove = ui_kit::button(ui, app.tr("render.coat_remove"), ui_kit::Button::Enabled(target.is_some())); + crate::scenario::publish_target("render:coat:remove", remove.rect); + if remove.clicked() + && let Some(target) = target + { + app.render_workspace.view.materials.pending_remove = Some(PendingRemoval { + coat: true, + name: app.render_workspace.view.name.clone(), + target, + revision: app.session.revision, + document: Arc::downgrade(&app.session.doc), + }); + } + }); + let replace = ui_kit::checkbox(ui, app.tr("render.appearance_editor.replace"), &mut binding.replace_saved_optics); + crate::scenario::publish_target("render:coat:replace", replace.rect); + if binding.coat_has_local_changes() { + note(app, ui, "render.coat_pending_edit"); + let response = ui_kit::button(ui, app.tr("render.coat_discard"), ui_kit::Button::Normal); + crate::scenario::publish_target("render:coat:discard", response.rect); + if response.clicked() { + let current = app + .session + .doc + .render + .setups + .get(&app.render_workspace.view.name) + .and_then(|setup| setup.coats.iter().find(|saved| binding.target.stable_target.as_ref() == Some(&saved.target))) + .map(|saved| saved.coat); + if let Some(saved) = current { + binding.hydrate_coat(saved); + } else { + binding.saved_coat_source = None; + binding.coat_enabled = false; + binding.coat_edited = false; + } + binding.enabled = true; + discard |= !binding.has_local_map_intent(); + } + } else if binding.saved_coat_source.is_some() { + note(app, ui, "render.appearance_editor.saved_state"); + } + discard +} + fn save_optics(app: &mut SolveApp, binding: &Binding) -> Result<(), String> { if !binding.current(app) { return Err(app.tr("render.material_revalidate_needed").into()); @@ -713,9 +1168,13 @@ fn save_optics(app: &mut SolveApp, binding: &Binding) -> Result<(), String> { let local = std::mem::take(&mut app.render_workspace.view.materials); let setup = super::setups::snapshot(app); app.render_workspace.view.materials = local; - let setup = setup?; + let mut setup = setup?; let value = &binding.glass; let name = app.render_workspace.view.name.clone(); + if let Some(saved) = app.session.doc.render.setups.get(&name) { + // Saving optical numbers is not the shot's explicit camera update action. + 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}); app.run( @@ -746,19 +1205,43 @@ fn editor_sections(app: &mut SolveApp, ui: &mut egui::Ui, binding: Option<&mut B None }; let title = app.tr("render.appearance_editor.glass").to_owned(); - ui_kit::method_section(ui, "render:appearance:glass", &title, "GPU", reason.as_deref(), |ui| glass_controls(app, ui, binding)); + let glass_reason = if !supported { + reason.clone() + } else if app.render_workspace.view.method == super::ImageMethod::Raster { + Some(app.tr("render.material_raytrace_required").to_owned()) + } else { + None + }; + ui_kit::method_section(ui, "render:appearance:glass", &title, "CPU / GPU", glass_reason.as_deref(), |ui| glass_controls(app, ui, binding)); + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + note(app, ui, "render.material_cpu_optics_limits"); + } let opaque_reason = reason.clone().or_else(|| binding.glass_enabled.then(|| app.tr("render.material_glass_exclusive").to_owned())); let title = app.tr("render.appearance_editor.coat").to_owned(); - ui_kit::method_section(ui, "render:appearance:coat", &title, "GPU", opaque_reason.as_deref(), |ui| coat_controls(app, ui, binding)); + let coat_reason = if !supported { + Some(app.tr("render.appearance_editor.body_reason").to_owned()) + } else if app.render_workspace.view.method == super::ImageMethod::Raster { + Some(app.tr("render.material_raytrace_required").to_owned()) + } else { + binding.glass_enabled.then(|| app.tr("render.material_glass_exclusive").to_owned()) + }; + let coat_removed = + ui_kit::method_section(ui, "render:appearance:coat", &title, "CPU / GPU", coat_reason.as_deref(), |ui| coat_controls(app, ui, binding)) + .unwrap_or(false); let title = app.tr("render.appearance_editor.maps").to_owned(); - ui_kit::method_section(ui, "render:appearance:maps", &title, "GPU", opaque_reason.as_deref(), |ui| map_controls(app, ui, binding)); + let map_reason = if supported && app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + Some(app.tr("render.cpu_maps_saved_help").to_owned()) + } else { + opaque_reason.clone() + }; + ui_kit::method_section(ui, "render:appearance:maps", &title, "GPU", map_reason.as_deref(), |ui| map_controls(app, ui, binding)); let title = app.tr("render.appearance_editor.saved").to_owned(); let removed = ui_kit::editor_section(ui, "render:appearance:saved", &title, false, |ui| { ui.add_enabled_ui(supported, |ui| saved_controls(app, ui, binding)).inner }) .unwrap_or(false); reflection_section(app, ui, supported.then_some(binding.target.name.as_str())); - removed + removed || coat_removed } /// Resolve one selected whole body against the authoritative captured scene. Never @@ -785,21 +1268,34 @@ pub(super) fn selection_controls(app: &mut SolveApp, ui: &mut egui::Ui, body: Op if let Some(target) = targets.next() && targets.next().is_none() { - binding = Some(Binding::new(target.clone(), app)); + let saved = app.render_workspace.view.draft.optics.iter().find(|saved| target.stable_target.as_ref() == Some(&saved.target)); + let mut hydrated = + saved.map_or_else(|| Binding::new(target.clone(), app), |saved| Binding::from_saved(target.clone(), app, saved.optics)); + if let Some(saved) = app.render_workspace.view.draft.coats.iter().find(|saved| target.stable_target.as_ref() == Some(&saved.target)) { + hydrated.hydrate_coat(saved.coat); + } + binding = Some(hydrated); } } let before = app.session.revision; + let original_target = binding.as_ref().map(|binding| binding.target.clone()); let removed = editor_sections(app, ui, binding.as_mut()); if let Some(binding) = binding { let view = &mut app.render_workspace.view.materials; - let existing = view.bindings.iter().position(|b| b.target == binding.target); + // Explicit stable revalidation may update a captured ordinal. Replace + // the actual edited row instead of retaining an obsolete duplicate. + let existing = view.bindings.iter().position(|b| b.target == binding.target || Some(&b.target) == original_target.as_ref()); if removed { if let Some(index) = existing { view.bindings.remove(index); } } else if app.session.revision == before { // Opening the editor alone never allocates an inactive assignment. - if binding.glass_enabled || binding.coat_enabled || binding.maps_enabled || existing.is_some() { + if (binding.saved_source.is_some() || (binding.saved_coat_source.is_some() && !binding.has_local_map_intent())) && !binding.active() { + if let Some(index) = existing { + view.bindings.remove(index); + } + } else if binding.glass_enabled || binding.coat_enabled || binding.maps_enabled || existing.is_some() { if existing.is_none() { view.enabled = true; } @@ -831,14 +1327,19 @@ fn saved_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) note( app, ui, - if saved.is_some() && !binding.active() { "render.appearance_editor.saved_state" } else { "render.appearance_editor.temporary" }, + if ((saved.is_some() && binding.saved_source.is_some()) || binding.saved_coat_source.is_some()) && !binding.active() { + "render.appearance_editor.saved_state" + } else { + "render.appearance_editor.temporary" + }, ); }); - let can_save = binding.glass_enabled + let can_save = binding.enabled + && binding.glass_enabled && binding.current(app) && !binding.maps_enabled && !binding.coat_enabled - && app.render_workspace.view.method == super::ImageMethod::GpuRaytrace; + && matches!(app.render_workspace.view.method, super::ImageMethod::CpuRaytrace | super::ImageMethod::GpuRaytrace); let mut removed = false; ui.horizontal(|ui| { let save = ui_kit::button(ui, app.tr("render.appearance_editor.save"), ui_kit::Button::Enabled(can_save)); @@ -856,6 +1357,7 @@ fn saved_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) { crate::scenario::publish_target(&format!("render:optics-remove:{index}"), remove.rect); app.render_workspace.view.materials.pending_remove = Some(PendingRemoval { + coat: false, name: app.render_workspace.view.name.clone(), target, revision: app.session.revision, @@ -863,6 +1365,12 @@ fn saved_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) }); } }); + if binding.saved_source.is_some() && binding.active() { + note(app, ui, "render.material_saved_edit_pending"); + let discard = ui_kit::button(ui, app.tr("render.appearance_editor.discard_saved_edit"), ui_kit::Button::Normal); + crate::scenario::publish_target("render:optics-discard-edit", discard.rect); + removed |= discard.clicked(); + } ui_kit::checkbox(ui, app.tr("render.appearance_editor.replace"), &mut binding.replace_saved_optics); if !can_save { note(app, ui, "render.appearance_editor.save_reason"); @@ -942,24 +1450,45 @@ pub(super) fn confirmation(app: &mut SolveApp, ctx: &egui::Context) { app.set_status(app.tr("render.review_stale").to_owned(), true); return; } - let title = app.tr("render.appearance_editor.remove_title").to_owned(); + let title = app.tr(if pending.coat { "render.coat_remove_title" } else { "render.appearance_editor.remove_title" }).to_owned(); let (closed, action) = ui_kit::Confirm::new(egui::Id::unique("render_remove_optics"), "delete", &title) .tone(ui_kit::Tone::Danger) .actions(app.tr("render.appearance_editor.remove"), app.tr("render.keep_editing"), None) .selected(ui_kit::Action::Cancel) .show(ctx, true, |ui| { - note(app, ui, "render.appearance_editor.remove_note"); + note(app, ui, if pending.coat { "render.coat_remove_note" } else { "render.appearance_editor.remove_note" }); }); if closed || action == ui_kit::Action::Cancel { app.render_workspace.view.materials.pending_remove = None; } if action == ui_kit::Action::Ok { app.render_workspace.view.materials.pending_remove = None; - match app.run("render.optics.unbind", json!({"name":pending.name,"target":&pending.target,"expected_revision":pending.revision})) { + let command = if pending.coat { "render.coat.unbind" } else { "render.optics.unbind" }; + match app.run(command, json!({"name":pending.name,"target":&pending.target,"expected_revision":pending.revision})) { Ok(_) => { // Removing one saved binding must preserve unsaved shot settings // and unrelated temporary overrides on this tab. - app.render_workspace.view.draft.optics.remove(&pending.target); + if pending.coat { + app.render_workspace.view.draft.coats.remove(&pending.target); + let revision = app.session.revision; + let document = Arc::downgrade(&app.session.doc); + app.render_workspace.view.materials.bindings.retain_mut(|binding| { + if binding.target.stable_target.as_ref() != Some(&pending.target) { + return true; + } + if !binding.has_local_map_intent() { + return false; + } + binding.saved_coat_source = None; + binding.coat_enabled = false; + binding.coat_edited = false; + binding.revision = revision; + binding.document = document.clone(); + true + }); + } else { + app.render_workspace.view.draft.optics.remove(&pending.target); + } } Err(error) => app.set_status(error, true), } diff --git a/crates/ui-egui/src/render_workspace_output.rs b/crates/ui-egui/src/render_workspace_output.rs index 2d33bf9b2..38a5bc086 100644 --- a/crates/ui-egui/src/render_workspace_output.rs +++ b/crates/ui-egui/src/render_workspace_output.rs @@ -17,6 +17,8 @@ pub(super) struct View { reveal: Option<&'static str>, pending: Option, pub checked: Option, + quality_plans: Option<[Result; 3]>, + quality_source: Option, scene_info: Option, selection_appearance: selection_appearance::View, pub(super) resolution: Resolution, @@ -117,9 +119,11 @@ pub(super) fn shot_row_action(app: &mut SolveApp, name: String, command: &str) { } fn request_action(app: &mut SolveApp, action: PendingAction) { - // Focusing the current shot is navigation, never a request to reload its draft. + // Editor focus is separate from activation. With the saved camera already in + // place (or in compatibility mode), focusing the active shot keeps its draft. if let PendingAction::Switch(name) = &action && *name == app.render_workspace.view.name + && (app.preferences.render_legacy_image_defaults || app.session.doc.render.setups.get(name).is_none_or(|setup| setup.camera == app.cam)) { super::selection_editor(app, &super::RenderSelection::Shot(name.clone())); return; @@ -137,11 +141,22 @@ fn request_action(app: &mut SolveApp, action: PendingAction) { app.set_status(error, true); } } +/// Explicit tree/strip activation restores the complete saved camera. Numeric reloads, +/// external edits and Undo keep using the camera-neutral setup adapter. +pub(super) fn activate_saved_shot(app: &mut SolveApp, name: String) -> Result<(), String> { + if !app.preferences.render_legacy_image_defaults { + // The command validates the saved setup before any active draft is replaced. + restore_saved_camera(app, &name)?; + } + app.render_workspace.view.name = name; + setups::load(app); + Ok(()) +} + fn perform_action(app: &mut SolveApp, action: PendingAction) -> Result<(), String> { match action { PendingAction::Switch(name) => { - app.render_workspace.view.name = name.clone(); - setups::load(app); + activate_saved_shot(app, name.clone())?; super::selection_editor(app, &super::RenderSelection::Shot(name)); } PendingAction::ManageShot { name, command } => { @@ -212,6 +227,26 @@ fn browse_button(app: &mut SolveApp, ui: &mut egui::Ui, kind: &str, key: &str) { library::open_category(app, kind); } } +/// All visible batch entry points share readiness and the captured, live-draining action. +fn all_shots_button(app: &mut SolveApp, ui: &mut egui::Ui, label: &str, target: &str) -> Option { + let ready = super::ribbon::action_ready(app, "render.batch"); + let button = ui_kit::button(ui, label, ui_kit::Button::Enabled(ready.is_ok())); + let button = if let Err(reason) = &ready { button.on_disabled_hover_text(reason) } else { button }; + crate::scenario::publish_target(target, button.rect); + if button.clicked() + && let Err(error) = super::ribbon::perform_job(app, "render.batch") + { + app.set_status(error, true); + } + ready.err() +} +fn batch_explanation(app: &SolveApp, ui: &mut egui::Ui, reason: Option<&str>) { + if let Some(reason) = reason { + ui_kit::text(ui, reason, ui_kit::Text::Note("render:batch:reason")); + } + ui_kit::text(ui, app.tr("render.batch_current_settings_help"), ui_kit::Text::Note("render.batch_current_settings_help")); +} + pub(super) fn scene_controls(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::text(ui, app.tr("render.scene_preserves_design"), ui_kit::Text::Note("render.scene_preserves_design")); let label = app.tr("render.children.method").to_string(); @@ -296,9 +331,8 @@ pub(super) fn scene_controls(app: &mut SolveApp, ui: &mut egui::Ui) { } }); let label = crate::i18n::format("render.scene_all_shots", &[("count", &app.session.doc.render.setups.len().to_string())]); - let response = ui_kit::button(ui, &label, ui_kit::Button::Enabled(false)); - crate::scenario::publish_target("render:scene:all-shots", response.rect); - ui_kit::text(ui, app.tr("render.scene_batch_reason"), ui_kit::Text::Note("render.scene_batch_reason")); + let reason = all_shots_button(app, ui, &label, "render:scene:all-shots"); + batch_explanation(app, ui, reason.as_deref()); }); let title = app.tr("render.scene_reminders").to_string(); ui_kit::section(ui, "render_scene_reminders", &title, true, |ui| { @@ -511,11 +545,11 @@ fn output_controls(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::text(ui, &size_limit_reason(app, before[0], before[1]), ui_kit::Text::Error("render.output_over_budget")); } studio::export_controls(app, ui); - let gpu = app.render_workspace.view.method == ImageMethod::GpuRaytrace; - if !gpu { - ui_kit::text(ui, app.tr("render.effects_gpu_only"), ui_kit::Text::Note("render.effects_gpu_only")); + let raytrace = app.render_workspace.view.method != ImageMethod::Raster; + if !raytrace { + ui_kit::text(ui, app.tr("render.output_raytrace_only"), ui_kit::Text::Note("render.output_raytrace_only")); } - ui.add_enabled_ui(gpu, |ui| { + ui.add_enabled_ui(raytrace, |ui| { let label = app.tr("render.children.keep_master").to_string(); let response = ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.studio.linear_exr); crate::scenario::publish_target("render:retain-exr", response.rect); @@ -524,12 +558,10 @@ fn output_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let label = app.tr("render.image_transparent").to_string(); let cpu = app.render_workspace.view.method == ImageMethod::CpuRaytrace; if cpu { - ui_kit::text(ui, app.tr("render.cpu_opaque_required"), ui_kit::Text::Note("render.cpu_opaque_required")); + ui_kit::text(ui, app.tr("render.cpu_transparent_help"), ui_kit::Text::Note("render.cpu_transparent_help")); } - // An incompatible retained value can always be cleared without switching method. - ui.add_enabled_ui(!cpu || app.render_workspace.view.transparent, |ui| { - ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.transparent); - }); + let response = ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.transparent); + crate::scenario::publish_target("render:transparent-background", response.rect); reveal_section(app, ui, "render_output_advanced"); let title = app.tr("render.output_advanced").to_string(); ui_kit::section(ui, "render_output_advanced", &title, false, |ui| { @@ -587,6 +619,7 @@ fn render_controls(app: &mut SolveApp, ui: &mut egui::Ui) { super::progress_pill(app, ui, "render:output-progress"); return; } + let mut batch_reason = None; ui.horizontal_wrapped(|ui| { let ready = super::ribbon::action_ready(app, "render.start"); let button = ui_kit::button(ui, app.tr("render.children.render_shot"), ui_kit::Button::Enabled(ready.is_ok())); @@ -596,10 +629,10 @@ fn render_controls(app: &mut SolveApp, ui: &mut egui::Ui) { if let Err(reason) = ready { button.backing_on_disabled_hover_text(reason); } - ui_kit::button(ui, app.tr("render.children.all_shots"), ui_kit::Button::Enabled(false)) - .backing_on_disabled_hover_text(app.tr("render.queue_pending")); + let label = app.tr("render.children.all_shots").to_string(); + batch_reason = all_shots_button(app, ui, &label, "render:output:section-all-shots"); }); - ui_kit::text(ui, app.tr("render.queue_pending"), ui_kit::Text::Note("render.queue_pending")); + batch_explanation(app, ui, batch_reason.as_deref()); if ui_kit::button(ui, app.tr("render.output_view_image"), ui_kit::Button::Enabled(app.render_workspace.view.completed.is_some())).clicked() { let _ = app.run("render.result.view", json!({"view":"image"})); } @@ -607,46 +640,92 @@ fn render_controls(app: &mut SolveApp, ui: &mut egui::Ui) { pub(super) fn sampling_editor(app: &mut SolveApp, ui: &mut egui::Ui) { editor_section(app, ui, "render_sampling_quality", "render.output_quality", |app, ui| { quality_choices(app, ui); - ui_kit::text(ui, app.tr("render.output_quality_waiting"), ui_kit::Text::Note("render.output_quality_waiting")); - browse_button(app, ui, "quality", "render.children.review_quality"); - library::inspect_kinds(app, ui, &["quality"]); + if app.render_workspace.view.method == ImageMethod::GpuRaytrace { + let view = &app.render_workspace.view; + let summary = quality_summary(app, view.draft.width, view.draft.height, view.samples, view.max_depth, view.seed, view.studio.denoise); + ui_kit::text(ui, &summary, ui_kit::Text::Note("render:quality:summary")); + } + if app.render_workspace.view.method == ImageMethod::CpuRaytrace { + let view = &app.render_workspace.view; + if let Some(sampling) = view.raytrace.progressive { + let summary = + cpu_quality_summary(app, view.draft.width, view.draft.height, sampling.samples_per_pixel, sampling.seed, view.raytrace.budget); + ui_kit::text(ui, &summary, ui_kit::Text::Note("render:quality:summary")); + } + ui_kit::text(ui, app.tr("render.cpu_quality_budget_help"), ui_kit::Text::Note("render.cpu_quality_budget_help")); + } else { + ui_kit::text(ui, app.tr("render.quality_budget_help"), ui_kit::Text::Note("render.quality_budget_help")); + if app.render_workspace.view.method == ImageMethod::GpuRaytrace { + browse_button(app, ui, "quality", "render.children.review_quality"); + library::inspect_kinds(app, ui, &["quality"]); + } + } }); for (id, key, method, draw) in [ ("render_sampling_path", "render.children.path", ImageMethod::GpuRaytrace, path_controls as fn(&mut SolveApp, &mut egui::Ui)), - ("render_sampling_adaptive", "render.children.adaptive", ImageMethod::GpuRaytrace, super::transport::adaptive_controls), ("render_sampling_glass", "render.children.glass", ImageMethod::GpuRaytrace, super::transport::glass_controls), ("render_sampling_cpu", "render.children.cpu", ImageMethod::CpuRaytrace, cpu_sampling), ] { let title = app.tr(key).to_string(); - let reason = (app.render_workspace.view.method != method) - .then(|| app.tr(if method == ImageMethod::GpuRaytrace { "render.effects_gpu_only" } else { "render.children.needs_cpu" }).to_string()); - ui_kit::method_section(ui, id, &title, if method == ImageMethod::GpuRaytrace { "GPU" } else { "CPU" }, reason.as_deref(), |ui| draw(app, ui)); + let glass = id == "render_sampling_glass"; + let reason = if glass { + (app.render_workspace.view.method == ImageMethod::Raster).then(|| app.tr("render.method_limit_raster").to_string()) + } else { + (app.render_workspace.view.method != method) + .then(|| app.tr(if method == ImageMethod::GpuRaytrace { "render.effects_gpu_only" } else { "render.children.needs_cpu" }).to_string()) + }; + ui_kit::method_section( + ui, + id, + &title, + if glass { + "CPU / GPU" + } else if method == ImageMethod::GpuRaytrace { + "GPU" + } else { + "CPU" + }, + reason.as_deref(), + |ui| draw(app, ui), + ); + if id == "render_sampling_path" { + let title = app.tr("render.children.adaptive").to_string(); + let reason = (app.render_workspace.view.method == ImageMethod::Raster).then(|| app.tr("render.method_limit_raster").to_string()); + ui_kit::method_section(ui, "render_sampling_adaptive", &title, "CPU / GPU", reason.as_deref(), |ui| { + super::transport::adaptive_controls(app, ui) + }); + } } } fn path_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let label = app.tr("render.children.samples").to_string(); let mut samples = app.render_workspace.view.samples.clamp(1, 4096); - if ui_kit::row(ui, &label, |ui| { + let response = ui_kit::row(ui, &label, |ui| { ui_kit::slider( ui, &mut samples, 1..=4096, ui_kit::Slider { integer: true, step: Some(1.0), format: |v| format!("{v:.0}"), ..Default::default() }, ) - }) - .changed() - { - app.render_workspace.view.samples = samples.checked_next_power_of_two().unwrap_or(4096).min(4096); + }); + crate::scenario::publish_target("render:gpu-samples", response.rect); + if response.changed() { + app.render_workspace.view.samples = + if app.preferences.render_legacy_image_defaults { samples.checked_next_power_of_two().unwrap_or(4096).min(4096) } else { samples }; } let label = app.tr("render.children.depth").to_string(); let mut depth = app.render_workspace.view.max_depth.clamp(1, 16); - if ui_kit::row(ui, &label, |ui| ui_kit::number_field(ui, &mut depth, 1..=16, 1.0, "")).changed() { + let response = ui_kit::row(ui, &label, |ui| ui_kit::number_field(ui, &mut depth, 1..=16, 1.0, "")); + crate::scenario::publish_target("render:gpu-depth", response.rect); + if response.changed() { app.render_workspace.view.max_depth = depth; } let label = app.tr("render.children.seed").to_string(); - ui_kit::row(ui, &label, |ui| ui_kit::number_field(ui, &mut app.render_workspace.view.seed, 0..=u32::MAX, 1.0, "")); + let response = ui_kit::row(ui, &label, |ui| ui_kit::number_field(ui, &mut app.render_workspace.view.seed, 0..=u32::MAX, 1.0, "")); + crate::scenario::publish_target("render:gpu-seed", response.rect); let label = app.tr("render.children.denoise").to_string(); - ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.studio.denoise); + let response = ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.studio.denoise); + crate::scenario::publish_target("render:gpu-denoise", response.rect); ui_kit::text(ui, app.tr("render.studio_denoise_help"), ui_kit::Text::Note("render.studio_denoise_help")); } fn cpu_sampling(app: &mut SolveApp, ui: &mut egui::Ui) { @@ -657,9 +736,15 @@ fn cpu_sampling(app: &mut SolveApp, ui: &mut egui::Ui) { } let depth = app.tr("render.children.reflect_depth").to_string(); let samples = app.tr("render.children.reflect_samples").to_string(); + let maximum = if app.render_workspace.view.raytrace.progressive.is_some() { 1 } else { 64 }; ui.add_enabled_ui(app.render_workspace.view.raytrace.reflections.is_some(), |ui| { ui_kit::row(ui, &depth, |ui| ui_kit::number_field(ui, &mut reflections.max_bounces, 1..=8, 1.0, "")); - ui_kit::row(ui, &samples, |ui| ui_kit::number_field(ui, &mut reflections.samples, 1..=64, 1.0, "")); + let response = ui_kit::row(ui, &samples, |ui| { + let field = ui_kit::number_field_preserving(ui, &mut reflections.samples, 1..=maximum, 1.0, ""); + crate::scenario::publish_target("render:cpu-reflection-samples-field", field.rect); + field + }); + crate::scenario::publish_target("render:cpu-reflection-samples", response.rect); }); if let Some(value) = &mut app.render_workspace.view.raytrace.reflections { *value = reflections; @@ -694,7 +779,7 @@ fn check_controls(app: &mut SolveApp, ui: &mut egui::Ui) { } } fn check_note_link(app: &mut SolveApp, ui: &mut egui::Ui, index: usize, line: &CheckLine) { - if line.status == ui_kit::CheckStatus::Ok { + if line.status == ui_kit::CheckStatus::Ok || line.key == "backend_pending" { return; } let message = line.label.to_ascii_lowercase(); @@ -807,26 +892,218 @@ pub(super) fn largest_output(app: &SolveApp) -> Option<(u64, u64)> { let draft = &app.render_workspace.view.draft; limits.fit(u64::from(draft.width).checked_mul(limits.max_dimension)?, u64::from(draft.height).checked_mul(limits.max_dimension)?, None) } -pub(super) fn quality_choices(app: &mut SolveApp, ui: &mut egui::Ui) { - let reason = app.tr("render.output_quality_waiting"); - let labels = ["render.quality_draft", "render.quality_balanced", "render.quality_high", "render.quality_custom"].map(|key| app.tr(key)); - let mut quality = 3; - if ui_kit::segmented( - ui, - &mut quality, - &labels, - ui_kit::Segments { - workspace_accent: true, - intrinsic: true, - compact: true, - targets: &["render:quality:draft", "render:quality:balanced", "render:quality:high", "render:quality:custom"], - disabled_reasons: &[Some(reason), Some(reason), Some(reason), None], - ..Default::default() +const QUALITY_IDS: [&str; 3] = ["Q-001", "Q-002", "Q-003"]; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct QualitySource { + method: ImageMethod, + progressive: bool, + budget: solidcraft_engine::render::job::CpuBudget, + adaptive: Option<(u32, u32, [u64; 3])>, +} +fn quality_source(app: &SolveApp) -> QualitySource { + let view = &app.render_workspace.view; + let cpu = view.method == ImageMethod::CpuRaytrace; + QualitySource { + method: view.method, + progressive: cpu && view.raytrace.progressive.is_some(), + budget: if cpu { view.raytrace.budget } else { Default::default() }, + adaptive: if cpu { + view.studio + .adaptive + .map(|a| (a.pilot_samples, a.min_samples, [a.relative_error.to_bits(), a.absolute_error.to_bits(), a.coverage_error.to_bits()])) + } else { + None }, - ) { - let _ = app.run("view.render_select", json!({"kind":"sampling"})); } } +fn quality_request(app: &SolveApp, id: &str) -> Result { + let view = &app.render_workspace.view; + match view.method { + ImageMethod::GpuRaytrace => Ok(json!({"id":id,"variant":"fixed_samples_png","acknowledge_omissions":true})), + ImageMethod::CpuRaytrace => { + if view.raytrace.progressive.is_none() { + return Err(app.tr("render.cpu_quality_progressive_required").to_string()); + } + Ok(json!({"id":id,"variant":"cpu_progressive_png","acknowledge_omissions":true, + "cpu":{"minimum_budget":view.raytrace.budget,"adaptive":view.studio.adaptive}})) + } + ImageMethod::Raster => Err(app.tr("render.method_limit_raster").to_string()), + } +} + +/// Immutable catalogue budgets are cached for comparison and hover summaries only. +/// An actual preset click prepares and applies a fresh canonical plan. +fn prepare_quality_choices(app: &mut SolveApp) { + let source = quality_source(app); + if app.render_workspace.view.inspector.quality_source != Some(source) || app.render_workspace.view.inspector.quality_plans.is_none() { + let plans = QUALITY_IDS.map(|id| { + quality_request(app, id).and_then(|params| app.session.execute("render.quality.prepare", ¶ms).map_err(|error| error.to_string())) + }); + app.render_workspace.view.inspector.quality_plans = Some(plans); + app.render_workspace.view.inspector.quality_source = Some(source); + } +} + +fn quality_selection(app: &SolveApp) -> usize { + let view = &app.render_workspace.view; + if view.method == ImageMethod::Raster || (view.method == ImageMethod::CpuRaytrace && view.raytrace.progressive.is_none()) { + return 3; + } + view.inspector + .quality_plans + .as_ref() + .and_then(|plans| { + plans.iter().position(|plan| { + plan.as_ref().is_ok_and(|plan| { + plan["settings"]["width"].as_u64() == Some(u64::from(view.draft.width)) + && plan["settings"]["height"].as_u64() == Some(u64::from(view.draft.height)) + && match view.method { + ImageMethod::GpuRaytrace => { + plan["variant"] == "fixed_samples_png" + && plan["gpu_options"]["samples"].as_u64() == Some(u64::from(view.samples)) + && plan["gpu_options"]["max_depth"].as_u64() == Some(u64::from(view.max_depth)) + && plan["gpu_options"]["seed"].as_u64() == Some(u64::from(view.seed)) + && plan["gpu_options"]["denoise"].as_bool() == Some(view.studio.denoise) + } + ImageMethod::CpuRaytrace => view.raytrace.progressive.is_some_and(|sampling| { + plan["variant"] == "cpu_progressive_png" + && plan["cpu_options"]["progressive"]["samples_per_pixel"].as_u64() == Some(u64::from(sampling.samples_per_pixel)) + && plan["cpu_options"]["progressive"]["seed"].as_u64() == Some(u64::from(sampling.seed)) + && plan["cpu_options"]["budget"] == json!(view.raytrace.budget) + }), + ImageMethod::Raster => false, + } + }) + }) + }) + .unwrap_or(3) +} + +fn quality_reason(app: &SolveApp, index: usize) -> Option<&str> { + if index == 3 { + return None; + } + if app.render_workspace.view.method == ImageMethod::Raster { + return Some(app.tr("render.method_limit_raster")); + } + if app.render_workspace.view.method == ImageMethod::CpuRaytrace && app.render_workspace.view.raytrace.progressive.is_none() { + return Some(app.tr("render.cpu_quality_progressive_required")); + } + match app.render_workspace.view.inspector.quality_plans.as_ref().and_then(|plans| plans.get(index)) { + Some(Ok(_)) => None, + Some(Err(reason)) => Some(reason), + None => Some(app.tr("render.error_quality_projection")), + } +} + +fn choose_quality(app: &mut SolveApp, index: usize) -> Result<(), String> { + if index == 3 { + return app.run("view.render_select", json!({"kind":"sampling"})).map(|_| ()); + } + let id = QUALITY_IDS.get(index).ok_or_else(|| app.tr("render.error_quality_projection").to_string())?; + let request = quality_request(app, id)?; + // Canonical chips are reversible numerical presets. Imported library plans keep + // their separate acknowledged review; comparison caches never author an edit. + let plan = app.run("render.quality.prepare", request)?; + apply_quality_transaction(app, &plan) +} + +fn quality_summary(app: &SolveApp, width: u32, height: u32, samples: u32, depth: u32, seed: u32, denoise: bool) -> String { + crate::i18n::format( + "render.quality_summary", + &[ + ("width", &width.to_string()), + ("height", &height.to_string()), + ("samples", &samples.to_string()), + ("depth", &depth.to_string()), + ("seed", &seed.to_string()), + ("denoise", app.tr(if denoise { "render.quality_denoise_on" } else { "render.quality_denoise_off" })), + ], + ) +} + +fn cpu_quality_summary( + app: &SolveApp, + width: u32, + height: u32, + samples: u32, + seed: u32, + budget: solidcraft_engine::render::job::CpuBudget, +) -> String { + crate::i18n::format( + "render.cpu_quality_summary", + &[ + ("width", &width.to_string()), + ("height", &height.to_string()), + ("samples", &samples.to_string()), + ("seed", &seed.to_string()), + ("profile", cpu::budget_name(app, budget)), + ], + ) +} +fn quality_hover(app: &SolveApp) -> String { + let labels = ["render.quality_draft", "render.quality_balanced", "render.quality_high"]; + app.render_workspace.view.inspector.quality_plans.as_ref().map_or_else(String::new, |plans| { + plans + .iter() + .zip(labels) + .filter_map(|(plan, label)| { + let plan = plan.as_ref().ok()?; + let field = |section: &str, key: &str| plan[section][key].as_u64().and_then(|n| u32::try_from(n).ok()); + if plan["variant"] == "cpu_progressive_png" { + let sampling = &plan["cpu_options"]["progressive"]; + let samples = sampling["samples_per_pixel"].as_u64().and_then(|n| u32::try_from(n).ok())?; + let seed = sampling["seed"].as_u64().and_then(|n| u32::try_from(n).ok())?; + let budget = serde_json::from_value(plan["cpu_options"]["budget"].clone()).ok()?; + let summary = cpu_quality_summary(app, field("settings", "width")?, field("settings", "height")?, samples, seed, budget); + return Some(format!("{}: {summary}", app.tr(label))); + } + let summary = quality_summary( + app, + field("settings", "width")?, + field("settings", "height")?, + field("gpu_options", "samples")?, + field("gpu_options", "max_depth")?, + field("gpu_options", "seed")?, + plan["gpu_options"]["denoise"].as_bool()?, + ); + Some(format!("{}: {summary}", app.tr(label))) + }) + .collect::>() + .join("\n") + }) +} + +pub(super) fn quality_choices(app: &mut SolveApp, ui: &mut egui::Ui) { + prepare_quality_choices(app); + let labels = ["render.quality_draft", "render.quality_balanced", "render.quality_high", "render.quality_custom"].map(|key| app.tr(key)); + let mut quality = quality_selection(app); + let choice = ui.scope(|ui| { + ui_kit::segmented( + ui, + &mut quality, + &labels, + ui_kit::Segments { + workspace_accent: true, + intrinsic: true, + compact: true, + targets: &["render:quality:draft", "render:quality:balanced", "render:quality:high", "render:quality:custom"], + disabled_reasons: &[quality_reason(app, 0), quality_reason(app, 1), quality_reason(app, 2), None], + ..Default::default() + }, + ) + }); + let help = quality_hover(app); + if !help.is_empty() { + choice.response.on_hover_text(help); + } + if choice.inner + && let Err(error) = choose_quality(app, quality) + { + app.set_status(error, true); + } +} + pub(super) fn check_summary(app: &SolveApp) -> String { let state = match &app.render_workspace.view.inspector.checked { Some(check) if check.current(app) && super::image_params(app).as_ref().ok() == Some(&check.request) => { @@ -983,6 +1260,11 @@ struct CheckLine { } fn check_lines(app: &SolveApp) -> Vec { use ui_kit::CheckStatus::{Error, Ok, Warning}; + if app.render_workspace.view.method == ImageMethod::GpuRaytrace + && let Some(key) = app.render_workspace.path_host.pending_message_key() + { + return vec![CheckLine { key: "backend_pending", label: app.tr(key).into(), status: Warning }]; + } if let Err(error) = super::image_params(app) { return vec![CheckLine { key: "error", label: error, status: Error }]; } @@ -1072,9 +1354,7 @@ fn check_report(app: &SolveApp) -> Option { } pub(super) fn scene_resource(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) { - if ui_kit::button(ui, app.tr("render.scene_review"), ui_kit::Button::Enabled(app.render_workspace.view.method == ImageMethod::GpuRaytrace)) - .clicked() - { + if ui_kit::button(ui, app.tr("render.scene_review"), ui_kit::Button::Enabled(app.render_workspace.view.method != ImageMethod::Raster)).clicked() { let mut view = library::View::default(); if let Err(error) = library::choose(app, &mut view, "native_scenes", id).and_then(|()| library::review::light(app, &view, id)) { app.set_status(error, true); @@ -1090,7 +1370,22 @@ pub(super) fn quality_resource(app: &mut SolveApp, ui: &mut egui::Ui, id: &str) app.set_status(error, true); } } +/// Share one non-camera numerical transaction between canonical presets and library reviews. +pub(super) fn apply_quality_transaction(app: &mut SolveApp, plan: &Value) -> Result<(), String> { + let before = setups::draft(app)?; + let previous = app.render_workspace.view.clone(); + let result = apply_quality(app, plan).and_then(|()| setups::persist_editor(app, &before)); + if let Err(error) = result { + app.render_workspace.view = previous; + return Err(error); + } + Ok(()) +} + pub(super) fn apply_quality(app: &mut SolveApp, plan: &Value) -> Result<(), String> { + if app.render_workspace.view.method == ImageMethod::CpuRaytrace { + return apply_cpu_quality(app, plan); + } if app.render_workspace.view.method != ImageMethod::GpuRaytrace || plan["variant"] != "fixed_samples_png" { return Err(crate::i18n::tr("render.error_quality_method").into()); } @@ -1122,6 +1417,38 @@ pub(super) fn apply_quality(app: &mut SolveApp, plan: &Value) -> Result<(), Stri view.dirty = true; Ok(()) } +fn apply_cpu_quality(app: &mut SolveApp, plan: &Value) -> Result<(), String> { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions, cpu_camera_sampling}; + let view = &app.render_workspace.view; + if view.raytrace.progressive.is_none() { + return Err(app.tr("render.cpu_quality_progressive_required").to_string()); + } + if plan["variant"] != "cpu_progressive_png" + || plan["cpu_context"] != json!({"minimum_budget":view.raytrace.budget,"adaptive":view.studio.adaptive}) + { + return Err(app.tr("render.error_quality_projection").to_string()); + } + let integer = |v: &Value| v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| app.tr("render.error_quality_projection").to_string()); + let width = integer(&plan["settings"]["width"])?; + let height = integer(&plan["settings"]["height"])?; + let progressive: CpuProgressiveOptions = serde_json::from_value(plan["cpu_options"]["progressive"].clone()).map_err(|error| error.to_string())?; + let budget: CpuBudget = serde_json::from_value(plan["cpu_options"]["budget"].clone()).map_err(|error| error.to_string())?; + if !CpuBudget::ALL.into_iter().skip_while(|b| *b != view.raytrace.budget).any(|b| b == budget) { + return Err(app.tr("render.error_quality_bounds").to_string()); + } + let sampling = cpu_camera_sampling(Some(progressive), view.studio.adaptive, budget).map_err(|error| error.to_string())?; + budget.validate_image(width, height, sampling).map_err(|error| error.to_string())?; + if view.studio.denoise { + solidcraft_engine::render::job::validate_cpu_denoise_image(width, height).map_err(|error| error.to_string())?; + } + let view = &mut app.render_workspace.view; + view.draft.width = width; + view.draft.height = height; + view.raytrace.progressive = Some(progressive); + view.raytrace.budget = budget; + view.dirty = true; + Ok(()) +} fn diagnostics(app: &mut SolveApp, ui: &mut egui::Ui) { let request = super::image_request(app); let job = app @@ -1157,9 +1484,20 @@ fn diagnostics(app: &mut SolveApp, ui: &mut egui::Ui) { cpu::captured_status(app, ui, &job); json_details(app, ui, "render.diag_job_details", &job); } - for key in - ["render.adaptive_pending", "render.exr_pending", "render.transmission_scope", "render.advanced_material_scope", "render.queue_pending"] - { + for key in ["render.adaptive_pending", "render.exr_pending"] { + ui_kit::text(ui, app.tr(key), ui_kit::Text::Note(key)); + } + let glass = match app.render_workspace.view.method { + ImageMethod::Raster => "render.output_raytrace_only", + ImageMethod::CpuRaytrace => "render.check_glass_cpu", + ImageMethod::GpuRaytrace => "render.check_glass_gpu", + }; + ui_kit::text(ui, app.tr(glass), ui_kit::Text::Note(glass)); + if app.render_workspace.view.method != ImageMethod::Raster { + let key = "render.check_media_scope"; + ui_kit::text(ui, app.tr(key), ui_kit::Text::Note(key)); + } + for key in ["render.check_media_remaining", "render.queue_pending"] { ui_kit::text(ui, app.tr(key), ui_kit::Text::Note(key)); } browse_button(app, ui, "capabilities", "render.browse_capabilities"); @@ -1193,12 +1531,25 @@ pub(super) fn fit_subject(app: &mut SolveApp) -> Result<(), String> { Ok(()) } -pub(super) fn restore_camera(app: &mut SolveApp) -> Result<(), String> { - let name = app.render_workspace.view.name.clone(); +/// Revert accepts only the restored camera as clean. Numerical and temporary +/// material drafts retain their independent dirty state and confirmation guard. +pub(super) fn restore_saved_camera(app: &mut SolveApp, name: &str) -> Result<(), String> { app.run("render.settings.apply", json!({"name":name}))?; app.follow_view_request(false); + app.ui.perspective = app.cam.fov > 0.0; + if app.render_workspace.view.name == name + && let Some(clean) = &mut app.render_workspace.view.clean_setup + { + clean.camera = app.cam; + } + setups::refresh_dirty(app); Ok(()) } + +pub(super) fn restore_camera(app: &mut SolveApp) -> Result<(), String> { + let name = app.render_workspace.view.name.clone(); + restore_saved_camera(app, &name) +} pub(super) fn confirmation_open(app: &SolveApp) -> bool { app.render_workspace.view.inspector.pending.is_some() || app.render_workspace.view.save_shot_name.is_some() @@ -1226,7 +1577,7 @@ fn gpu_status(app: &mut SolveApp, ui: &mut egui::Ui) { super::retry_crashed_setup(app, ui); } super::PathHost::NotStarted if app.render_workspace.view.method == ImageMethod::GpuRaytrace => { - ui_kit::text(ui, app.tr("render.gpu_unavailable"), ui_kit::Text::Note("render.gpu_unavailable")); + ui_kit::text(ui, app.tr("render.gpu_path_not_started"), ui_kit::Text::Note("render.gpu_path_not_started")); } super::PathHost::NotStarted | super::PathHost::Ready(_) => {} } diff --git a/crates/ui-egui/src/render_workspace_prepare.rs b/crates/ui-egui/src/render_workspace_prepare.rs new file mode 100644 index 000000000..948213ad9 --- /dev/null +++ b/crates/ui-egui/src/render_workspace_prepare.rs @@ -0,0 +1,1429 @@ +//! Native Check/Start ownership. Preparation and retirement use one bounded +//! worker; the window accepts only the already-proved real-session commit. +use crate::SolveApp; +use egui::Context; +use serde_json::{Value, json}; +use solidcraft_engine::render_preparation::Kind; + +pub(crate) fn enabled(app: &SolveApp) -> bool { + !cfg!(target_arch = "wasm32") && app.apply_off_thread.is_some() +} + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use super::*; + use crate::control::ControlRequest; + use solidcraft_engine::render::job::CancelToken; + use solidcraft_engine::render_preparation::{Prepared, finish_retained, prepare}; + use solidcraft_engine::schema::ParamCheck; + use std::collections::BTreeMap; + use std::sync::mpsc::{Receiver, SyncSender, TryRecvError, TrySendError}; + use std::sync::{Arc, Weak}; + + #[derive(Default)] + pub(crate) struct State { + pending: Option, + batches: batches::State, + #[cfg(test)] + proof_ready: Option>, + #[cfg(test)] + retired_probe: Option>, + #[cfg(test)] + disconnect_retirement: bool, + #[cfg(test)] + disconnect_input: bool, + } + impl Drop for State { + fn drop(&mut self) { + if let Some(pending) = &mut self.pending { + // This app-global owner is not replaced on a tab/document reset. + // Real app teardown may perform ordinary destructors. During + // interaction, a failed return stays held in this bounded slot. + if !pending.committed { + pending.cancel.cancel(); + } + if let Some(worker) = &mut pending.worker { + let _ = worker.retire(); + } + } + } + } + + struct Guard { + uid: u64, + document: Weak, + model: Weak, + revision: u64, + camera: (solidcraft_engine::render::UpAxis, [u64; 8]), + moves: BTreeMap, + exploded: BTreeMap, + visibility: Value, + shot: String, + visual: Value, + lights: solidcraft_engine::schema::render_lights::Visibility, + } + fn camera(app: &SolveApp) -> (solidcraft_engine::render::UpAxis, [u64; 8]) { + let c = app.cam; + (c.up, [c.target.x, c.target.y, c.target.z, c.yaw, c.pitch, c.roll, c.distance, c.fov].map(f64::to_bits)) + } + fn same_moves(a: &BTreeMap, b: &BTreeMap) -> bool { + a.len() == b.len() + && a.iter() + .zip(b) + .all(|((ka, a), (kb, b))| ka == kb && a.iter().flatten().zip(b.iter().flatten()).all(|(a, b)| a.to_bits() == b.to_bits())) + } + impl Guard { + fn new(app: &SolveApp) -> Self { + Self { + uid: app.session.uid, + document: Arc::downgrade(&app.session.doc), + model: Arc::downgrade(&app.session.model.state()), + revision: app.session.revision, + camera: camera(app), + moves: app.session.pending_moves.clone(), + exploded: app.session.exploded.clone(), + visibility: json!(app.session.visibility), + shot: app.render_workspace.view.name.clone(), + visual: super::super::ribbon::final_visual(app), + lights: app.render_workspace.view.lights.visibility.clone(), + } + } + fn current(&self, app: &SolveApp) -> bool { + self.document.ptr_eq(&Arc::downgrade(&app.session.doc)) + && self.model.ptr_eq(&Arc::downgrade(&app.session.model.state())) + && self.revision == app.session.revision + && !app.session.model.is_stale() + && self.camera == camera(app) + && same_moves(&self.moves, &app.session.pending_moves) + && same_moves(&self.exploded, &app.session.exploded) + && self.visibility == json!(app.session.visibility) + && self.shot == app.render_workspace.view.name + && self.visual == super::super::ribbon::final_visual(app) + && self.lights == app.render_workspace.view.lights.visibility + && !app.file_load.busy() + && app.file_picker.is_none() + && app.saving.is_none() + } + } + + enum Origin { + Ui, + Control { request: ControlRequest, echo: Option }, + } + struct Pending { + kind: Kind, + params: Value, + unfiltered: Value, + guard: Guard, + origin: Option, + scope: Option, + cancel: CancelToken, + cancelled: Option, + worker: Option, + completion: Option>, + committed: bool, + applied: bool, + unavailable: Option, + warnings: Vec, + level: ParamCheck, + #[cfg(test)] + proof_ready: Option>, + #[cfg(test)] + retired_probe: Option>, + #[cfg(test)] + disconnect_retirement: bool, + #[cfg(test)] + disconnect_input: bool, + } + struct PreparationInput { + snapshot: solidcraft_engine::Session, + kind: Kind, + params: Value, + cancel: CancelToken, + scope: Option, + } + struct Worker { + ready: Receiver>, + returning: SyncSender, + acknowledged: Receiver<()>, + prepared: Option, + returned: bool, + // A worker which disconnects before receiving its source cannot cause + // that source to be destroyed on the window. True app teardown owns it. + unavailable_input: Option, + } + impl Worker { + fn retire(&mut self) -> Result<(), String> { + if self.returned { + return Ok(()); + } + let Some(prepared) = self.prepared.take() else { return Ok(()) }; + match self.returning.try_send(prepared) { + Ok(()) => { + self.returned = true; + Ok(()) + } + Err(TrySendError::Full(prepared) | TrySendError::Disconnected(prepared)) => { + // Never free a returned heavy capture on the interactive UI, + // report released credit, or start an unbounded fallback. + self.prepared = Some(prepared); + Err(crate::i18n::tr("render.preparation_retirement_failed").into()) + } + } + } + } + fn command(kind: Kind) -> &'static str { + match kind { + Kind::Check => "render.preflight", + Kind::Start => "render.start", + } + } + fn cancel_pending(pending: &mut Pending, reason: String) { + if pending.committed { + return; + } + if pending.cancelled.is_none() { + pending.cancelled = Some(reason) + } + pending.cancel.cancel(); + } + fn begin( + app: &mut SolveApp, + kind: Kind, + request: Value, + origin: Origin, + scope: Option, + level: ParamCheck, + ) -> Result<(), String> { + if app.render_preparation.pending.is_some() || super::super::live::final_pending(app) || batches::unavailable(&app.render_preparation.batches) + { + return Err(app.tr("render.ribbon_job_active").into()); + } + if kind == Kind::Start && batches::busy(&app.render_preparation.batches, app.session.uid) && request.get("replace") != Some(&json!(true)) { + return Err(app.tr("render.ribbon_job_active").into()); + } + if app.file_load.busy() || app.file_picker.is_some() || app.saving.is_some() { + return Err(app.tr("render.ribbon_finish_dialog").into()); + } + app.session.set_validation(app.preferences.validation); + let params = super::super::light::filter_request(app, request.clone())?; + let issues: Vec = solidcraft_engine::schema::issues(command(kind), ¶ms).into_iter().map(|issue| issue.message).collect(); + if level == ParamCheck::Strict + && let Some(first) = issues.first() + { + return Err(solidcraft_engine::params::bad(command(kind), first).to_string()); + } + let pending = Pending { + kind, + params, + unfiltered: request, + guard: Guard::new(app), + origin: Some(origin), + scope, + cancel: CancelToken::default(), + cancelled: None, + worker: None, + completion: None, + committed: false, + applied: false, + unavailable: None, + warnings: if level == ParamCheck::Warn { issues } else { Vec::new() }, + level, + #[cfg(test)] + proof_ready: app.render_preparation.proof_ready.clone(), + #[cfg(test)] + retired_probe: app.render_preparation.retired_probe.clone(), + #[cfg(test)] + disconnect_retirement: app.render_preparation.disconnect_retirement, + #[cfg(test)] + disconnect_input: app.render_preparation.disconnect_input, + }; + super::super::live::suspend_for_preparation(app); + app.render_preparation.pending = Some(pending); + Ok(()) + } + #[cfg(test)] + pub(crate) fn test_configure(app: &mut SolveApp, ready: SyncSender, retired: SyncSender<()>, disconnect: bool) { + app.render_preparation.proof_ready = Some(ready); + app.render_preparation.retired_probe = Some(retired); + app.render_preparation.disconnect_retirement = disconnect; + } + #[cfg(test)] + pub(crate) fn test_disconnect_input(app: &mut SolveApp) { + app.render_preparation.disconnect_input = true; + } + + pub(crate) fn begin_ui(app: &mut SolveApp, kind: Kind, request: Value) -> Result<(), String> { + begin(app, kind, request, Origin::Ui, solidcraft_engine::io::vfs::current_scope(), app.session.param_check) + } + pub(crate) fn begin_batch_ui(app: &mut SolveApp, request: Value) -> Result<(), String> { + batches::begin(app, request, Origin::Ui, solidcraft_engine::io::vfs::current_scope(), app.session.param_check) + } + pub(crate) fn busy(app: &SolveApp) -> bool { + app.render_preparation.pending.is_some() || batches::busy(&app.render_preparation.batches, app.session.uid) + } + pub(crate) fn cancel(app: &mut SolveApp) -> bool { + let Some(pending) = &mut app.render_preparation.pending else { + let mut state = std::mem::take(&mut app.render_preparation); + let uid = app.session.uid; + let cancelled = batches::cancel_owner(app, &mut state.batches, uid); + app.render_preparation = state; + return cancelled; + }; + if pending.committed || pending.applied { + return false; + } + cancel_pending(pending, crate::i18n::tr("render.preparation_cancelled").into()); + true + } + pub(crate) fn document_closing(app: &mut SolveApp, uid: u64) { + let mut state = std::mem::take(&mut app.render_preparation); + if let Some(pending) = &mut state.pending + && pending.guard.uid == uid + && !pending.committed + { + cancel_pending(pending, crate::i18n::tr("render.preparation_cancelled").into()); + } + batches::cancel_owner(app, &mut state.batches, uid); + app.render_preparation = state; + } + + fn spawn(app: &SolveApp, pending: &Pending) -> Result { + let (input_tx, input_rx) = std::sync::mpsc::sync_channel::(1); + let (ready_tx, ready) = std::sync::mpsc::sync_channel(1); + let (returning, retired) = std::sync::mpsc::sync_channel(1); + let (ack, acknowledged) = std::sync::mpsc::sync_channel(1); + #[cfg(test)] + let gate = app.apply_gate.clone(); + #[cfg(test)] + let proof_ready = pending.proof_ready.clone(); + #[cfg(test)] + let retired_probe = pending.retired_probe.clone(); + #[cfg(test)] + let disconnect_retirement = pending.disconnect_retirement; + #[cfg(test)] + let disconnect_input = pending.disconnect_input; + #[cfg(test)] + let (input_closed_tx, input_closed_rx) = std::sync::mpsc::sync_channel(1); + solidcraft_engine::kernel::kernel_thread("render-preparation") + .spawn(move || { + #[cfg(test)] + if disconnect_input { + drop(input_rx); + let _ = input_closed_tx.send(()); + return; + } + let Ok(PreparationInput { snapshot, kind, params, cancel, scope }) = input_rx.recv() else { return }; + solidcraft_engine::io::vfs::scoped(scope, || { + let result = prepare(snapshot, kind, params, cancel).map_err(|error| error.to_string()); + #[cfg(test)] + if let Some(ready) = proof_ready { + let _ = ready.send(result.is_ok()); + } + #[cfg(test)] + if let Some(gate) = gate { + // Deterministic test delay after proof owns its actual leases. + // A disconnected gate drops the result here on this worker. + if gate.lock().map_or(true, |gate| gate.recv().is_err()) { + drop(result); + let _ = ready_tx.send(Err("render preparation test gate disconnected".into())); + let _ = ack.send(()); + if let Some(retired) = retired_probe { + let _ = retired.send(()); + } + return; + } + } + let successful = result.is_ok(); + #[cfg(test)] + if disconnect_retirement && successful { + // Inject an actual disconnected return/ack channel after + // handing the owned proof to the ordinary UI receiver. + if let Err(returned) = ready_tx.send(result) { + drop(returned); + } + return; + } + match ready_tx.send(result) { + Ok(()) if successful => { + if let Ok(prepared) = retired.recv() { + drop(prepared); + } + } + // A closed window never leaves a heavy result on that window. + // SendError retains it until this worker's drop below. + Err(returned) => drop(returned), + Ok(()) => {} + } + let _ = ack.send(()); + #[cfg(test)] + if let Some(retired) = retired_probe { + let _ = retired.send(()); + } + }); + }) + .map_err(|error| error.to_string())?; + // Only create the heavy source after a worker exists. Failed OS thread + // creation therefore drops no scratch Session on the window. + let mut snapshot = app.session.scratch(); + snapshot.param_check = pending.level; + let input = PreparationInput { + snapshot, + kind: pending.kind, + params: pending.params.clone(), + cancel: pending.cancel.clone(), + scope: pending.scope.clone(), + }; + #[cfg(test)] + if disconnect_input { + let _ = input_closed_rx.recv(); + } + let unavailable_input = input_tx.try_send(input).err().map(|error| match error { + TrySendError::Full(input) | TrySendError::Disconnected(input) => input, + }); + Ok(Worker { ready, returning, acknowledged, prepared: None, returned: false, unavailable_input }) + } + fn answer(pending: &mut Pending) { + let Some(origin) = pending.origin.take() else { return }; + let result = pending.completion.take().unwrap_or_else(|| Err(crate::i18n::tr("render.preparation_retirement_failed").into())); + if let Origin::Control { request, echo } = origin { + let mut reply = match result { + Ok(value) => json!({"ok":true,"result":value}), + Err(error) => json!({"ok":false,"error":error}), + }; + if let Some(level) = echo { + reply["param_check"] = json!(level.name()) + } + let _ = request.reply.send(reply); + } + } + fn apply(app: &mut SolveApp, pending: &mut Pending) { + let kind = pending.kind; + let level = pending.level; + let scope = pending.scope.clone(); + let chat_turn = match &pending.origin { + Some(Origin::Control { request, .. }) => request.chat_turn.clone(), + _ => None, + }; + let Some(prepared) = pending.worker.as_mut().and_then(|worker| worker.prepared.as_mut()) else { return }; + let mut committed = false; + let mut result = crate::agent_chat::with_tool_request(app, chat_turn.as_ref(), |app| { + solidcraft_engine::io::vfs::scoped(scope, || { + app.finish_render_preparation(command(kind), &pending.params, |session| { + let own = session.param_check; + session.param_check = level; + let result = finish_retained(session, prepared).map_err(|error| error.to_string()); + session.param_check = own; + committed = kind == Kind::Start && result.is_ok(); + result + }) + }) + }); + pending.committed = committed; + if let Ok(value) = &mut result { + if !pending.warnings.is_empty() + && let Some(object) = value.as_object_mut() + { + object.insert("param_warnings".into(), json!(pending.warnings)); + } + if matches!(pending.origin, Some(Origin::Ui)) && pending.kind == Kind::Start { + result = super::super::ribbon::follow_started(app, value).map(|()| value.clone()); + } + } + if pending.kind == Kind::Check { + match &result { + Ok(reply) => { + super::super::cpu::record_checked(app, &pending.unfiltered, reply); + super::super::inspector::record_check(app, &pending.unfiltered, reply); + app.set_status(app.tr("render.image_supported").to_string(), false); + } + Err(error) => super::super::inspector::record_check(app, &pending.unfiltered, &json!({"error":error})), + } + } + if let Err(error) = &result { + app.set_status(error.clone(), true) + } + pending.completion = Some(result); + pending.applied = true; + } + + fn report_failure(app: &mut SolveApp, pending: &Pending, error: &str) { + if pending.kind == Kind::Check { + super::super::inspector::record_check(app, &pending.unfiltered, &json!({"error":error})); + } + app.set_status(error.to_string(), pending.cancelled.is_none()); + } + + pub(crate) fn tick(app: &mut SolveApp, ctx: &Context) { + let mut state = std::mem::take(&mut app.render_preparation); + // Always poll an existing batch worker, including while an individual + // request waits. A waiting Single cannot deadlock batch retirement. + batches::poll(app, ctx, &mut state.batches); + // A queued same-document replacement cannot overtake the original + // first batch front. Prove/commit/retire that front first, then leave + // later fronts paused while replacement proof runs. A failed proof + // therefore resumes the original queue without cancelling it. + let prior_first = state + .pending + .as_ref() + .filter(|p| p.kind == Kind::Start && p.unfiltered.get("replace") == Some(&json!(true))) + .filter(|p| p.worker.is_none() && p.cancelled.is_none() && batches::first_pending(&state.batches, p.guard.uid)) + .map(|p| p.guard.uid); + if let Some(uid) = prior_first { + batches::schedule(app, ctx, &mut state.batches, Some(uid)); + } + let Some(pending) = &mut state.pending else { + batches::schedule(app, ctx, &mut state.batches, None); + app.render_preparation = state; + return; + }; + if !pending.applied { + if pending.worker.is_none() && batches::unavailable(&state.batches) { + cancel_pending(pending, app.tr("render.preparation_unavailable").into()); + } + if !pending.guard.current(app) { + cancel_pending(pending, app.tr("render.live.final_changed").into()) + } + if let Some(Origin::Control { request, .. }) = &pending.origin + && crate::control::chat_turn_cancelled(request.chat_turn.as_deref()) + { + cancel_pending(pending, crate::i18n::tr("render.preparation_cancelled").into()); + } + } + if pending.worker.is_none() { + if let Some(error) = &pending.cancelled { + report_failure(app, pending, error); + pending.completion = Some(Err(error.clone())); + answer(pending); + state.pending = None; + } else if prior_first.is_none() && !batches::lane_busy(&state.batches) && super::super::live::preparation_ready(app) { + match spawn(app, pending) { + Ok(worker) => { + if worker.unavailable_input.is_some() { + pending.unavailable = Some(app.tr("render.preparation_retirement_failed").into()); + } + pending.worker = Some(worker); + } + Err(error) => { + report_failure(app, pending, &error); + pending.completion = Some(Err(error)); + answer(pending); + state.pending = None + } + } + } + app.render_preparation = state; + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + return; + } + if pending.unavailable.is_none() { + let ready = pending.worker.as_ref().filter(|_| !pending.applied).map(|worker| worker.ready.try_recv()); + match ready { + Some(Ok(Ok(prepared))) => { + if let Some(worker) = &mut pending.worker { + worker.prepared = Some(prepared) + } + if let Some(error) = &pending.cancelled { + report_failure(app, pending, error); + pending.completion = Some(Err(error.clone())); + pending.applied = true; + } else { + apply(app, pending); + } + } + Some(Ok(Err(error))) => { + report_failure(app, pending, &error); + pending.completion = Some(Err(error)); + pending.applied = true + } + Some(Err(TryRecvError::Disconnected)) => pending.unavailable = Some(app.tr("render.preparation_retirement_failed").into()), + _ => {} + } + if pending.applied { + if let Some(worker) = &mut pending.worker + && let Err(error) = worker.retire() + { + pending.unavailable = Some(error) + } + if pending.unavailable.is_none() { + match pending.worker.as_ref().map(|worker| worker.acknowledged.try_recv()) { + Some(Ok(())) => { + answer(pending); + state.pending = None + } + Some(Err(TryRecvError::Disconnected)) => pending.unavailable = Some(app.tr("render.preparation_retirement_failed").into()), + _ => {} + } + } + } + } + if let Some(pending) = &mut state.pending + && let Some(error) = &pending.unavailable + { + app.set_status(error.clone(), true); + // A committed Start has a real identity even if retirement fails. + // Never hide that owning job or cancel its transferred token. + if !pending.committed { + pending.completion = Some(Err(error.clone())) + } + answer(pending); + } + app.render_preparation = state; + if app.render_preparation.pending.is_some() || batches::has_work(&app.render_preparation.batches) { + ctx.request_repaint_after(std::time::Duration::from_millis(20)) + } + } + + pub(crate) fn progress(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + let Some(pending) = &app.render_preparation.pending else { return batches::progress(app, ui) }; + let key = if pending.unavailable.is_some() { + "render.preparation_unavailable" + } else if pending.cancelled.is_some() { + "render.image_cancelling" + } else if pending.applied { + "render.preparation_retiring" + } else if pending.worker.is_none() && batches::lane_busy(&app.render_preparation.batches) { + "render.batch_waiting_worker" + } else if pending.worker.is_none() { + "render.live.final_waiting" + } else if pending.kind == Kind::Check { + "render.preparation_checking" + } else { + "render.image_preparing" + }; + crate::ui_kit::text(ui, app.tr(key), crate::ui_kit::Text::Inline); + let cancel = crate::ui_kit::button( + ui, + app.tr("cmd.render_cancel"), + crate::ui_kit::Button::Enabled(pending.unavailable.is_none() && (!pending.applied || pending.committed)), + ); + crate::scenario::publish_target("render:preparation-cancel", cancel.rect); + if cancel.clicked() { + super::super::ribbon::perform_job(app, "render.cancel").unwrap_or_else(|error| app.set_status(error, true)) + } + true + } + pub(crate) fn inspect(app: &SolveApp) -> Value { + app.render_preparation.pending.as_ref().map_or(Value::Null, |pending| { + json!({ + "kind":command(pending.kind),"waiting_for_live":pending.worker.is_none()&&!super::super::live::preparation_ready(app), + "waiting_for_worker":pending.worker.is_none()&&batches::lane_busy(&app.render_preparation.batches),"preparing":pending.worker.is_some()&&!pending.applied, + "cancelled":pending.cancelled,"retiring":pending.applied,"unavailable":pending.unavailable,"committed":pending.committed + }) + }) + } + pub(crate) fn inspect_batches(app: &SolveApp) -> Value { + batches::inspect(&app.render_preparation.batches) + } + + // One coordinator shares the native preparation lane with individual Check/Start. + mod batches { + use super::*; + use solidcraft_engine::render_preparation::batch as api; + use std::sync::mpsc; + + #[derive(Default)] + pub(super) struct State { + slots: [Option; crate::documents::MAX_OPEN], + active: Option, + cursor: usize, + } + struct Source { + uid: u64, + document: Weak, + model: Weak, + revision: u64, + moves: BTreeMap, + exploded: BTreeMap, + context: Value, + } + impl Source { + fn context(s: &solidcraft_engine::Session) -> Value { + json!({"visibility":s.visibility,"sketch":s.active_sketch,"feature_sketch":s.feature_edit_sketch, + "component":s.active_component,"occurrence":s.active_occurrence_path, + "camera":s.camera.map(|c|(c.up,[c.target.x,c.target.y,c.target.z,c.yaw,c.pitch,c.roll,c.distance,c.fov].map(f64::to_bits)))}) + } + fn new(s: &solidcraft_engine::Session) -> Self { + Self { + uid: s.uid, + document: Arc::downgrade(&s.doc), + model: Arc::downgrade(&s.model.state()), + revision: s.revision, + moves: s.pending_moves.clone(), + exploded: s.exploded.clone(), + context: Self::context(s), + } + } + fn current(&self, s: &solidcraft_engine::Session) -> bool { + self.uid == s.uid + && self.document.ptr_eq(&Arc::downgrade(&s.doc)) + && self.model.ptr_eq(&Arc::downgrade(&s.model.state())) + && self.revision == s.revision + && !s.model.is_stale() + && same_moves(&self.moves, &s.pending_moves) + && same_moves(&self.exploded, &s.exploded) + && self.context == Self::context(s) + } + } + struct First { + params: Option, + scope: Option, + source: Source, + origin: Option, + level: ParamCheck, + warnings: Vec, + } + struct Slot { + uid: u64, + first: Option, + plan: Option, + cancelled: Option, + #[cfg(test)] + proof_ready: Option>, + #[cfg(test)] + retired_probe: Option>, + #[cfg(test)] + disconnect_retirement: bool, + } + // One fixed, by-value message in the existing capacity-one channel. Private + // constructors make these slots exclusive; no new Box/allocation or owner + // transfer is introduced before the empty worker has started. The extra + // inline Option slot is bounded UI channel metadata, not renderer credit. + struct Input { + claim: Option, + retire: Option, + } + impl Input { + fn claim(claim: api::Claim) -> Self { + Self { claim: Some(claim), retire: None } + } + fn retire(plan: api::Plan) -> Self { + Self { claim: None, retire: Some(plan) } + } + fn is_retirement(&self) -> bool { + self.retire.is_some() + } + } + struct Worker { + ready: Receiver, + returning: SyncSender, + acknowledged: Receiver<()>, + prepared: Option, + _unavailable_input: Option, + returned: bool, + } + struct Active { + slot: usize, + worker: Worker, + cancel: CancelToken, + cleanup_only: bool, + applied: bool, + committed: bool, + completion: Option>, + unavailable: Option, + } + impl Drop for State { + fn drop(&mut self) { + // Only the real app teardown destroys these global slots. Tab, + // document and host lifecycles never replace this owner. + if let Some(active) = &mut self.active { + if !active.committed { + active.cancel.cancel(); + } + let _ = active.worker.retire(); + } + } + } + impl Worker { + fn retire(&mut self) -> Result<(), String> { + if self.returned { + return Ok(()); + } + let Some(prepared) = self.prepared.take() else { return Ok(()) }; + match self.returning.try_send(prepared) { + Ok(()) => { + self.returned = true; + Ok(()) + } + Err(TrySendError::Full(p) | TrySendError::Disconnected(p)) => { + self.prepared = Some(p); + Err(crate::i18n::tr("render.preparation_retirement_failed").into()) + } + } + } + fn send(&mut self, sender: SyncSender, input: Input) -> Result<(), String> { + match sender.try_send(input) { + Ok(()) => Ok(()), + Err(TrySendError::Full(input) | TrySendError::Disconnected(input)) => { + self._unavailable_input = Some(input); + Err(crate::i18n::tr("render.preparation_retirement_failed").into()) + } + } + } + } + fn empty_worker(app: &SolveApp, slot: &Slot) -> Result<(Worker, SyncSender), String> { + let (input_tx, input_rx) = mpsc::sync_channel::(1); + let (ready_tx, ready) = mpsc::sync_channel(1); + let (returning, returned) = mpsc::sync_channel(1); + let (ack, acknowledged) = mpsc::sync_channel(1); + #[cfg(test)] + let gate = app.apply_gate.clone(); + #[cfg(test)] + let proof = slot.proof_ready.clone(); + #[cfg(test)] + let retired = slot.retired_probe.clone(); + #[cfg(test)] + let disconnect = slot.disconnect_retirement; + #[cfg(not(test))] + let _ = (app, slot); + solidcraft_engine::kernel::kernel_thread("render-batch-preparation") + .spawn(move || { + let release = match input_rx.recv() { + Ok(Input { claim: Some(claim), retire: None }) => api::with_scope(claim, |claim| { + let prepared = api::prepare(claim); + #[cfg(test)] + if let Some(proof) = proof { + let _ = proof.send(true); + } + #[cfg(test)] + if let Some(gate) = gate + && gate.lock().map_or(true, |gate| gate.recv().is_err()) + { + drop(prepared); + return true; + } + #[cfg(test)] + if disconnect { + drop(returned); + if let Err(prepared) = ready_tx.send(prepared) { + drop(prepared); + } + return false; + } + match ready_tx.send(prepared) { + Ok(()) => { + if let Ok(prepared) = returned.recv() { + drop(prepared); + } + } + Err(prepared) => drop(prepared), + } + true + }), + Ok(Input { claim: None, retire: Some(plan) }) => { + api::retire_plan(plan); + true + } + // Constructors never produce an invalid choice. Keep even an + // internally malformed message's last owners on this worker, + // under their own original scopes, before acknowledging it. + Ok(input) => { + if let Some(claim) = input.claim { + api::with_scope(claim, drop); + } + if let Some(plan) = input.retire { + api::retire_plan(plan); + } + true + } + Err(_) => true, + }; + // Scope and all source/plan backing have retired before ack. + if !release { + return; + } + let _ = ack.send(()); + #[cfg(test)] + if let Some(retired) = retired { + let _ = retired.send(()); + } + }) + .map_err(|e| e.to_string())?; + Ok((Worker { ready, returning, acknowledged, prepared: None, _unavailable_input: None, returned: false }, input_tx)) + } + pub(super) fn lane_busy(state: &State) -> bool { + state.active.is_some() + } + pub(super) fn unavailable(state: &State) -> bool { + state.active.as_ref().is_some_and(|a| a.unavailable.is_some()) + } + pub(super) fn busy(state: &State, uid: u64) -> bool { + state.slots.iter().flatten().any(|s| s.uid == uid) + } + pub(super) fn has_work(state: &State) -> bool { + state.slots.iter().any(Option::is_some) + } + pub(super) fn first_pending(state: &State, uid: u64) -> bool { + state.slots.iter().flatten().any(|s| s.uid == uid && s.first.is_some()) + } + pub(super) fn begin( + app: &mut SolveApp, + params: Value, + origin: Origin, + scope: Option, + level: ParamCheck, + ) -> Result<(), String> { + if super::super::super::live::final_pending(app) { + return Err(app.tr("render.ribbon_job_active").into()); + } + if unavailable(&app.render_preparation.batches) || app.render_preparation.pending.as_ref().is_some_and(|p| p.unavailable.is_some()) { + return Err(app.tr("render.preparation_unavailable").into()); + } + if busy(&app.render_preparation.batches, app.session.uid) { + return Err(app.tr("render.ribbon_job_active").into()); + } + if app.file_load.busy() || app.file_picker.is_some() || app.saving.is_some() { + return Err(app.tr("render.ribbon_finish_dialog").into()); + } + app.session.set_validation(app.preferences.validation); + let warnings: Vec<_> = solidcraft_engine::schema::issues("render.batch", ¶ms).into_iter().map(|i| i.message).collect(); + if level == ParamCheck::Strict + && let Some(first) = warnings.first() + { + return Err(solidcraft_engine::params::bad("render.batch", first).to_string()); + } + let index = app + .render_preparation + .batches + .slots + .iter() + .position(Option::is_none) + .ok_or_else(|| app.tr("render.batch_owner_limit").to_string())?; + // UI passes its already-filtered request. Native control preserves + // the exact supplied API intent, including first-saved fallback. + let first = First { + params: Some(params), + scope, + source: Source::new(&app.session), + origin: Some(origin), + level, + warnings: if level == ParamCheck::Warn { warnings } else { Vec::new() }, + }; + let slot = Slot { + uid: app.session.uid, + first: Some(first), + plan: None, + cancelled: None, + #[cfg(test)] + proof_ready: app.render_preparation.proof_ready.clone(), + #[cfg(test)] + retired_probe: app.render_preparation.retired_probe.clone(), + #[cfg(test)] + disconnect_retirement: app.render_preparation.disconnect_retirement, + }; + super::super::super::live::suspend_for_preparation(app); + app.render_preparation.batches.slots[index] = Some(slot); + Ok(()) + } + fn answer(first: &mut First, result: Result) { + if let Some(Origin::Control { request, echo }) = first.origin.take() { + let mut reply = match result { + Ok(v) => json!({"ok":true,"result":v}), + Err(e) => json!({"ok":false,"error":e}), + }; + if let Some(level) = echo { + reply["param_check"] = json!(level.name()); + } + let _ = request.reply.send(reply); + } + } + pub(super) fn cancel_owner(app: &mut SolveApp, state: &mut State, uid: u64) -> bool { + let mut found = false; + for (i, slot) in state.slots.iter_mut().enumerate() { + if let Some(slot) = slot + && slot.uid == uid + { + found = true; + slot.cancelled.get_or_insert_with(|| crate::i18n::tr("render.preparation_cancelled").into()); + if let Some(active) = &mut state.active + && active.slot == i + && !active.committed + { + active.cancel.cancel(); + } + } + } + if found { + let _ = crate::documents::with_render_owner(app, uid, |s, _| api::cancel(s)); + } + found + } + fn commit(app: &mut SolveApp, uid: u64, prepared: &mut api::Prepared, first: Option<&First>) -> Result { + let level = first.map(|f| f.level); + let chat = first.and_then(|f| f.origin.as_ref()).and_then(|o| match o { + Origin::Control { request, .. } => request.chat_turn.clone(), + Origin::Ui => None, + }); + let mut finish = |s: &mut solidcraft_engine::Session| { + let own = s.param_check; + if let Some(level) = level { + s.param_check = level; + } + let out = api::finish_retained(s, prepared).map_err(|e| e.to_string()); + s.param_check = own; + out + }; + if app.session.uid == uid { + crate::agent_chat::with_tool_request(app, chat.as_ref(), |app| app.finish_render_preparation("render.batch", &Value::Null, finish)) + } else { + crate::documents::with_render_owner(app, uid, |session, view| { + let out = finish(session); + if out.is_ok() { + super::super::super::follow_batch_view(view, session.render_queue_state()); + } + out + }) + .unwrap_or_else(|| Err(crate::i18n::tr("render.live.final_changed").into())) + } + } + pub(super) fn poll(app: &mut SolveApp, ctx: &Context, state: &mut State) { + let Some(mut active) = state.active.take() else { return }; + let Some(slot) = state.slots[active.slot].as_mut() else { + active.unavailable = Some(app.tr("render.preparation_retirement_failed").into()); + state.active = Some(active); + return; + }; + let mut released = false; + if !active.applied && !active.cleanup_only { + let current = crate::documents::render_owner(app, slot.uid); + if current.is_none() || slot.first.as_ref().is_some_and(|f| current.is_none_or(|s| !f.source.current(s))) { + slot.cancelled.get_or_insert_with(|| crate::i18n::tr("render.live.final_changed").into()); + active.cancel.cancel(); + } + if slot.first.as_ref().and_then(|f| f.origin.as_ref()).is_some_and(|o| match o { + Origin::Control { request, .. } => crate::control::chat_turn_cancelled(request.chat_turn.as_deref()), + Origin::Ui => false, + }) { + slot.cancelled.get_or_insert_with(|| crate::i18n::tr("render.preparation_cancelled").into()); + active.cancel.cancel(); + } + } + if active.unavailable.is_none() && !active.applied && !active.cleanup_only { + match active.worker.ready.try_recv() { + Ok(mut prepared) => { + let mut result = commit(app, slot.uid, &mut prepared, slot.first.as_ref()); + active.committed = prepared.committed(); + if let Ok(reply) = &mut result { + if let Some(first) = &slot.first + && !first.warnings.is_empty() + && let Some(obj) = reply.as_object_mut() + { + obj.insert("param_warnings".into(), json!(first.warnings)); + } + match api::take_plan(&mut prepared) { + Ok(plan) => slot.plan = plan, + Err(e) => result = Err(e.to_string()), + } + } + active.worker.prepared = Some(prepared); + active.applied = true; + active.completion = Some(result); + } + Err(TryRecvError::Disconnected) => active.unavailable = Some(app.tr("render.preparation_retirement_failed").into()), + Err(TryRecvError::Empty) => {} + } + } + if active.unavailable.is_none() && (active.applied || active.cleanup_only) { + if let Err(e) = active.worker.retire() { + active.unavailable = Some(e); + } + if active.unavailable.is_none() { + match active.worker.acknowledged.try_recv() { + Ok(()) => { + let result = active.completion.take().unwrap_or(Ok(Value::Null)); + if let Err(error) = &result { + app.set_status(error.clone(), slot.cancelled.is_none() || active.cleanup_only); + } + if let Some(first) = &mut slot.first { + answer(first, result); + } + slot.first = None; + let index = active.slot; + released = true; + // A Plan is never dropped by clearing this slot. + // Cancelled committed plans get a separate worker retirement. + if state.slots[index].as_ref().is_some_and(|s| s.plan.is_none()) { + state.slots[index] = None; + } + } + Err(TryRecvError::Disconnected) => active.unavailable = Some(app.tr("render.preparation_retirement_failed").into()), + Err(TryRecvError::Empty) => {} + } + } + } + if let Some(error) = &active.unavailable { + app.set_status(error.clone(), true); + if let Some(slot) = state.slots[active.slot].as_mut() + && let Some(first) = &mut slot.first + { + let reply = if active.committed { active.completion.take().unwrap_or_else(|| Err(error.clone())) } else { Err(error.clone()) }; + answer(first, reply); + } + } + if !released { + state.active = Some(active); + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + } + } + pub(super) fn schedule(app: &mut SolveApp, ctx: &Context, state: &mut State, only_first: Option) { + if state.active.is_some() { + return; + } + for offset in 0..state.slots.len() { + let index = (state.cursor + offset) % state.slots.len(); + let Some(slot) = state.slots[index].as_mut() else { continue }; + if only_first.is_some_and(|uid| slot.uid != uid || slot.first.is_none()) { + continue; + } + let owner = crate::documents::render_owner(app, slot.uid); + if owner.is_none() || slot.first.as_ref().is_some_and(|f| owner.is_none_or(|s| !f.source.current(s))) { + slot.cancelled.get_or_insert_with(|| crate::i18n::tr("render.live.final_changed").into()); + } + if slot.first.as_ref().and_then(|f| f.origin.as_ref()).is_some_and(|o| match o { + Origin::Control { request, .. } => crate::control::chat_turn_cancelled(request.chat_turn.as_deref()), + Origin::Ui => false, + }) { + slot.cancelled.get_or_insert_with(|| crate::i18n::tr("render.preparation_cancelled").into()); + } + if slot.cancelled.is_some() && slot.plan.is_none() { + if let Some(first) = &mut slot.first { + answer(first, Err(slot.cancelled.clone().unwrap_or_default())); + } + state.slots[index] = None; + continue; + } + if slot.first.is_some() && !super::super::super::live::preparation_ready(app) { + continue; + } + if let Some(plan) = &slot.plan + && slot.cancelled.is_none() + && let Some(session) = owner + { + let q = session.render_queue_state(); + if q.waiting == 0 { + slot.cancelled = Some(crate::i18n::tr("render.preparation_cancelled").into()); + } else if q.running != 0 { + continue; + } + if !plan.owner_matches(session) { + slot.cancelled = Some(crate::i18n::tr("render.live.final_changed").into()); + } + } + // Start the empty receiver before taking any heavy claim/plan. + let (mut worker, sender) = match empty_worker(app, slot) { + Ok(w) => w, + Err(error) => { + // Spawn failed before a scratch owner existed. An idle heavy + // plan remains in its bounded slot, unavailable until teardown. + let cancel = CancelToken::default(); + let (tx, rx) = mpsc::sync_channel(1); + drop(tx); + let (ret, _) = mpsc::sync_channel(1); + let (ack, acked) = mpsc::sync_channel(1); + drop(ack); + let held = + Worker { ready: rx, returning: ret, acknowledged: acked, prepared: None, _unavailable_input: None, returned: false }; + state.active = Some(Active { + slot: index, + worker: held, + cancel, + cleanup_only: true, + applied: true, + committed: false, + completion: Some(Err(error.clone())), + unavailable: Some(error), + }); + return; + } + }; + let cancel = CancelToken::default(); + let mut completion = None; + let input = if slot.cancelled.is_some() { + slot.plan.take().map(Input::retire) + } else if let Some(first) = &mut slot.first { + let result = crate::documents::with_render_owner(app, slot.uid, |session, _| { + let own = session.param_check; + session.param_check = first.level; + let result = api::claim(session, &mut first.params, &mut first.scope, cancel.clone()); + session.param_check = own; + result + }); + match result { + Some(Ok(claim)) => Some(Input::claim(claim)), + Some(Err(error)) => { + slot.cancelled = Some(error.to_string()); + completion = Some(Err(error.to_string())); + None + } + None => { + slot.cancelled = Some(crate::i18n::tr("render.live.final_changed").into()); + None + } + } + } else { + match crate::documents::with_render_owner(app, slot.uid, |session, _| { + let result = api::claim_next(session, &mut slot.plan, cancel.clone()); + if result.is_err() + && let Some(plan) = &slot.plan + { + // Route equality alone is not cancellation authority. + // Abort only this matching epoch before retiring it. + let _ = api::cancel_plan(session, plan); + } + result + }) { + Some(Ok(Some(claim))) => Some(Input::claim(claim)), + Some(Ok(None)) => None, + Some(Err(error)) => { + slot.cancelled = Some(error.to_string()); + completion = Some(Err(error.to_string())); + slot.plan.take().map(Input::retire) + } + None => slot.plan.take().map(Input::retire), + } + }; + if let Some(input) = input { + let cleanup = input.is_retirement(); + let failure = worker.send(sender, input).err(); + state.active = Some(Active { + slot: index, + worker, + cancel, + cleanup_only: cleanup, + applied: cleanup, + committed: false, + completion, + unavailable: failure, + }); + } else { + // Metadata-only refusal/None owns no capture. Close the empty + // worker input and wait its acknowledgement before reusing lane. + drop(sender); + state.active = Some(Active { + slot: index, + worker, + cancel, + cleanup_only: true, + applied: true, + committed: false, + completion: completion.or_else(|| slot.cancelled.clone().map(Err)), + unavailable: None, + }); + } + state.cursor = (index + 1) % state.slots.len(); + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + return; + } + } + pub(super) fn inspect(state: &State) -> Value { + json!({"owners":state.slots.iter().flatten().map(|s|json!({"uid":s.uid,"first":s.first.is_some(),"retained_plan_bytes":s.plan.as_ref().map(api::Plan::retained_bytes),"cancelled":s.cancelled})).collect::>(), + "worker":state.active.as_ref().map(|a|json!({"uid":state.slots[a.slot].as_ref().map(|s|s.uid),"preparing":!a.applied&&!a.cleanup_only,"retiring":a.applied||a.cleanup_only,"unavailable":a.unavailable,"committed":a.committed}))}) + } + pub(super) fn progress(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + let state = &app.render_preparation.batches; + if !busy(state, app.session.uid) { + return false; + } + let active = state.active.as_ref().filter(|a| state.slots[a.slot].as_ref().is_some_and(|s| s.uid == app.session.uid)); + if active.is_none() && app.session.render_queue_state().running != 0 { + return false; + } + let key = match active { + Some(a) if a.unavailable.is_some() => "render.preparation_unavailable", + Some(a) if a.applied || a.cleanup_only => "render.preparation_retiring", + Some(_) => "render.batch_preparing", + None => "render.batch_waiting_worker", + }; + crate::ui_kit::text(ui, app.tr(key), crate::ui_kit::Text::Inline); + let cancel = crate::ui_kit::button(ui, app.tr("cmd.render_cancel"), crate::ui_kit::Button::Enabled(!unavailable(state))); + crate::scenario::publish_target("render:preparation-cancel", cancel.rect); + if cancel.clicked() { + super::super::super::ribbon::perform_job(app, "render.cancel").unwrap_or_else(|e| app.set_status(e, true)); + } + true + } + } + + fn cancel_batch_control(app: &mut SolveApp, req: ControlRequest) -> Option { + let params = req.params.get("params").cloned().filter(|p| !p.is_null()).unwrap_or_else(|| json!({})); + if params.get("job").is_some_and(|job| !job.is_null()) { + return Some(req); + } + let echo = match crate::control::request_param_check(&req.method, &req.params) { + Ok(level) => level, + Err(error) => { + let _ = req.reply.send(json!({"ok":false,"error":error})); + return None; + } + }; + let result = (|| -> Result, String> { + let scope = crate::control::request_scope(app, &req.params)?.or_else(solidcraft_engine::io::vfs::current_scope); + let level = echo.unwrap_or(app.session.param_check); + let warnings: Vec<_> = solidcraft_engine::schema::issues("render.cancel", ¶ms).into_iter().map(|i| i.message).collect(); + if level == ParamCheck::Strict + && let Some(first) = warnings.first() + { + return Err(solidcraft_engine::params::bad("render.cancel", first).to_string()); + } + let own = app.session.param_check; + app.session.param_check = level; + let checked = + solidcraft_engine::io::vfs::scoped(scope, || solidcraft_engine::render_preparation::batch::check_cancel(&app.session, ¶ms)); + app.session.param_check = own; + if checked.map_err(|e| e.to_string())?.is_some() { + return Ok(None); + } + let mut state = std::mem::take(&mut app.render_preparation); + let uid = app.session.uid; + let cancelled = batches::cancel_owner(app, &mut state.batches, uid); + app.render_preparation = state; + let mut reply = json!({"preparing":true,"cancel_requested":cancelled,"queue":app.session.render_queue_state()}); + if level == ParamCheck::Warn && !warnings.is_empty() { + reply["param_warnings"] = json!(warnings); + } + Ok(Some(reply)) + })(); + let mut reply = match result { + Ok(None) => return Some(req), + Ok(Some(value)) => json!({"ok":true,"result":value}), + Err(error) => json!({"ok":false,"error":error}), + }; + if let Some(level) = echo { + reply["param_check"] = json!(level.name()); + } + let _ = req.reply.send(reply); + None + } + + pub(crate) fn control(app: &mut SolveApp, req: ControlRequest) -> Option { + if !super::enabled(app) { + return Some(req); + } + if matches!(req.method.as_str(), "engine.batch" | "engine.script") { + let steps = req.params.as_array().or_else(|| req.params.get("commands").and_then(Value::as_array)); + if steps.is_some_and(|steps| { + steps.iter().any(|step| { + step.get("command") + .or_else(|| step.get("id")) + .and_then(Value::as_str) + .and_then(solidcraft_engine::find_command) + .is_some_and(|spec| matches!(spec.id, "render.start" | "render.preflight" | "render.batch")) + }) + }) { + let echo = match crate::control::request_param_check(&req.method, &req.params) { + Ok(level) => level, + Err(error) => { + let _ = req.reply.send(json!({"ok":false,"error":error})); + return None; + } + }; + if let Err(error) = crate::control::request_scope(app, &req.params) { + let _ = req.reply.send(json!({"ok":false,"error":error})); + return None; + } + let mut value = json!({"ok":false,"error":"native render preparation must be sent as an individual engine.execute request"}); + if let Some(level) = echo { + value["param_check"] = json!(level.name()); + } + let _ = req.reply.send(value); + return None; + } + return Some(req); + } + if !matches!(req.method.as_str(), "engine.execute" | "command") { + return Some(req); + } + let id = req + .params + .get("command") + .or_else(|| req.params.get("id")) + .and_then(Value::as_str) + .and_then(solidcraft_engine::find_command) + .map(|spec| spec.id); + let kind = match id { + Some("render.preflight") => Kind::Check, + Some("render.start") => Kind::Start, + Some("render.batch") => Kind::Start, + Some("render.cancel") + if app.session.render_queue_state().job.is_none() && batches::busy(&app.render_preparation.batches, app.session.uid) => + { + return cancel_batch_control(app, req); + } + _ => return Some(req), + }; + let echo = match crate::control::request_param_check(&req.method, &req.params) { + Ok(level) => level, + Err(error) => { + let _ = req.reply.send(json!({"ok":false,"error":error})); + return None; + } + }; + let scope = match crate::control::request_scope(app, &req.params) { + Ok(scope) => scope.or_else(solidcraft_engine::io::vfs::current_scope), + Err(error) => { + let _ = req.reply.send(json!({"ok":false,"error":error})); + return None; + } + }; + let params = req.params.get("params").cloned().filter(|value| !value.is_null()).unwrap_or_else(|| json!({})); + let reply = req.reply.clone(); + let level = echo.unwrap_or(app.session.param_check); + let chat_turn = req.chat_turn.clone(); + let batch = id == Some("render.batch"); + let result = crate::agent_chat::with_tool_request(app, chat_turn.as_ref(), |app| { + if batch { + batches::begin(app, params, Origin::Control { request: req, echo }, scope, level) + } else { + begin(app, kind, params, Origin::Control { request: req, echo }, scope, level) + } + }); + if let Err(error) = result { + let mut value = json!({"ok":false,"error":error}); + if let Some(level) = echo { + value["param_check"] = json!(level.name()) + } + let _ = reply.send(value); + } + None + } +} +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use native::{State, begin_batch_ui, begin_ui, busy, cancel, control, document_closing, inspect, inspect_batches, progress, tick}; + +#[cfg(target_arch = "wasm32")] +mod web { + use super::*; + #[derive(Default)] + pub(crate) struct State; + pub(crate) fn busy(_: &SolveApp) -> bool { + false + } + pub(crate) fn cancel(_: &mut SolveApp) -> bool { + false + } + pub(crate) fn tick(_: &mut SolveApp, _: &Context) {} + pub(crate) fn inspect(_: &SolveApp) -> Value { + Value::Null + } + pub(crate) fn inspect_batches(_: &SolveApp) -> Value { + Value::Null + } + pub(crate) fn document_closing(_: &mut SolveApp, _: u64) {} + pub(crate) fn progress(_: &mut SolveApp, _: &mut egui::Ui) -> bool { + false + } + pub(crate) fn begin_ui(_: &mut SolveApp, _: Kind, _: Value) -> Result<(), String> { + Err("native preparation is unavailable".into()) + } + pub(crate) fn begin_batch_ui(_: &mut SolveApp, _: Value) -> Result<(), String> { + Err("native preparation is unavailable".into()) + } + pub(crate) fn control(_: &mut SolveApp, req: crate::control::ControlRequest) -> Option { + Some(req) + } +} +#[cfg(target_arch = "wasm32")] +pub(crate) use web::{State, begin_batch_ui, begin_ui, busy, cancel, control, document_closing, inspect, inspect_batches, progress, tick}; + +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use native::{test_configure, test_disconnect_input}; diff --git a/crates/ui-egui/src/render_workspace_ribbon.rs b/crates/ui-egui/src/render_workspace_ribbon.rs index e03c87475..a1429b286 100644 --- a/crates/ui-egui/src/render_workspace_ribbon.rs +++ b/crates/ui-egui/src/render_workspace_ribbon.rs @@ -27,6 +27,8 @@ fn handled(id: &str) -> bool { | "render.shot.rename" | "render.shot.remove" | "render.library.appearance.apply" + | "render.coat.bind" + | "render.coat.unbind" | "render.optics.bind" | "render.optics.unbind" | "render.library.surface.bind" @@ -56,6 +58,12 @@ fn handled(id: &str) -> bool { } pub(super) fn busy(app: &SolveApp) -> bool { + if super::prepare::busy(app) { + return true; + } + if super::live::final_pending(app) { + return true; + } let queue = app.session.render_queue_state(); if queue.running != 0 || queue.waiting != 0 { return true; @@ -89,7 +97,7 @@ pub(super) fn action_ready(app: &SolveApp, id: &str) -> Result<(), String> { } "render.compare" if app.render_workspace.view.retained.is_empty() => Err(app.tr("render.ribbon_no_result").into()), "render.preflight" | "render.start" => { - if id == "render.start" && busy(app) { + if super::prepare::busy(app) || (id == "render.start" && busy(app)) { return Err(app.tr("render.ribbon_job_active").into()); } super::image_params(app).map(|_| ()) @@ -149,13 +157,36 @@ pub(super) fn command_info(app: &SolveApp, command: &CommandSpec) -> CommandInfo /// No action falls back to a default executor, saved shot or a different result. pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { action_ready(app, id)?; - match id { - "render.batch" => { - let request = super::image_params(app)?; - app.run(id, json!({"request":request}))?; + if matches!(id, "render.start" | "render.batch" | "render.result.regrade") { + let params = match id { + "render.batch" => json!({"request":super::image_params(app)?}), + "render.result.regrade" => { + let source = app.render_workspace.view.completed.ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; + json!({"job":source,"presentation":presentation(app)}) + } + _ => super::image_params(app)?, + }; + let pending = PendingFinal { + action: id.into(), + params, + document: std::sync::Arc::downgrade(&app.session.doc), + revision: app.session.revision, + model: std::sync::Arc::downgrade(&app.session.model.state()), + moves: app.session.pending_moves.clone(), + shot: app.render_workspace.view.name.clone(), + visual: final_visual(app), + }; + if super::live::defer_final(app, pending.clone()) { + return Ok(()); } + return submit_deferred(app, pending); + } + match id { "render.preflight" => { let request = super::image_params(app)?; + if super::prepare::enabled(app) { + return super::prepare::begin_ui(app, solidcraft_engine::render_preparation::Kind::Check, request); + } let reply = match app.run(id, request.clone()) { Ok(reply) => reply, Err(error) => { @@ -167,26 +198,17 @@ pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { inspector::record_check(app, &request, &reply); app.set_status(app.tr("render.image_supported").to_string(), false); } - "render.start" => { - let request = super::image_params(app)?; - let reply = app.run(id, request)?; - let job = serde_json::from_value(reply["job"].clone()) - .map_err(|e| crate::i18n::format("render.error_job_identity", &[("error", &e.to_string())]))?; - app.render_workspace.view.job = Some(job); - app.render_workspace.view.job_shot = Some(app.render_workspace.view.name.clone()); - } "render.result.copy" => { let job = app.render_workspace.view.completed.ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; app.run(id, json!({"job":job}))?; } - "render.result.regrade" => { - let source = app.render_workspace.view.completed.ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; - let reply = app.run(id, json!({"job":source,"presentation":presentation(app)}))?; - let job = serde_json::from_value(reply["job"].clone()) - .map_err(|error| crate::i18n::format("render.error_regrade_identity", &[("error", &error.to_string())]))?; - app.render_workspace.view.job = Some(job); - } "render.cancel" => { + if super::prepare::cancel(app) { + return Ok(()); + } + if super::live::cancel_final(app) { + return Ok(()); + } let job = app .session .render_queue_state() @@ -209,6 +231,92 @@ pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { Ok(()) } +#[derive(Clone)] +pub(super) struct PendingFinal { + action: String, + params: serde_json::Value, + document: std::sync::Weak, + revision: u64, + model: std::sync::Weak, + moves: std::collections::BTreeMap, + shot: String, + visual: serde_json::Value, +} +pub(super) fn final_visual(app: &SolveApp) -> serde_json::Value { + json!({"request":super::image_request(app).ok(),"presentation":presentation(app), + "hidden_bodies":app.session.visibility.hidden_bodies,"hidden_occurrences":app.session.visibility.hidden_occurrences}) +} +/// Submit the exact click-time request only after live capture/work has released its leases. +/// This bypasses the pending action's own busy flag, never its captured source guard. +pub(super) fn submit_deferred(app: &mut SolveApp, pending: PendingFinal) -> Result<(), String> { + // A command or automation may have submitted an original-session job while the + // live job drained. Never preempt it or bypass normal final-job priority. + if busy(app) { + return Err(app.tr("render.ribbon_job_active").into()); + } + if !std::sync::Weak::ptr_eq(&pending.document, &std::sync::Arc::downgrade(&app.session.doc)) + || pending.revision != app.session.revision + || !std::sync::Weak::ptr_eq(&pending.model, &std::sync::Arc::downgrade(&app.session.model.state())) + || pending.moves != app.session.pending_moves + || pending.shot != app.render_workspace.view.name + || pending.visual != final_visual(app) + { + return Err(app.tr("render.live.final_changed").into()); + } + let id = pending.action.as_str(); + match id { + "render.batch" => { + if super::prepare::enabled(app) { + return super::prepare::begin_batch_ui(app, pending.params); + } + app.run(id, pending.params)?; + } + "render.start" => { + if super::prepare::enabled(app) { + return super::prepare::begin_ui(app, solidcraft_engine::render_preparation::Kind::Start, pending.params); + } + let reply = app.run(id, pending.params)?; + follow_started(app, &reply)?; + } + "render.result.regrade" => { + let reply = app.run(id, pending.params)?; + let job = serde_json::from_value(reply["job"].clone()) + .map_err(|error| crate::i18n::format("render.error_regrade_identity", &[("error", &error.to_string())]))?; + app.render_workspace.view.job = Some(job); + } + + _ => return Err(crate::i18n::tr("render.error_job_action").into()), + } + Ok(()) +} + +/// The explicit Render click follows its newly minted real-session job. The +/// asynchronous preparation path reuses this after the same command post-hooks. +pub(super) fn follow_started(app: &mut SolveApp, reply: &serde_json::Value) -> Result<(), String> { + let job = + serde_json::from_value(reply["job"].clone()).map_err(|e| crate::i18n::format("render.error_job_identity", &[("error", &e.to_string())]))?; + app.render_workspace.view.job = Some(job); + app.render_workspace.view.job_shot = Some(app.render_workspace.view.name.clone()); + // An explicit UI Render action must show the image being computed. Otherwise + // complete passes remain hidden behind the unchanged integrated model preview. + // Keep an intentional comparison open and retain the compatibility workflow. + if !app.preferences.render_legacy_image_defaults && app.render_workspace.view.compare.is_none() { + app.render_workspace.view.auto_result_job = if app.render_workspace.view.result { + None + } else { + Some(super::AutoResultJob { job, handle: app.session.render_job_handle(job).map_err(|error| error.to_string())? }) + }; + app.render_workspace.view.result = true; + app.render_workspace.view.follow_job = true; + app.render_workspace.view.result_scale = super::ResultScale::Fit; + app.cancel_view_animation(); + app.viewport.nav = None; + app.viewport.key_hold = None; + app.viewport.orbit_free = None; + } + Ok(()) +} + pub(super) fn presentation(app: &SolveApp) -> solidcraft_engine::render::job::presentation::Presentation { let view = &app.render_workspace.view; solidcraft_engine::render::job::presentation::Presentation { @@ -297,7 +405,9 @@ fn navigate(app: &mut SolveApp, id: &str) -> Result<(), String> { focus(app, shot, None); } "render.settings.set" => app.render_workspace.view.save_shot_name = Some(String::new()), - "render.library.appearance.apply" | "render.optics.bind" | "render.optics.unbind" => focus(app, object, Some("surfaces")), + "render.library.appearance.apply" | "render.coat.bind" | "render.coat.unbind" | "render.optics.bind" | "render.optics.unbind" => { + focus(app, object, Some("surfaces")) + } "render.library.surface.bind" | "render.library.surface.prepare" | "render.library.surface.unbind" => { focus(app, object, Some("surfaces")); } diff --git a/crates/ui-egui/src/render_workspace_setups.rs b/crates/ui-egui/src/render_workspace_setups.rs index 7382cb863..eec0e151f 100644 --- a/crates/ui-egui/src/render_workspace_setups.rs +++ b/crates/ui-egui/src/render_workspace_setups.rs @@ -6,15 +6,26 @@ use solidcraft_engine::render::job::{AreaLights, RaytraceEnvironmentOptions, Ray use super::{ImageMethod, cpu, hdr, materials, studio}; use crate::SolveApp; -/// Unsaved files and temporary bindings use the runtime request route. Embedded sources -/// use the typed job route unless a binding also needs the runtime schema. +/// Unsaved inputs protect local shot edits and independent navigation. Portable +/// Glass and coat drafts remain unsaved while using the typed capture route. pub(super) fn has_runtime_inputs(app: &SolveApp) -> bool { - has_unportable_bindings(app) || hdr::active(app).is_some_and(|target| !hdr::input(app, target).embedded()) + requires_runtime_request(app) + || app.render_workspace.view.materials.bindings.iter().any(|binding| binding.has_unsaved_coat_intent() || binding.has_unsaved_optics_intent()) } -fn has_unportable_bindings(app: &SolveApp) -> bool { +/// File sources and ordinal Glass/maps use the runtime request schema. Stable +/// Glass and coat drafts overlay targets into typed captured settings instead. +pub(super) fn requires_runtime_request(app: &SolveApp) -> bool { + has_runtime_bindings(app) || hdr::active(app).is_some_and(|target| !hdr::input(app, target).embedded()) +} + +pub(super) fn has_unportable_bindings(app: &SolveApp) -> bool { + !app.render_workspace.view.materials.bindings.is_empty() || has_runtime_bindings(app) +} + +fn has_runtime_bindings(app: &SolveApp) -> bool { let view = &app.render_workspace.view; - if !view.materials.bindings.is_empty() { + if view.materials.bindings.iter().any(super::materials::Binding::has_runtime_intent) { return true; } match view.method { @@ -26,17 +37,54 @@ fn has_unportable_bindings(app: &SolveApp) -> bool { || !options.dielectrics.is_empty() || options.surface_effects.is_some() || options.emissions.is_some() + || options.aging.is_some() + || options.sky.is_some() + || (options.sun.is_some() && !view.studio.sun_enabled) + || (options.volume.is_some() && view.studio.volume.is_none()) } } } /// Pure construction: saving intent must work with no CPU/GPU host and stale geometry. pub(super) fn snapshot(app: &SolveApp) -> Result { + snapshot_with_lens_override(app, None) +} + +/// Validate a prospective lens edit without changing the live draft first. In particular, +/// removing an authored lens remains possible after navigating to orthographic. +pub(super) fn snapshot_with_lens(app: &SolveApp, lens: Option) -> Result { + snapshot_with_lens_override(app, Some(lens)) +} + +fn snapshot_with_lens_override(app: &SolveApp, lens: Option>) -> Result { cpu::validate_progressive_image(app)?; if has_unportable_bindings(app) { return Err(app.tr("render.setup_runtime_unsupported").to_string()); } - let setup = draft(app)?; + let mut setup = draft(app)?; + if let Some(lens) = lens { + match &mut setup.job { + Some(RenderJob::CpuRaytrace { options, .. }) => options.lens = lens, + Some(RenderJob::GpuPath { options, .. }) => options.lens = lens, + _ => return Err(app.tr("render.shot_lens_raytrace_reason").into()), + } + } + validate_snapshot(app, setup) +} + +/// Stable saved optical edits stay transient while every ordinary image capture sees +/// the prospective values. Generic Save still requires the explicit optical review. +pub(super) fn image_snapshot(app: &SolveApp) -> Result { + cpu::validate_progressive_image(app)?; + if has_runtime_bindings(app) { + return Err(app.tr("render.setup_runtime_unsupported").into()); + } + let mut setup = draft(app)?; + materials::overlay_saved(app, &mut setup)?; + validate_snapshot(app, setup) +} + +fn validate_snapshot(app: &SolveApp, setup: RenderSetup) -> Result { // Preserve unsupported legacy intent visibly instead of erasing it while upgrading a setup. if setup.environment_rotation != 0.0 || setup.environment_intensity != 1.0 { return Err(app.tr("render.setup_legacy_environment").to_string()); @@ -56,12 +104,23 @@ pub(super) fn draft(app: &SolveApp) -> Result { setup.job = Some(match view.method { ImageMethod::Raster => RenderJob::Raster { transparent_background: view.transparent }, ImageMethod::CpuRaytrace => { - if view.transparent { - return Err(app.tr("render.cpu_opaque_required").to_string()); - } let options = &view.raytrace; RenderJob::CpuRaytrace { - options: CpuJob { + transparent_background: view.transparent, + options: Box::new(CpuJob { + 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 { + gradient: view.cpu.gradient, + rotation_rad: view.cpu.rotation_rad, + intensity: view.cpu.intensity, + }), + aging: view.studio.aging.clone(), + adaptive: view.studio.adaptive, + denoise: view.studio.denoise, + path: options.path, + lens: view.studio.lens_enabled.then_some(view.studio.lens), + output: studio::cpu_output(view), budget: options.budget, primary_samples: options.primary_samples, progressive: options.progressive, @@ -74,7 +133,7 @@ pub(super) fn draft(app: &SolveApp) -> Result { shadows: options.shadows, environment: match view.cpu.environment { cpu::Environment::Constant => Some(RaytraceEnvironmentOptions { color: view.cpu.color, intensity: view.cpu.intensity }), - cpu::Environment::Hdr => None, + cpu::Environment::Hdr | cpu::Environment::Sky => None, cpu::Environment::None => options.environment, }, hdr: if view.cpu.environment == cpu::Environment::Hdr { @@ -87,7 +146,7 @@ pub(super) fn draft(app: &SolveApp) -> Result { } else { None }, - }, + }), } } ImageMethod::GpuRaytrace => { @@ -111,6 +170,8 @@ pub(super) fn draft(app: &SolveApp) -> Result { lens: studio.lens_enabled.then_some(studio.lens), lighting: if studio.lighting_enabled { Some(StudioLighting { + punctual_lights: studio.punctual_lights, + directional_lights: studio.directional_lights, environment: studio.ambient, sun: studio.sun_enabled.then_some(studio.sun), area_lights: AreaLights::new(&studio.area_lights).map_err(|error| error.to_string())?, @@ -150,6 +211,7 @@ pub(super) fn persist_editor(app: &mut SolveApp, before: &RenderSetup) -> Result let old = serde_json::to_value(before).ok(); let new = serde_json::to_value(&after).map_err(|error| error.to_string())?; let saved = app.session.doc.render.setups.get(&app.render_workspace.view.name); + let creating = saved.is_none(); let saved = saved.and_then(|setup| serde_json::to_value(setup).ok()); let mut patch = serde_json::Map::new(); if let Some(fields) = new.as_object() { @@ -163,22 +225,39 @@ pub(super) fn persist_editor(app: &mut SolveApp, before: &RenderSetup) -> Result } } if !patch.is_empty() { + // The engine creates missing setups from its legacy defaults. On the first real + // numerical edit, preserve the whole visible numerical baseline, including image + // size and method; a job-only patch can be inadmissible at the engine's default size. + // Navigation keeps its explicit Update shot policy. Merely revealing an editor is + // still read-only because an actual edit must have populated the patch first. + if creating && let Some(fields) = new.as_object() { + patch = fields.iter().filter(|(key, _)| key.as_str() != "camera").map(|(key, value)| (key.clone(), value.clone())).collect(); + } after.validate().map_err(|error| error.to_string())?; let name = app.render_workspace.view.name.clone(); app.run("render.settings.set", serde_json::json!({"name":name,"set":patch}))?; app.render_workspace.revision = app.session.revision; let camera = app.render_workspace.view.clean_setup.as_ref().map_or(after.camera, |clean| clean.camera); app.render_workspace.view.clean_setup = Some(RenderSetup { camera, ..after.clone() }); + app.render_workspace.view.clean_persisted = true; app.render_workspace.view.clean_name = app.render_workspace.view.name.clone(); materials::refresh_render_revision(app); cpu::refresh_render_revision(app); } if let Some(saved) = app.session.doc.render.setups.get(&app.render_workspace.view.name) { + if let Some(RenderJob::CpuRaytrace { options, .. }) = &saved.job { + app.render_workspace.view.raytrace.output = options.output.clone(); + app.render_workspace.view.raytrace.denoise = options.denoise; + app.render_workspace.view.raytrace.lens = options.lens; + app.render_workspace.view.raytrace.path = options.path; + app.render_workspace.view.raytrace.volume = options.volume; + } let mut saved = saved.clone(); saved.camera = after.camera; if saved == after { let camera = app.render_workspace.view.clean_setup.as_ref().map_or(after.camera, |clean| clean.camera); app.render_workspace.view.clean_setup = Some(RenderSetup { camera, ..after }); + app.render_workspace.view.clean_persisted = true; app.render_workspace.view.clean_name = app.render_workspace.view.name.clone(); app.render_workspace.revision = app.session.revision; } @@ -187,14 +266,33 @@ pub(super) fn persist_editor(app: &mut SolveApp, before: &RenderSetup) -> Result Ok(()) } +/// A missing setup uses the same transient baseline for initial loading and later model edits. +/// Existing entries, including a legacy job-less setup, retain their saved interpretation. +fn saved_or_initial(app: &SolveApp) -> RenderSetup { + app.session.doc.render.setups.get(&app.render_workspace.view.name).cloned().unwrap_or_else(|| { + let mut setup = RenderSetup::default(); + // Only a new, unsaved setup adopts the useful native image route. Discovery is read-only; + // saved Raster, fixed CPU and legacy job-less setups keep their exact interpretation. + if !app.preferences.render_legacy_image_defaults && super::image_host(app, ImageMethod::CpuRaytrace).is_ok() { + setup.job = Some(RenderJob::CpuRaytrace { + transparent_background: false, + options: Box::new(CpuJob { progressive: Some(Default::default()), ..Default::default() }), + }); + } + setup + }) +} + /// A setup switch/reload replaces its numeric editor draft, never a completed image or camera. pub(super) fn load(app: &mut SolveApp) { - let setup = app.session.doc.render.setups.get(&app.render_workspace.view.name).cloned().unwrap_or_default(); + let persisted = app.session.doc.render.setups.contains_key(&app.render_workspace.view.name); + let setup = saved_or_initial(app); load_values(&mut app.render_workspace.view, setup); app.render_workspace.view.dirty = false; app.render_workspace.revision = app.session.revision; // Keep the explicit Restore Saved Camera action: loading options does not navigate. app.render_workspace.view.clean_setup = draft(app).ok(); + app.render_workspace.view.clean_persisted = persisted; app.render_workspace.view.clean_name = app.render_workspace.view.name.clone(); super::light::loaded(app); } @@ -203,6 +301,7 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) { view.method = ImageMethod::Raster; view.transparent = false; view.raytrace = RaytraceOptions::default(); + view.cpu_sampling_initialized = false; view.cpu = cpu::View::default(); view.samples = 64; view.max_depth = 8; @@ -211,9 +310,27 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) { view.materials = materials::View::default(); match &setup.job { Some(RenderJob::Raster { transparent_background }) => view.transparent = *transparent_background, - Some(RenderJob::CpuRaytrace { options }) => { + Some(RenderJob::CpuRaytrace { options, transparent_background }) => { view.method = ImageMethod::CpuRaytrace; + view.transparent = *transparent_background; + view.cpu_sampling_initialized = true; + view.studio.volume = options.volume; + view.studio.denoise = options.denoise; + view.studio.aging = options.aging.clone(); + view.studio.adaptive = options.adaptive; + view.studio.sun_enabled = options.sun.is_some(); + if let Some(sun) = options.sun { + view.studio.sun = sun; + view.studio.lighting_enabled = true; + } view.raytrace = RaytraceOptions { + sun: options.sun.map(Box::new), + volume: options.volume, + adaptive: options.adaptive.map(Box::new), + denoise: options.denoise, + path: options.path, + lens: options.lens, + output: options.output.clone(), budget: options.budget, primary_samples: options.primary_samples, progressive: options.progressive, @@ -226,6 +343,23 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) { shadows: options.shadows, ..Default::default() }; + if let Some(lens) = options.lens { + view.studio.lens_enabled = true; + view.studio.lens = lens; + } + if let Some(output) = &options.output { + view.studio.tone_map = output.tone_map; + view.studio.finishing = output.finishing; + view.studio.backdrop_enabled = output.backdrop.is_some(); + view.studio.backdrop = output.backdrop.unwrap_or_default(); + view.studio.linear_exr = output.linear_exr; + } + if let Some(SkyEnvironment::Sky { gradient, rotation_rad, intensity }) = options.sky { + view.cpu.environment = cpu::Environment::Sky; + view.cpu.gradient = gradient; + view.cpu.rotation_rad = rotation_rad; + view.cpu.intensity = intensity; + } if let Some(environment) = options.environment { view.cpu.environment = cpu::Environment::Constant; view.cpu.color = environment.color; @@ -268,6 +402,8 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) { view.studio.sun = sun; } view.studio.area_lights = lighting.area_lights.iter().copied().collect(); + view.studio.directional_lights = lighting.directional_lights; + view.studio.punctual_lights = lighting.punctual_lights; } if let Some(SkyEnvironment::Sky { gradient, rotation_rad, intensity }) = &options.environment { view.studio.environment = studio::Environment::Sky; @@ -294,7 +430,9 @@ pub(super) fn same_model_source(app: &SolveApp, document: &std::sync::Weak Result<(), String> { + save_with_camera(app, true) +} + +/// Numerical source edits capture bytes/intent atomically without updating the shot camera. +pub(super) fn save_numerical(app: &mut SolveApp) -> Result<(), String> { + save_with_camera(app, false) +} + +fn setup_patch(setup: RenderSetup, save_camera: bool) -> Result { + let mut value = serde_json::to_value(setup).map_err(|error| error.to_string())?; + if !save_camera && let Some(fields) = value.as_object_mut() { + fields.remove("camera"); + } + Ok(value) +} + +/// Numeric reloads keep both the live camera and its previous dirty baseline. +pub(super) fn reload_numerical(app: &mut SolveApp) { + let camera = app.render_workspace.view.clean_setup.as_ref().map(|clean| clean.camera); + load(app); + if let Some(camera) = camera + && let Some(clean) = &mut app.render_workspace.view.clean_setup + { + clean.camera = camera; + } + refresh_dirty(app); +} + +fn save_with_camera(app: &mut SolveApp, save_camera: bool) -> Result<(), String> { + let clean_camera = app.render_workspace.view.clean_setup.as_ref().map_or(app.cam, |clean| clean.camera); let mut setup = snapshot(app)?; let name = app.render_workspace.view.name.clone(); let capture = hdr::active(app).and_then(|target| match hdr::input(app, target) { @@ -487,7 +675,7 @@ pub(super) fn save(app: &mut SolveApp) -> Result<(), String> { if let Some((_, path, digest)) = &capture { let mut params = serde_json::json!({"name":name,"path":path,"expected_sha256":digest}); match &mut setup.job { - Some(RenderJob::CpuRaytrace { options }) => { + Some(RenderJob::CpuRaytrace { options, .. }) => { let environment = options.hdr.take().ok_or_else(|| app.tr("render.hdr_inspect_required").to_string())?; params["rotation_rad"] = serde_json::json!(environment.rotation_rad); params["intensity"] = serde_json::json!(environment.intensity); @@ -501,11 +689,11 @@ pub(super) fn save(app: &mut SolveApp) -> Result<(), String> { } _ => return Err(app.tr("render.hdr_inspect_required").to_string()), } - params["set"] = serde_json::json!(setup); + params["set"] = setup_patch(setup, save_camera)?; // The expected digest rejects an externally changed file before any resource/setup edit. app.run("render.settings.capture_hdr", params)?; } else { - app.run("render.settings.set", serde_json::json!({"name":name,"set":setup}))?; + app.run("render.settings.set", serde_json::json!({"name":name,"set":setup_patch(setup, save_camera)?}))?; } let setup = app.session.doc.render.setups.get(&name).cloned().ok_or_else(|| app.tr("render.setup_save_missing").to_string())?; if let Some((target, _, resource)) = capture { @@ -514,10 +702,21 @@ pub(super) fn save(app: &mut SolveApp) -> Result<(), String> { hdr::Target::Gpu => app.render_workspace.view.studio.hdr = hdr::Input::EmbeddedResource { resource }, } } + if let Some(RenderJob::CpuRaytrace { options, .. }) = &setup.job { + app.render_workspace.view.raytrace.output = options.output.clone(); + app.render_workspace.view.raytrace.denoise = options.denoise; + app.render_workspace.view.raytrace.lens = options.lens; + app.render_workspace.view.raytrace.path = options.path; + app.render_workspace.view.raytrace.volume = options.volume; + } app.render_workspace.view.draft = setup.clone(); - app.render_workspace.view.clean_setup = Some(setup); + app.render_workspace.view.clean_setup = Some(if save_camera { setup } else { RenderSetup { camera: clean_camera, ..setup } }); + app.render_workspace.view.clean_persisted = true; app.render_workspace.view.clean_name = app.render_workspace.view.name.clone(); app.render_workspace.view.dirty = false; app.render_workspace.revision = app.session.revision; + if !save_camera { + refresh_dirty(app); + } Ok(()) } diff --git a/crates/ui-egui/src/render_workspace_shot.rs b/crates/ui-egui/src/render_workspace_shot.rs index 4ce451391..95b4fb231 100644 --- a/crates/ui-egui/src/render_workspace_shot.rs +++ b/crates/ui-egui/src/render_workspace_shot.rs @@ -176,9 +176,7 @@ pub(super) fn duplicate(app: &mut SolveApp, name: &str) -> Result<(), String> { } pub(super) fn revert(app: &mut SolveApp, name: &str) -> Result<(), String> { - app.run("render.settings.apply", json!({"name":name}))?; - app.follow_view_request(false); - Ok(()) + inspector::restore_saved_camera(app, name) } /// E7: saved camera, lens, exposure and frame in approved order. @@ -235,7 +233,7 @@ pub(super) fn editor(app: &mut SolveApp, ui: &mut egui::Ui, shot: &str) { let title = app.tr("render.page_camera").to_string(); ui_kit::section(ui, "render_shot_camera", &title, true, |ui| camera(app, ui, shot)); let title = app.tr("render.shot_lens").to_string(); - ui_kit::section_method(ui, "render_shot_lens", &title, true, "GPU", |ui| lens(app, ui, shot, &saved)); + ui_kit::section(ui, "render_shot_lens", &title, true, |ui| lens(app, ui, shot, &saved)); let title = app.tr("render.shot_exposure_section").to_string(); ui_kit::section(ui, "render_shot_exposure", &title, true, |ui| exposure(app, ui, shot, &saved)); let title = app.tr("render.stage_frame").to_string(); @@ -359,35 +357,101 @@ pub(super) fn look_at_selection(app: &mut SolveApp, shot: &str) -> Result<(), St set_camera(app, shot, solidcraft_engine::render::Camera { target: bounds.center(), ..app.cam }) } +/// Change only saved lens intent. Camera updates keep their explicit Update shot action. +pub(super) fn set_lens(app: &mut SolveApp, shot: &str, lens: Option) -> Result<(), String> { + use solidcraft_engine::doc::render_settings::RenderJob; + let saved = app.session.doc.render.setups.get(shot).ok_or_else(|| app.tr("render.ribbon_no_saved_camera").to_string())?; + let active = app.render_workspace.view.name == shot; + let establishing_job = active && saved.job.is_none(); + let mut candidate = if active { + super::setups::snapshot_with_lens(app, lens)? + } else { + let mut candidate = saved.clone(); + match &mut candidate.job { + Some(RenderJob::CpuRaytrace { options, .. }) => options.lens = lens, + Some(RenderJob::GpuPath { options, .. }) => options.lens = lens, + _ => return Err(app.tr("render.shot_lens_raytrace_reason").into()), + } + candidate + }; + // Numerical lens intent uses the visible method, but never adopts navigation. + candidate.camera = saved.camera; + candidate.validate().map_err(|error| error.to_string())?; + let patch = if establishing_job { + let mut patch = serde_json::to_value(&candidate).map_err(|error| error.to_string())?; + if let Some(fields) = patch.as_object_mut() { + fields.remove("camera"); + } + patch + } else { + // Validate the visible draft above, but save only lens intent on the saved job. + // Independent method and sampling edits keep their own dirty state. + let mut job = saved.job.clone(); + match &mut job { + Some(RenderJob::CpuRaytrace { options, .. }) => options.lens = lens, + Some(RenderJob::GpuPath { options, .. }) => options.lens = lens, + _ => return Err(app.tr("render.shot_lens_raytrace_reason").into()), + } + json!({"job":job}) + }; + edit_settings(app, shot, patch)?; + if active { + app.render_workspace.view.studio.lens_enabled = lens.is_some(); + if let Some(value) = lens { + app.render_workspace.view.studio.lens = value; + } + app.render_workspace.view.raytrace.lens = lens; + if establishing_job { + let view = &mut app.render_workspace.view; + let camera = view.clean_setup.as_ref().map_or(app.cam, |clean| clean.camera); + view.clean_setup = Some(RenderSetup { camera, ..candidate }); + view.clean_persisted = true; + view.clean_name = shot.into(); + } + super::setups::refresh_dirty(app); + } + Ok(()) +} + fn lens(app: &mut SolveApp, ui: &mut egui::Ui, shot: &str, saved: &RenderSetup) { use solidcraft_engine::doc::render_settings::RenderJob; - let gpu = matches!(saved.job, Some(RenderJob::GpuPath { .. })); - let enabled = gpu && app.cam.fov > 0.0; - let lens = match &saved.job { - Some(RenderJob::GpuPath { options, .. }) => options.lens, - _ => None, + // A fresh native CPU default is transient until the first numerical edit. + // Read its visible method here; opening Frame must not write that job to Studio. + let current = if app.render_workspace.view.name == shot { + super::setups::snapshot(app).or_else(|_| super::setups::draft(app)).unwrap_or_else(|_| saved.clone()) + } else { + saved.clone() + }; + let (supported, sampling, lens) = match ¤t.job { + Some(RenderJob::CpuRaytrace { options, .. }) => (true, options.progressive.is_some(), options.lens), + Some(RenderJob::GpuPath { options, .. }) => (true, true, options.lens), + _ => (false, false, None), }; let mut on = lens.is_some(); let mut value = lens.unwrap_or(app.render_workspace.view.studio.lens); - let changed = ui - .add_enabled_ui(enabled, |ui| { - let mut changed = ui_kit::checkbox(ui, app.tr("render.shot_dof"), &mut on).changed(); - ui.add_enabled_ui(on, |ui| { - changed |= ui_kit::row(ui, app.tr("render.shot_aperture"), |ui| { - ui_kit::number_field(ui, &mut value.aperture_radius_mm, 0.0..=1e7, 0.1, " mm") - }) + let perspective = saved.camera.fov > 0.0 && app.cam.fov > 0.0; + let compatible = supported && sampling && perspective; + // Removing an authored lens remains possible after navigating to orthographic. + let mut changed = false; + ui.add_enabled_ui(supported && (on || compatible), |ui| { + let response = ui_kit::checkbox(ui, app.tr("render.shot_dof"), &mut on); + crate::scenario::publish_target("render:shot:dof", response.rect); + changed |= response.changed(); + }); + ui.add_enabled_ui(on && compatible, |ui| { + changed |= + ui_kit::row(ui, app.tr("render.shot_aperture"), |ui| ui_kit::number_field(ui, &mut value.aperture_radius_mm, 0.0..=1e7, 0.1, " mm")) .changed(); - changed |= ui_kit::row(ui, app.tr("render.shot_focus_distance"), |ui| { - ui_kit::number_field(ui, &mut value.focus_distance_mm, 1e-6..=1e9, 1.0, " mm") - }) - .changed(); - }); - changed + changed |= ui_kit::row(ui, app.tr("render.shot_focus_distance"), |ui| { + ui_kit::number_field(ui, &mut value.focus_distance_mm, 1e-6..=1e9, 1.0, " mm") }) - .inner; - let reason = if !gpu { - Some("render.shot_lens_gpu_reason") - } else if !enabled { + .changed(); + }); + let reason = if !supported { + Some("render.shot_lens_raytrace_reason") + } else if !sampling { + Some("render.shot_lens_cpu_progressive_reason") + } else if !perspective { Some("render.shot_lens_perspective_reason") } else if !on { Some("render.shot_lens_enable_reason") @@ -397,16 +461,8 @@ fn lens(app: &mut SolveApp, ui: &mut egui::Ui, shot: &str, saved: &RenderSetup) if let Some(key) = reason { ui_kit::text(ui, app.tr(key), ui_kit::Text::Note(key)); } - if changed && enabled { - let mut job = saved.job.clone(); - if let Some(solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options, .. }) = &mut job { - options.lens = on.then_some(value); - } - let action = edit_settings(app, shot, json!({"job":job})); - if action.is_ok() && app.render_workspace.view.name == shot { - app.render_workspace.view.studio.lens_enabled = on; - app.render_workspace.view.studio.lens = value; - } + if changed { + let action = set_lens(app, shot, on.then_some(value)); result(app, action); } } @@ -453,6 +509,21 @@ pub(crate) fn overlay_visible(app: &SolveApp) -> bool { !app.render_workspace.view.result && (app.render_workspace.view.stage == Stage::Frame || selected(app).is_some()) } +/// Actual output-camera frame, independent of inspector focus and transient guides. +/// Retained result/compare views use their captured image dimensions separately. +pub(crate) fn render_rect(app: &SolveApp, viewport: Rect) -> Rect { + if app.preferences.render_legacy_image_defaults { + return preview_rect(app, viewport).unwrap_or(viewport); + } + let free = crate::shell::workspace_content(app, crate::render_ui::canvas(app, viewport)); + // With no surrounding chrome, an equal-aspect image uses the same full + // rectangle as Design. The normal workspace still keeps its card margin. + let frame_area = if free == viewport { free } else { free.shrink(Tokens::get().space_8) }; + frame_rect(super::image_aspect(&app.render_workspace.view.draft), frame_area).unwrap_or(free) +} + +/// Contextual composition guides may preview a transient/selected-shot aspect. +/// Their visibility/aspect must never choose the nonlegacy rendered projection. pub(crate) fn preview_rect(app: &SolveApp, viewport: Rect) -> Option { if !overlay_visible(app) { return None; diff --git a/crates/ui-egui/src/render_workspace_studio.rs b/crates/ui-egui/src/render_workspace_studio.rs index 9f829cd9f..2ff7637a5 100644 --- a/crates/ui-egui/src/render_workspace_studio.rs +++ b/crates/ui-egui/src/render_workspace_studio.rs @@ -1,6 +1,6 @@ //! GPU studio editors. Numeric intent is portable; HDR resources cross the engine capture boundary. use serde_json::{Value, json}; -use solidcraft_engine::render::job::{AreaLight, AreaLights, StudioLighting, Sun, ThinLens, ToneMap}; +use solidcraft_engine::render::job::{AreaLight, AreaLights, DirectionalLights, PunctualLights, StudioLighting, Sun, ThinLens, ToneMap}; use solidcraft_engine::render::lighting::environment::SkyGradient; use super::hdr; @@ -41,6 +41,8 @@ pub(super) struct View { pub sun_enabled: bool, pub sun: Sun, pub area_lights: Vec, + pub directional_lights: DirectionalLights, + pub punctual_lights: PunctualLights, } impl Default for View { @@ -71,10 +73,24 @@ impl Default for View { sun_enabled: false, sun: Sun { direction: [-0.4, -0.6, 0.7], angular_radius_rad: 0.02, radiance: [1000.0, 950.0, 850.0] }, area_lights: Vec::new(), + directional_lights: Default::default(), + punctual_lights: Default::default(), } } } +/// CPU and GPU editors share presentation intent; CPU transport options remain independent. +/// Preserve an explicitly saved identity object instead of erasing it on an unedited reload. +pub(super) fn cpu_output(view: &super::ViewState) -> Option> { + let settings = solidcraft_engine::render::job::OutputOptions { + tone_map: view.studio.tone_map, + finishing: view.studio.finishing, + backdrop: view.studio.backdrop_enabled.then_some(view.studio.backdrop), + linear_exr: view.studio.linear_exr, + }; + if settings == Default::default() && view.raytrace.output.is_none() { None } else { Some(Box::new(settings)) } +} + pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { let view = &app.render_workspace.view.studio; params["tone_map"] = json!(view.tone_map); @@ -96,6 +112,8 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { } if view.lighting_enabled { let lighting = StudioLighting { + punctual_lights: view.punctual_lights, + directional_lights: view.directional_lights, environment: view.ambient, sun: view.sun_enabled.then_some(view.sun), area_lights: AreaLights::new(&view.area_lights).map_err(|error| error.to_string())?, @@ -415,22 +433,24 @@ pub(super) fn export_controls(app: &mut SolveApp, ui: &mut egui::Ui) { crate::scenario::publish_target("render:export-format", response.rect); } pub(super) fn format_choices(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response { + let available = linear_export_available(app); ui.scope(|ui| { - let reason = app.tr("render.output_exr_unavailable"); + let reason = app.tr("render.output_master_unavailable"); let mut format = usize::from(app.render_workspace.view.studio.export_exr); if ui_kit::segmented( ui, &mut format, &["PNG", "EXR"], ui_kit::Segments { - disabled_reasons: &[None, Some(reason)], + disabled_reasons: &[None, (!available).then_some(reason)], + targets: &["render:format-png", "render:format-exr"], workspace_accent: true, intrinsic: true, compact: true, ..Default::default() }, ) { - app.render_workspace.view.studio.export_exr = false; + app.render_workspace.view.studio.export_exr = format == 1; } }) .response diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index f709d984e..48ac0bdd6 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -106,8 +106,6 @@ fn environment_editor_unsupported_methods_keep_controls_and_reasons_without_swit ); let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); for key in [ - "render.environment.needs_gpu", - "render.environment.gradient_gpu", "render.environment.blur_pending", "render.environment.world_pending", "render.environment.medium", @@ -116,6 +114,16 @@ fn environment_editor_unsupported_methods_keep_controls_and_reasons_without_swit ] { assert!(text.contains(h.app.tr(key)), "missing {key}: {text}"); } + if method == ImageMethod::Raster { + assert!(text.contains(h.app.tr("render.environment.source_raytrace"))); + assert!(text.contains(h.app.tr("render.output_raytrace_only"))); + } else { + assert!(!text.contains(h.app.tr("render.environment.source_raytrace")), "CPU environment sources are supported"); + assert!(crate::scenario::rect_of("render:environment:source").is_some()); + assert!(text.contains(h.app.tr("render.cpu_volume_help"))); + assert!(text.contains(h.app.tr("render.cpu_volume_path_required"))); + assert!(crate::scenario::rect_of("render:volume-enable-path").is_some()); + } output.textures_delta.clear(); let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); for pressed in [true, false] { @@ -215,6 +223,14 @@ fn environment_editor_checked_file_embeds_bytes_and_keeps_the_recheck_banner() { #[test] fn environment_editor_medium_toggle_saves_one_command_without_a_gpu_host() { let mut h = environment_editor_fixture(); + let name = h.app.render_workspace.view.name.clone(); + super::inspector::activate_saved_shot(&mut h.app, name).unwrap(); + let saved_camera = h.app.session.doc.render.setups[&h.app.render_workspace.view.name].camera; + h.app.cam.yaw += 0.2; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "navigation is a real draft after activating the saved shot"); + let live_camera = h.app.cam; + let before = h.app.session.doc.clone(); environment_editor_frame(&mut h, vec![]); let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); let undo = h.app.session.undo.len(); @@ -229,11 +245,17 @@ fn environment_editor_medium_toggle_saves_one_command_without_a_gpu_host() { } assert!(h.app.render_workspace.view.studio.volume.is_some()); assert_eq!(h.app.session.undo.len(), undo + 1); - let expected = setups::snapshot(&h.app).unwrap(); + let mut expected = setups::snapshot(&h.app).unwrap(); + // Numerical atmosphere edits preserve the saved shot while navigation remains a draft. + expected.camera = saved_camera; assert_eq!(h.app.session.doc.render.setups[&h.app.render_workspace.view.name], expected); + assert_eq!(h.app.cam, live_camera); + assert_eq!(h.app.render_workspace.view.clean_setup.as_ref().unwrap().camera, saved_camera); h.app.run("edit.undo", json!({})).unwrap(); setups::load(&mut h.app); assert!(h.app.render_workspace.view.studio.volume.is_none()); + assert_eq!(h.app.session.doc, before, "Undo restores the exact pre-gesture document"); + assert_eq!(h.app.cam, live_camera); } #[test] @@ -745,7 +767,7 @@ fn render_lights_solo_and_mute_filter_preview_and_render_copies_without_saving_o } #[test] -fn render_lights_editor_opening_and_disabled_gpu_types_never_edit_or_start_a_job() { +fn render_lights_editor_opening_is_read_only_and_gpu_point_conversion_is_one_undoable_edit() { let mut h = render_lights_fixture(); h.app .run( @@ -761,12 +783,27 @@ fn render_lights_editor_opening_and_disabled_gpu_types_never_edit_or_start_a_job let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); h.frames(3); assert!(crate::scenario::rect_of("render:light:editor").is_some()); - h.step(&json!({"click":{"handle":"render:light:type:point"}})).unwrap(); assert!(Arc::ptr_eq(&document, &h.app.session.doc)); assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); assert!(h.app.render_workspace.view.job.is_none()); assert!(h.app.dialog.is_none()); assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "area"); + let camera = h.app.cam; + h.step(&json!({"click":{"handle":"render:light:type:point"}})).unwrap(); + assert_eq!(h.app.session.undo.len(), before.0 + 1); + assert_eq!(h.app.session.doc.features, document.features); + assert_eq!(h.app.session.doc.materials, document.materials); + assert_eq!(h.app.cam, camera); + assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "point"); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(*h.app.session.doc, *document); + assert_eq!(h.app.session.undo.len(), before.0); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); + assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "area"); } #[test] @@ -1408,9 +1445,10 @@ fn adopting_into_blank_document_resets_render_draft_and_preserves_hosts() { #[test] fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design() { - for language in ["en", "de", "ko", "ru"] { + for (language, legacy) in [("en", false), ("de", false), ("ko", false), ("ru", false), ("en", true)] { let mut h = Harness::new(); h.app.preferences.language = language.into(); + h.app.preferences.render_legacy_image_defaults = legacy; h.frames(1); let export = studio::export_label(&h.app).to_string(); @@ -1425,6 +1463,7 @@ fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design let undo = h.app.session.undo.len(); click_render_check(&mut h); h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.result, !legacy, "Render must make its image visible unless the previous workflow is requested"); for _ in 0..50 { h.frames(1); if h.app.render_workspace.view.completed.is_some() { @@ -1432,6 +1471,10 @@ fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design } } let good = h.app.render_workspace.view.completed.unwrap(); + h.frames(2); + if !legacy { + assert_eq!(displayed_image(&h.app).unwrap().info.job, good); + } h.step(&json!({"widget":export})).unwrap(); assert!(h.dir.join("render.png").is_file()); h.app.render_workspace.view.draft.width = 1024; @@ -1689,7 +1732,7 @@ fn progressive_image_controls_route_to_the_registered_host() { let doc = h.app.session.doc.clone(); let undo = h.app.session.undo.len(); let checked = image_params(&h.app).unwrap(); - assert_eq!(checked["raytrace"]["clear_coats"][0]["weight"], 1.0); + assert_eq!(checked["settings"]["coats"][0]["coat"]["weight"], 1.0); assert_eq!(checked["raytrace"]["textures"][0]["base_color_srgb"], map_path.to_string_lossy().as_ref()); h.app.run("render.preflight", checked.clone()).unwrap(); assert_eq!(image_params(&h.app).unwrap(), checked); @@ -1698,7 +1741,11 @@ fn progressive_image_controls_route_to_the_registered_host() { let job = h.app.render_workspace.view.job.unwrap(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); while h.app.render_workspace.view.completed.is_none() { - assert!(std::time::Instant::now() < deadline, "progressive UI job did not complete"); + assert!( + std::time::Instant::now() < deadline, + "progressive UI job did not complete: {:?}", + h.app.session.execute("render.status", &json!({"job":job})) + ); std::thread::sleep(std::time::Duration::from_millis(5)); h.frames(1); } @@ -2018,7 +2065,7 @@ fn cpu_checkpoints_replace_only_the_provisional_texture_and_keep_final_export_an let doc = h.app.session.doc.clone(); let undo = h.app.session.undo.len(); h.app.render_workspace.view.job = Some(second); - let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, adaptive: None, frame: frame.info.clone() }; cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); remember_displayed_job(&mut h.app, false); assert_eq!(displayed_image(&h.app).unwrap().info.job, second); @@ -2078,7 +2125,7 @@ fn cancelling_a_preview_returns_to_the_final_image_without_resetting_pan_or_expo let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); let pending = serde_json::from_value(reply["job"].clone()).unwrap(); h.app.render_workspace.view.job = Some(pending); - let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, adaptive: None, frame: frame.info.clone() }; cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); assert!(h.app.render_workspace.preview_image.is_none(), "a different job's checkpoint must be ignored"); info.frame.job = pending; @@ -2326,11 +2373,332 @@ fn image_method_requests_never_fall_back_or_mix_cpu_and_gpu_options() { assert!(image_params(&h.app).is_err()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn new_render_setups_use_available_cpu_progressive_without_saving_or_starting() { + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.app.session.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.method, if available { ImageMethod::CpuRaytrace } else { ImageMethod::Raster }); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, available.then(CpuProgressiveOptions::default)); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + assert_eq!(h.app.render_workspace.view.raytrace.budget, solidcraft_engine::render::job::CpuBudget::Compact); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(!h.app.render_workspace.view.dirty); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + + // The preference preserves the previous defaults even with a supported native host. + h.app.preferences.render_legacy_image_defaults = true; + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn unsaved_render_defaults_survive_model_edits_and_preserve_local_drafts() { + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.app.session.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Subject"})).unwrap(); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + enter(&mut h.app, true).unwrap(); + let expected_method = if available { ImageMethod::CpuRaytrace } else { ImageMethod::Raster }; + let expected_sampling = available.then(CpuProgressiveOptions::default); + assert_eq!(h.app.render_workspace.view.method, expected_method); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, expected_sampling); + + let before = h.app.session.undo.len(); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#123456"})).unwrap(); + let edited = h.app.session.doc.clone(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.render_workspace.view.method, expected_method, "a model edit must not replace the unsaved CPU baseline with Raster"); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, expected_sampling); + assert!(h.app.session.doc.render.setups.is_empty()); + assert!(Arc::ptr_eq(&edited, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), before + 1, "only the appearance edit creates undo history"); + + // Defaults apply when opening a new setup, never retrospectively to this unsaved choice. + h.app.preferences.render_legacy_image_defaults = true; + h.app.session.set_render_job_host(None).unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 1.25; + let sampling = expected_sampling.map(|options| CpuProgressiveOptions { samples_per_pixel: 24, ..options }); + h.app.render_workspace.view.raytrace.progressive = sampling; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#654321"})).unwrap(); + let edited = h.app.session.doc.clone(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.render_workspace.view.method, expected_method); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, sampling); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 1.25); + assert!(h.app.render_workspace.view.dirty); + assert!(h.app.session.doc.render.setups.is_empty()); + assert!(Arc::ptr_eq(&edited, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), before + 2); + assert!(h.app.render_workspace.view.job.is_none()); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster, "the next explicit new load follows the changed defaults"); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn first_numeric_edit_persists_the_unsaved_image_route_once_without_saving_navigation() { + use solidcraft_engine::doc::render_settings::RenderSetup; + use solidcraft_engine::render::job::CpuHost; + let mut h = Harness::new(); + h.app.session.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Subject"})).unwrap(); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.draft.width = 32; + h.app.render_workspace.view.draft.height = 24; + h.app.render_workspace.view.draft.background = [3, 4, 5]; + let before = setups::draft(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + setups::persist_editor(&mut h.app, &before).unwrap(); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "opening an editor never creates a setup"); + assert_eq!(h.app.session.undo.len(), undo); + if available { + h.app.render_workspace.view.draft.exposure_ev = 1.25; + } else { + h.app.render_workspace.view.draft.width = 128; + } + let expected = setups::draft(&h.app).unwrap(); + setups::persist_editor(&mut h.app, &before).unwrap(); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + assert_eq!(saved.job, expected.job, "the first numerical patch must carry the intended CPU/progressive route"); + assert_eq!(saved.exposure_ev, expected.exposure_ev); + assert_eq!((saved.width, saved.height), (expected.width, expected.height)); + assert_eq!(saved.background, [3, 4, 5], "first creation preserves the visible baseline, not engine defaults"); + assert_eq!(saved.camera, RenderSetup::default().camera, "numeric edits retain the explicit Update shot camera policy"); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(h.app.render_workspace.view.job.is_none()); + setups::sync_revision(&mut h.app); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.draft, saved); + assert_eq!( + h.app.render_workspace.view.raytrace.progressive, + expected.job.and_then(|job| match job { + solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. } => options.progressive, + _ => None, + }) + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + + // Undo of an actual saved setup is still a removal, not an active unsaved baseline. + h.app.preferences.render_legacy_image_defaults = true; + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.session.doc.render.setups.is_empty()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); +} + +#[test] +fn render_image_defaults_preserve_offline_and_saved_setups_and_explicit_sampling() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob, RenderSetup}; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions}; + let mut h = Harness::new(); + for host in [None, Some(CpuHost::cooperative())] { + h.app.session.set_render_job_host(host).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + } + let progressive = CpuProgressiveOptions { samples_per_pixel: 32, seed: 81 }; + for job in [ + None, + Some(RenderJob::Raster { transparent_background: true }), + Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(CpuJob { primary_samples: 4, ..Default::default() }) }), + Some(RenderJob::CpuRaytrace { + transparent_background: false, + options: Box::new(CpuJob { progressive: Some(progressive), ..Default::default() }), + }), + ] { + let setup = RenderSetup { width: 32, height: 24, job, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"Saved","set":setup})).unwrap(); + h.app.render_workspace.view.name = "Saved".into(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.draft, setup); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + if let Some(RenderJob::CpuRaytrace { options, .. }) = setup.job { + assert_eq!(h.app.render_workspace.view.raytrace.progressive, options.progressive); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, options.primary_samples); + } else { + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + } + } + + // Selecting the CPU method is an explicit new choice. It supplies sampling but retains + // existing progressive intent; legacy preferences retain the fixed route and spatial AA. + let mut h = Harness::new(); + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.primary_samples = 16; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions::default())); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 1); + h.app.render_workspace.view.raytrace.progressive = Some(progressive); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(progressive)); + h.app.preferences.render_legacy_image_defaults = true; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.primary_samples = 16; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 16); +} + +fn sampling_policy_fixture(fixed: bool) -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + if fixed { + h.app + .run( + "render.settings.set", + json!({"name":"Sampling intent","set":{"width":64,"height":32,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"primary_samples":4,"shadows":false,"lights":[]}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Sampling intent".into(); + setups::load(&mut h.app); + } else { + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 32; + } + h.app.render_workspace.view.live_paused = true; + inspector::select_editor(&mut h.app, inspector::Editor::Sampling); + h.frames(3); + if crate::scenario::rect_of("render:cpu-spp").is_none() { + h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr("render.children.cpu"))}})).unwrap(); + } + h.frames(2); + h +} + +#[test] +fn normal_cpu_progressive_sampling_is_status_without_an_off_selector_or_paint_mutation() { + let mut h = sampling_policy_fixture(false); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let before = h.app.render_workspace.view.raytrace.clone(); + h.frames(3); + assert!(crate::scenario::rect_of("render:cpu-sampling").is_some()); + assert!(crate::scenario::rect_of("render:cpu-spp-field").is_some()); + assert!(crate::scenario::rect_of("render:cpu-fixed").is_none()); + assert!(crate::scenario::rect_of("render:cpu-adopt-progressive").is_none()); + assert!(crate::scenario::rect_of("render:aa").is_none()); + assert_eq!(h.app.render_workspace.view.raytrace, before); + assert!(before.progressive.is_some()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn saved_fixed_cpu_sampling_requires_explicit_adoption_and_keeps_other_intent() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = sampling_policy_fixture(true); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let before = setups::snapshot(&h.app).unwrap(); + let camera = h.app.cam; + h.frames(3); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(crate::scenario::rect_of("render:cpu-fixed").is_none()); + h.step(&json!({"click":{"handle":"render:cpu-adopt-progressive"}})).unwrap(); + h.frames(3); + let saved = &h.app.session.doc.render.setups["Sampling intent"]; + assert_eq!((saved.width, saved.height, saved.exposure_ev), (64, 32, 1.5)); + let Some(RenderJob::CpuRaytrace { options, .. }) = &saved.job else { panic!("CPU method must stay selected") }; + assert_eq!(options.primary_samples, 1); + assert!(options.progressive.is_some()); + assert!(!options.shadows); + assert_eq!(options.lights, Some(Vec::new())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn fixed_cpu_adoption_refuses_reflection_or_size_changes_instead_of_rewriting_them() { + use solidcraft_engine::render::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; + let mut h = sampling_policy_fixture(true); + let reflection = + ReflectionOptions { bodies: vec![ReflectionBody { body: "Body".into(), mode: ReflectionMode::RoughSpecular }], samples: 64, max_bounces: 2 }; + h.app.render_workspace.view.raytrace.reflections = Some(reflection.clone()); + h.frames(3); + h.step(&json!({"click":{"handle":"render:cpu-adopt-progressive"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, Some(reflection)); + h.app.render_workspace.view.raytrace.reflections = None; + h.app.render_workspace.view.draft.width = 2048; + h.app.render_workspace.view.draft.height = 2048; + h.frames(3); + let document = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:cpu-adopt-progressive"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); +} + +#[test] +fn explicit_fixed_cpu_sampling_survives_method_switches_reselection_and_saved_reload() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert!(h.app.render_workspace.view.raytrace.progressive.is_some()); + inspector::select_editor(&mut h.app, inspector::Editor::Sampling); + h.app.preferences.render_legacy_image_defaults = true; + h.frames(3); + h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr("render.children.cpu"))}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-fixed"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + h.app.render_workspace.view.raytrace.primary_samples = 4; + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::CpuRaytrace, ImageMethod::Raster, ImageMethod::CpuRaytrace] { + select_image_method(&mut h.app, method); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none(), "switching methods must preserve an explicit fixed choice"); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + } + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::CpuRaytrace] { + select_image_method(&mut h.app, method); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none(), "a saved fixed setup must not be converted on reselect"); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + } + assert!(h.app.render_workspace.view.job.is_none()); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn native_cpu_controls_check_and_start_the_same_capture_and_keep_it_exportable() { use solidcraft_engine::render::job::{CpuHost, Phase}; let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = true; let host = CpuHost::for_platform().unwrap(); h.app.session.set_render_job_host(Some(host.clone())).unwrap(); h.app.render_workspace.image_host = Some(host); @@ -2423,7 +2791,7 @@ fn native_cpu_controls_check_and_start_the_same_capture_and_keep_it_exportable() h.app.run("render.export", json!({"job":id,"path":path})).unwrap(); assert_eq!(std::fs::read(path).unwrap(), frame.png()); h.app.render_workspace.view.transparent = true; - assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_opaque_required"))); + assert_eq!(image_params(&h.app).unwrap()["transparent_background"], true); h.app.render_workspace.view.transparent = false; h.app.render_workspace.view.raytrace.primary_samples = 3; assert!(image_params(&h.app).is_err()); @@ -2842,9 +3210,11 @@ fn gpu_material_recipes_use_exact_linear_absorption_without_changing_saved_appea h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); h.app.session.mark_saved(); - let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); let doc = h.app.session.doc.clone(); let undo = h.app.session.undo.len(); + // Exercise the retained ordinal-only adapter; stable Glass capture is covered separately. + target.stable_target = None; h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; h.app.render_workspace.view.materials.enabled = true; let mut count = 0; @@ -2897,6 +3267,9 @@ fn numeric_editor_save_refreshes_only_unchanged_runtime_binding_sources() { [(ImageMethod::GpuRaytrace, false), (ImageMethod::GpuRaytrace, true), (ImageMethod::CpuRaytrace, false), (ImageMethod::CpuRaytrace, true)] { let mut h = Harness::new(); + // This fixture exercises changing fixed AA/reflection attempts, independently of + // progressive sampling's one-attempt-per-camera-sample contract. + h.app.preferences.render_legacy_image_defaults = true; h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Target"})).unwrap(); enter(&mut h.app, true).unwrap(); select_image_method(&mut h.app, method); @@ -2953,6 +3326,7 @@ fn numeric_editor_save_refreshes_only_unchanged_runtime_binding_sources() { fn undo_numeric_editor_sync_preserves_runtime_inputs_and_camera_draft() { use solidcraft_engine::render::job::ReflectionMode; let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = true; h.call("ui.resize", json!({"width":1600,"height":2600})); h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Target"})).unwrap(); enter(&mut h.app, true).unwrap(); @@ -2996,26 +3370,29 @@ fn gpu_material_identity_requires_explicit_revalidation_and_never_retargets() { let mut h = Harness::new(); h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + // Glass revalidation keeps the original ordinal identity contract, even + // with a stable capture target. Coat ordinal shifts have their own test. let mut binding = materials::Binding::new(target, &h.app); - binding.coat_enabled = true; + binding.glass_enabled = true; h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; h.app.render_workspace.view.materials.enabled = true; h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; - materials::params(&h.app, &mut json!({})).unwrap(); + let capture = |app: &SolveApp| materials::params(app, &mut json!({"settings":setups::draft(app).unwrap()})); + capture(&h.app).unwrap(); h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); - assert!(materials::params(&h.app, &mut json!({})).is_err()); + assert!(capture(&h.app).is_err()); materials::revalidate(&mut h.app, &mut binding).unwrap(); h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; - materials::params(&h.app, &mut json!({})).unwrap(); + capture(&h.app).unwrap(); h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[20,0,0],"body_name":"Other","operation":"new"})).unwrap(); let scene = h.app.run("render.scene", json!({})).unwrap(); let target: materials::Target = serde_json::from_value(scene["bodies"].as_array().unwrap().iter().find(|body| body["name"] == "Other").unwrap().clone()).unwrap(); let mut moved = materials::Binding::new(target.clone(), &h.app); - moved.coat_enabled = true; + moved.glass_enabled = true; h.app.render_workspace.view.materials.bindings = vec![moved.clone()]; h.app.run("browser.visibility", json!({"items":["Optics"],"visible":false})).unwrap(); - assert!(materials::params(&h.app, &mut json!({})).is_err()); + assert!(capture(&h.app).is_err()); assert!(materials::revalidate(&mut h.app, &mut moved).is_err(), "a surviving body with a new ordinal must be selected explicitly"); assert_eq!(moved.target, target); let scene = h.app.run("render.scene", json!({})).unwrap(); @@ -3029,7 +3406,7 @@ fn gpu_material_identity_requires_explicit_revalidation_and_never_retargets() { } #[test] -fn clicked_gpu_glass_recipe_stays_temporary_and_blocks_cpu_rendering() { +fn clicked_gpu_glass_recipe_stays_temporary_and_preserves_cpu_certified_numbers() { let mut h = Harness::new(); h.call("ui.resize", json!({"width":1600,"height":2200})); h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); @@ -3049,8 +3426,23 @@ fn clicked_gpu_glass_recipe_stays_temporary_and_blocks_cpu_rendering() { assert!(binding.glass_enabled && !binding.coat_enabled && !binding.maps_enabled); assert_eq!(binding.glass.recipe, Some("starter.glass.amber-tint")); assert_eq!(binding.target.name, "Optics"); + let glass = binding.glass.clone(); h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; - assert!(image_params(&h.app).is_err(), "CPU must not silently ignore active GPU material assignments"); + let cpu = image_request(&h.app).unwrap(); + let authored = &cpu["settings"]["optics"][0]["optics"]; + assert_eq!(authored["boundary"], "closed_mesh"); + assert_eq!(authored["ior"], glass.ior); + assert_eq!(authored["absorption_per_mm"], json!(glass.absorption)); + let optical: solidcraft_engine::doc::render_optics::OpticalMaterial = serde_json::from_value(authored.clone()).unwrap(); + let lowered = optical.to_cpu(h.app.render_workspace.view.materials.bindings[0].target.ordinal, "Optics").unwrap(); + assert_eq!(lowered.boundary, solidcraft_engine::render::job::DielectricBoundary::ClosedBox); + assert_eq!(lowered.ior, glass.ior); + assert_eq!(lowered.absorption_per_mm, glass.absorption); + assert_eq!( + h.app.render_workspace.view.materials.bindings[0].glass.boundary, + materials::Boundary::Closed, + "CPU certification never downgrades the authored preset boundary" + ); assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); assert!(!h.app.session.is_dirty()); } @@ -3090,6 +3482,49 @@ fn clicked_gpu_material_at_assignment_limit_edits_existing_but_cannot_add_anothe assert!(!h.app.session.is_dirty()); } +#[test] +fn new_cpu_reflection_matches_sampling_without_rewriting_explicit_attempts() { + use solidcraft_engine::render::job::ReflectionMode; + for legacy in [false, true] { + let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = legacy; + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + enter(&mut h.app, true).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + let expected = if legacy { 4 } else { 1 }; + assert_eq!(h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().samples, expected); + let request = image_request(&h.app).expect("adding the first mirror must leave a renderable request"); + assert_eq!(request["raytrace"]["reflections"]["samples"], expected); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Reflector"); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["reflections"]["samples"], expected); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + + // Existing numerical intent is never silently reduced when a body mode changes. + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 4; + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().samples, 4); + assert_eq!(image_request(&h.app).is_ok(), legacy); + inspector::select_editor(&mut h.app, inspector::Editor::Sampling); + h.call("ui.resize", json!({"width":1600,"height":2600})); + h.frames(3); + h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr("render.children.cpu"))}})).unwrap(); + h.frames(3); + assert_eq!( + h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().samples, + 4, + "showing the field must preserve unsupported existing attempts" + ); + assert_eq!(image_request(&h.app).is_ok(), legacy); + } +} + #[test] fn cpu_reflection_controls_preserve_exact_targets_and_engine_bounds() { use solidcraft_engine::render::job::ReflectionMode; @@ -3308,6 +3743,20 @@ fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host() denoise: true, lens: Some(ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 123.0 }), lighting: Some(StudioLighting { + punctual_lights: Default::default(), + directional_lights: solidcraft_engine::render::job::DirectionalLights::new(&[ + solidcraft_engine::render::job::DirectionalLightOptions { + direction: [0.0, 0.0, 2.0], + color: [0.25, 0.5, 1.0], + intensity: 0.0, + }, + solidcraft_engine::render::job::DirectionalLightOptions { + direction: [3.0, -4.0, 5.0], + color: [0.6, 0.4, 0.2], + intensity: 2.5, + }, + ]) + .unwrap(), environment: [0.25, 0.5, 0.75], sun: Some(Sun { direction: [2.0, 3.0, 4.0], angular_radius_rad: 0.0123456789, radiance: [11.0, 22.0, 33.0] }), area_lights: AreaLights::new(&[AreaLight { @@ -3382,6 +3831,51 @@ fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host() assert_eq!(reopened.render.setups["GPU copy"], expected, "the native container keeps exact numeric intent"); } +#[test] +fn default_cpu_progressive_request_preserves_area_and_led_lighting_without_saving() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{CpuProgressiveOptions, RectangleLightOptions, led_strip::LedStripOptions}; + let mut h = Harness::new(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions::default())); + let lights = vec![ + RectangleLightOptions { + center_mm: [0.0, 0.0, 100.0], + edge_u_mm: [20.0, 0.0, 0.0], + edge_v_mm: [0.0, -30.0, 0.0], + color: [0.3, 0.5, 0.7], + intensity: 5.0, + }, + LedStripOptions { + center_mm: [10.0, 20.0, 80.0], + length_mm: 40.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.68, 0.38], + intensity: 3.0, + } + .rectangle() + .unwrap(), + ]; + h.app.render_workspace.view.raytrace.area_lights = Some(lights.clone()); + h.app.render_workspace.view.raytrace.area_samples = Some(64); + h.app.render_workspace.view.raytrace.seed = Some(9123); + let request = image_request(&h.app).expect("default progressive sampling must accept the complete area/LED setup"); + let setup: RenderSetup = serde_json::from_value(request["settings"].clone()).unwrap(); + setup.validate().unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = setup.job else { panic!("CPU method must be preserved") }; + assert_eq!(options.progressive, Some(CpuProgressiveOptions::default())); + assert_eq!(options.area_lights, Some(lights)); + assert_eq!((options.area_samples, options.seed), (Some(64), Some(9123))); + assert!(request.get("progressive").is_none(), "CPU sampling must not select the GPU executor"); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + #[test] fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values() { use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; @@ -3399,7 +3893,12 @@ fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values "area_samples":16,"seed":9123,"environment":{"color":[0.0,0.0,0.0],"intensity":2.0} })) .unwrap(); - let mut expected = RenderSetup { camera: h.app.cam, exposure_ev: 1.5, job: Some(RenderJob::CpuRaytrace { options }), ..Default::default() }; + let mut expected = RenderSetup { + camera: h.app.cam, + exposure_ev: 1.5, + job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options) }), + ..Default::default() + }; h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); h.app.render_workspace.view.name = "CPU numeric".into(); setups::load(&mut h.app); @@ -3422,7 +3921,7 @@ fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values assert!(json!(expected)["job"]["options"].get("exposure_ev").is_none()); for value in [json!({}), json!({"lights":[],"punctual_lights":[],"area_lights":[],"environment":{"color":[0.0,0.0,0.0],"intensity":0.0}})] { let options: CpuJob = serde_json::from_value(value).unwrap(); - expected.job = Some(RenderJob::CpuRaytrace { options }); + expected.job = Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options) }); h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); setups::load(&mut h.app); assert_eq!(setups::snapshot(&h.app).unwrap(), expected); @@ -3433,6 +3932,8 @@ fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values fn cpu_progressive_controls_resize_only_on_request_and_save_reload_without_a_host() { use solidcraft_engine::render::job::CpuProgressiveOptions; let mut h = Harness::new(); + // Exercise the retained fixed-to-progressive control, rather than the new method default. + h.app.preferences.render_legacy_image_defaults = true; h.call("ui.resize", json!({"width":1600,"height":2600})); enter(&mut h.app, true).unwrap(); inspector::select_editor(&mut h.app, inspector::Editor::Sampling); @@ -3509,7 +4010,7 @@ fn cpu_progressive_setup_preserves_hidden_values_empty_lists_and_one_exposure() width: 32, height: 16, exposure_ev: -1.5, - job: Some(RenderJob::CpuRaytrace { options }), + job: Some(RenderJob::CpuRaytrace { transparent_background: false, options: Box::new(options) }), ..Default::default() }; h.app.run("render.settings.set", json!({"name":"Progressive hidden","set":expected})).unwrap(); @@ -3654,7 +4155,7 @@ fn hdr_ui_save_embeds_once_without_a_host_and_reload_never_reopens_the_source_pa assert_eq!(h.app.session.doc.render.resources.len(), 1, "both setups share one source payload"); assert_eq!(h.app.session.doc.render.resources.total_bytes(), bytes.len()); let cpu = h.app.session.doc.render.setups.get("HDR CPU").unwrap().clone(); - assert!(matches!(&cpu.job, Some(RenderJob::CpuRaytrace { options }) + assert!(matches!(&cpu.job, Some(RenderJob::CpuRaytrace { options, .. }) if options.hdr.unwrap().samples == 64 && options.progressive.unwrap().samples_per_pixel == 7 && options.progressive.unwrap().seed == 84)); let encoded = h.app.session.doc.to_json(); assert!(!encoded.contains("original-embedded.hdr"), "the document never stores the source path"); @@ -3755,6 +4256,7 @@ fn embedded_hdr_runtime_requests_preserve_temporary_bindings_without_serializing use solidcraft_engine::render::job::ReflectionMode; for target in [hdr::Target::Cpu, hdr::Target::Gpu] { let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = true; h.app.run("solid.box", json!({"body_name":"Target","length":10,"width":20,"height":5})).unwrap(); enter(&mut h.app, true).unwrap(); inspector::select_editor(&mut h.app, inspector::Editor::Output); @@ -3796,6 +4298,67 @@ fn embedded_hdr_runtime_requests_preserve_temporary_bindings_without_serializing } } +#[test] +fn cpu_progressive_sample_editor_uses_the_selected_profile_without_rewriting_existing_intent() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + for (budget, maximum) in [(CpuBudget::Compact, 64), (CpuBudget::Studio, 1024), (CpuBudget::Workstation, 4096)] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + inspector::select_editor(&mut h.app, inspector::Editor::Sampling); + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.draft.width = 8; + h.app.render_workspace.view.draft.height = 8; + h.app.render_workspace.view.raytrace.budget = budget; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: maximum + 1, seed: 82 }); + h.frames(3); + h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr("render.children.cpu"))}})).unwrap(); + h.frames(3); + + // Merely painting the constrained field must retain and refuse an incompatible draft. + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, maximum + 1); + assert!(image_request(&h.app).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + + // A real edit respects the chosen profile, rather than offering the Workstation cap + // under Compact and failing later when the person tries to save or start rendering. + for _ in 0..8 { + let field = crate::scenario::rect_of("render:cpu-spp-field").unwrap(); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let top = crate::scenario::rect_of("render:inspector:header").unwrap().bottom() + Tokens::get().space_8; + let bottom = inspector.bottom() - Tokens::get().space_8; + if field.top() >= top && field.bottom() <= bottom { + break; + } + let delta = field.center().y.clamp(top + field.height() / 2.0, bottom - field.height() / 2.0) - field.center().y; + h.call("ui.scroll", json!({"x":inspector.center().x,"y":(top+bottom)/2.0,"delta":delta})); + h.frames(20); + } + let field = crate::scenario::rect_of("render:cpu-spp-field").unwrap(); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let top = crate::scenario::rect_of("render:inspector:header").unwrap().bottom() + Tokens::get().space_8; + assert!( + inspector.contains_rect(field) && field.top() >= top && field.bottom() <= inspector.bottom() - Tokens::get().space_8, + "the sample editor must be visible before typing" + ); + 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":"4097"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions { samples_per_pixel: maximum, seed: 82 })); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (8, 8)); + assert!(image_request(&h.app).is_ok()); + assert!(h.app.render_workspace.view.job.is_none(), "editing samples must never start a job"); + } +} + #[test] fn cpu_resource_profile_edits_preserve_resolution_samples_and_saved_intent() { use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; @@ -4117,6 +4680,162 @@ fn missing_linear_master_is_never_reconstructed_from_a_finished_png() { assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), bytes); } +#[cfg(not(target_arch = "wasm32"))] +mod linear_format_choices { + use super::*; + use solidcraft_engine::render::job; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + struct Executor(Arc); + struct Work { + ready: Arc, + preview: Option, + png: Option>, + exr: Option>, + } + impl job::ImageWork for Work { + fn step(&mut self, _: usize) -> job::Result { + if self.preview.is_some() || !self.ready.load(Ordering::Acquire) { + return Ok(job::TaskPoll::Pending(job::Progress { phase: job::Phase::Running, done: 1, total: 2 })); + } + Ok(job::TaskPoll::Complete(self.png.take().unwrap())) + } + fn take_preview(&mut self) -> Option { + self.preview.take() + } + fn take_linear_exr(&mut self) -> Option> { + self.exr.take() + } + } + impl job::ImageExecutor for Executor { + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("test-linear-master").unwrap(); + descriptor.profiles[0].features.push(solidcraft_engine::render::RenderFeature::Progressive); + Ok(descriptor) + } + fn preview_samples(&self, _: job::JobOptions) -> Option { + Some(2) + } + fn supports_linear_exr(&self) -> bool { + true + } + fn admit(&self, scene: &ProductScene, request: &job::ImageRequest, _: job::JobOptions) -> job::Result { + let mut admission = job::admit(scene, request)?; + admission.estimated_total_bytes += job::linear_exr::encoded_limit(request.width, request.height)? + 16 * 4; + Ok(admission) + } + fn begin( + &self, + _: ProductScene, + request: job::ImageRequest, + options: job::JobOptions, + cancel: job::CancelToken, + ) -> job::Result> { + use job::ImageWork; + assert_eq!((request.width, request.height), (2, 2)); + let mut png = job::PngTask::new(&request, [200, 30, 50, 255].repeat(4), cancel.clone())?; + let job::TaskPoll::Complete(png) = png.step(4)? else { panic!("the two-row PNG must finish") }; + let exr = if options.linear_exr { + let mut task = job::linear_exr::ExrTask::new(2, 2, vec![[8.0, 0.25, 0.5, 1.0]; 4], cancel)?; + assert!(task.step(2)?); + Some(task.finish()?.0) + } else { + None + }; + Ok(Box::new(Work { + ready: self.0.clone(), + preview: Some(job::ImageWorkPreview { png: png.clone(), samples_per_pixel: 1 }), + png: Some(png), + exr, + })) + } + } + + fn frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 100.0))), events, ..Default::default() }, + |ui| { + studio::format_choices(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); + } + pub(super) fn choose(h: &mut Harness, target: &str) { + frame(h, vec![]); + let at = crate::scenario::rect_of(target).unwrap().center(); + for pressed in [true, false] { + frame( + h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + } + + #[test] + fn exr_choices_use_the_actual_retained_final_master_and_keep_selection_during_previews() { + let mut h = Harness::new(); + h.app.render_workspace.view.studio.linear_exr = true; + choose(&mut h, "render:format-exr"); + assert!(!h.app.render_workspace.view.studio.export_exr, "a future retention flag is not an exportable master"); + let ready = Arc::new(AtomicBool::new(true)); + let host = job::ImageHost::with_executor(Arc::new(Executor(ready.clone()))).unwrap(); + h.app.session.register_render_job_host(host).unwrap(); + let request = json!({"progressive":true,"samples":2,"linear_exr":true,"settings":{"width":2,"height":2}}); + let reply = h.app.session.execute("render.start", &request).unwrap(); + let completed = serde_json::from_value(reply["job"].clone()).unwrap(); + let completed_handle = h.app.session.render_job_handle(completed).unwrap(); + assert_eq!(completed_handle.wait_timeout(Duration::from_secs(10)).unwrap().progress.phase, job::Phase::Completed); + let master = completed_handle.frame().unwrap().unwrap(); + let raw = master.linear_exr().expect("the real host must retain the producer's valid native master"); + assert_eq!(&raw[..4], &20_000_630_u32.to_le_bytes()); + h.app.render_workspace.view.completed = Some(completed); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.render_workspace.view.studio.linear_exr = false; + assert!(studio::linear_export_available(&h.app)); + choose(&mut h, "render:format-exr"); + assert!(h.app.render_workspace.view.studio.export_exr, "completed data determines export, independently of the current draft"); + frame(&mut h, vec![]); + assert!(h.app.render_workspace.view.studio.export_exr, "painting cannot reset an explicit EXR choice"); + let path = h.dir.join("retained-master.exr"); + h.app.session.execute("render.export", &json!({"job":completed,"path":path,"format":"exr"})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), raw); + + ready.store(false, Ordering::Release); + let reply = h.app.session.execute("render.start", &request).unwrap(); + let current = serde_json::from_value(reply["job"].clone()).unwrap(); + let current_handle = h.app.session.render_job_handle(current).unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while current_handle.preview().unwrap().is_none() { + assert!(Instant::now() < deadline, "the deterministic producer must publish its first pass"); + std::thread::sleep(Duration::from_millis(1)); + } + assert!(current_handle.frame().unwrap().is_none()); + h.app.render_workspace.view.job = Some(current); + frame(&mut h, vec![]); + assert!(studio::linear_export_available(&h.app), "the current provisional image must not hide the previous final's master"); + assert!(h.app.render_workspace.view.studio.export_exr); + h.app.render_workspace.view.completed = None; + assert!(!studio::linear_export_available(&h.app), "a provisional PNG cannot enable raw export"); + h.app.render_workspace.view.studio.export_exr = false; + choose(&mut h, "render:format-exr"); + assert!(!h.app.render_workspace.view.studio.export_exr); + h.app.render_workspace.view.completed = Some(completed); + choose(&mut h, "render:format-exr"); + assert!(h.app.render_workspace.view.studio.export_exr); + current_handle.cancel().unwrap(); + h.app.session.set_render_job_host(Some(job::CpuHost::cooperative())).unwrap(); + assert!(h.app.session.render_job_handle(completed).is_err(), "clearing retained session ownership removes that export source"); + assert!(!studio::linear_export_available(&h.app)); + choose(&mut h, "render:format-png"); + assert!(!h.app.render_workspace.view.studio.export_exr, "PNG remains selectable after the master disappears"); + } +} + #[test] fn render_workspace_stage_commands_keep_registered_actions_without_a_ribbon() { let mut h = Harness::new(); @@ -5978,7 +6697,9 @@ fn render_workspace_shots_strip_geometry_and_theme_evidence() { fn appearance_editor_hostile_optics_stay_finite_and_never_panic() { let mut h = Harness::new(); h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); - let target = materials::read_targets(&mut h.app).unwrap().remove(0); + let mut target = materials::read_targets(&mut h.app).unwrap().remove(0); + // Exercise the retained ordinal-only adapter; stable Glass capture is covered separately. + target.stable_target = None; h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; h.app.render_workspace.view.materials.enabled = true; for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1e300] { @@ -6084,53 +6805,86 @@ fn output_viewer_copy_uses_retained_final_pixels_and_refuses_missing_or_oversize /// In a window too narrow for the row, Cancel still shows whole. #[test] fn progress_pill_cancel_keeps_its_label_and_a_long_name_gives_way() { - let mut h = output_viewer_fixture(); - h.app.render_workspace.view.draft.width = 512; - h.app.render_workspace.view.draft.height = 512; - h.app.render_workspace.view.name = "A".into(); - ribbon::perform_job(&mut h.app, "render.start").unwrap(); - let job = h.app.render_workspace.view.job.unwrap(); - h.frames(3); - let whole = crate::scenario::rect_of("render:progress:cancel").unwrap().width(); - let fraction = |h: &mut Harness| { - let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); - status["progress"]["done"].as_f64().unwrap() / status["progress"]["total"].as_f64().unwrap().max(1.0) - }; - assert!(fraction(&mut h) < 0.1); - let long = "A very long shot name that will not fit beside the progress meter ".repeat(4); - let host = h.app.session.render_job_host().unwrap().clone(); - for below in [true, false] { - if !below { - for _ in 0..100_000 { - if fraction(&mut h) >= 0.1 { - break; + for image in [false, true] { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.draft.width = 512; + h.app.render_workspace.view.draft.height = 512; + h.app.render_workspace.view.name = "A".into(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert!(h.app.render_workspace.view.result, "Render opens its image by default"); + if !image { + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + } + h.frames(3); + let whole = crate::scenario::rect_of("render:progress:cancel").unwrap().width(); + let fraction = |h: &mut Harness| { + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + status["progress"]["done"].as_f64().unwrap() / status["progress"]["total"].as_f64().unwrap().max(1.0) + }; + assert!(fraction(&mut h) < 0.1); + let long = "A very long shot name that will not fit beside the progress meter ".repeat(4); + let host = h.app.session.render_job_host().unwrap().clone(); + for below in [true, false] { + if !below { + for _ in 0..100_000 { + if fraction(&mut h) >= 0.1 { + break; + } + host.pump(64).unwrap(); + } + let reached = fraction(&mut h); + assert!((0.1..1.0).contains(&reached), "{reached}"); + } + for name in ["Bracket front view", long.as_str()] { + h.app.render_workspace.view.job_shot = Some(name.into()); + h.frames(3); + let cancel = crate::scenario::rect_of("render:progress:cancel").unwrap(); + let pill = crate::scenario::rect_of("render:progress-pill").unwrap(); + let shown = crate::scenario::rect_of("render:progress:name").unwrap(); + let case = format!("image: {image}, below 10 %: {below}, {} characters", name.len()); + assert!((cancel.width() - whole).abs() < 0.5, "{case}: Cancel {} wide, whole {whole}", cancel.width()); + assert!(pill.contains_rect(cancel), "{case}: {cancel:?} outside {pill:?}"); + assert!(shown.right() < cancel.left(), "{case}"); + let cut = crate::scenario::count_of("render:progress:name:cut"); + assert_eq!(cut, Some(if name == long { 1.0 } else { 0.0 }), "{case}"); + // The shared outer canvas owns the progress row in both views. The image + // viewer reserves that row and its header above the smaller pan/zoom viewport. + let canvas = h.app.shell.content.unwrap(); + let viewport = h.app.viewport.rect.unwrap(); + assert!(canvas.contains_rect(pill), "{case}: {pill:?} outside canvas {canvas:?}"); + for (panel, edge) in h.app.shell.workspace_panels.values() { + if edge.is_some() { + assert!(!pill.intersect(*panel).is_positive(), "{case}: {pill:?} overlaps reserved panel {panel:?}"); + } + } + if image { + assert!(canvas.contains_rect(viewport), "{case}: viewport {viewport:?} outside canvas {canvas:?}"); + assert!(!pill.intersect(viewport).is_positive(), "{case}: {pill:?} covers image viewport {viewport:?}"); + for target in [ + "render:result:view:model", + "render:result:view:fit", + "render:result:view:actual", + "render:result-copy", + "render:result-export", + "render:result-close", + ] { + let header = crate::scenario::rect_of(target).unwrap(); + assert!(canvas.contains_rect(header), "{case}: header {target} {header:?} outside canvas {canvas:?}"); + assert!(!pill.intersect(header).is_positive(), "{case}: {pill:?} covers header {target} {header:?}"); + } + } else { + assert!(viewport.contains_rect(pill), "{case}: {pill:?} outside viewport {viewport:?}"); } - host.pump(64).unwrap(); } - let reached = fraction(&mut h); - assert!((0.1..1.0).contains(&reached), "{reached}"); - } - for name in ["Bracket front view", long.as_str()] { - h.app.render_workspace.view.job_shot = Some(name.into()); - h.frames(3); - let cancel = crate::scenario::rect_of("render:progress:cancel").unwrap(); - let pill = crate::scenario::rect_of("render:progress-pill").unwrap(); - let shown = crate::scenario::rect_of("render:progress:name").unwrap(); - let case = format!("below 10 %: {below}, {} characters", name.len()); - assert!((cancel.width() - whole).abs() < 0.5, "{case}: Cancel {} wide, whole {whole}", cancel.width()); - assert!(pill.contains_rect(cancel), "{case}: {cancel:?} outside {pill:?}"); - assert!(shown.right() < cancel.left(), "{case}"); - let cut = crate::scenario::count_of("render:progress:name:cut"); - assert_eq!(cut, Some(if name == long { 1.0 } else { 0.0 }), "{case}"); - assert!(h.app.viewport.rect.unwrap().contains_rect(pill), "{case}: {pill:?}"); } + // A window too narrow for the whole row: the name is cut and Cancel still shows whole. + h.call("ui.resize", json!({"width": 480, "height": 600})); + h.frames(3); + let cancel = crate::scenario::rect_of("render:progress:cancel").unwrap(); + assert!((cancel.width() - whole).abs() < 0.5, "narrow window: Cancel {} wide, whole {whole}", cancel.width()); + assert_eq!(crate::scenario::count_of("render:progress:name:cut"), Some(1.0)); } - // A window too narrow for the whole row: the name is cut and Cancel still shows whole. - h.call("ui.resize", json!({"width": 480, "height": 600})); - h.frames(3); - let cancel = crate::scenario::rect_of("render:progress:cancel").unwrap(); - assert!((cancel.width() - whole).abs() < 0.5, "narrow window: Cancel {} wide, whole {whole}", cancel.width()); - assert_eq!(crate::scenario::count_of("render:progress:name:cut"), Some(1.0)); } #[test] @@ -6154,6 +6908,96 @@ fn output_viewer_progress_keeps_stage_tools_and_cancel_cancels_without_closing_v assert!(crate::scenario::handle_at("render:pick").is_some()); } +#[test] +fn auto_opened_image_cancel_returns_to_model_and_preserves_previous_or_explicit_views() { + for case in ["first", "previous", "explicit_before", "explicit_after", "comparison", "legacy"] { + let mut h = output_viewer_fixture(); + let previous = if matches!(case, "previous" | "comparison") { + let job = completed_preview(&mut h, [20, 40, 60]); + sync_results(&mut h.app); + Some(job) + } else { + None + }; + if case == "explicit_before" { + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + } else if case == "comparison" { + h.app.run("render.compare", json!({"left":"live","right":0})).unwrap(); + } else if case == "legacy" { + h.app.preferences.render_legacy_image_defaults = true; + } + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert_eq!( + h.app.render_workspace.view.auto_result_job.as_ref().map(|auto| auto.job), + matches!(case, "first" | "previous" | "explicit_after").then_some(job), + "{case}" + ); + if case == "explicit_after" { + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + assert!(h.app.render_workspace.view.auto_result_job.is_none()); + } + ribbon::perform_job(&mut h.app, "render.cancel").unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + host.pump(1024).unwrap(); + if h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "cancelled" { + break; + } + } + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "cancelled"); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, !matches!(case, "first" | "legacy"), "{case}"); + assert!(h.app.render_workspace.view.auto_result_job.is_none()); + assert_eq!(h.app.render_workspace.view.completed, previous, "{case}: cancelling must not change the retained image"); + assert_eq!(h.app.session.render_selected_result(), previous); + assert_eq!(h.app.render_workspace.view.compare.is_some(), case == "comparison"); + if let Some(previous) = previous { + assert_eq!(displayed_image(&h.app).unwrap().info.job, previous); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn auto_opened_image_failure_returns_to_model_and_reports_the_job_error() { + use solidcraft_engine::render::job; + struct Failed; + impl job::ImageExecutor for Failed { + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("gpu-path").unwrap(); + descriptor.profiles[0].features.push(solidcraft_engine::render::RenderFeature::Progressive); + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &job::ImageRequest, _: job::JobOptions) -> job::Result { + job::admit(scene, request) + } + fn begin(&self, _: ProductScene, _: job::ImageRequest, _: job::JobOptions, _: job::CancelToken) -> job::Result> { + Err(job::JobError::new(job::ErrorCode::Internal, "controlled image failure")) + } + } + let mut h = output_viewer_fixture(); + let host = job::ImageHost::with_executor(Arc::new(Failed)).unwrap(); + h.app.session.register_render_job_host(host.clone()).unwrap(); + h.app.render_workspace.path_host = PathHost::Ready(host); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert_eq!(h.app.render_workspace.view.auto_result_job.as_ref().map(|auto| auto.job), Some(job)); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap().progress.phase, job::Phase::Failed); + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.render_workspace.view.auto_result_job.is_none()); + assert!(h.app.status.as_ref().is_some_and(|status| status.0.contains("controlled image failure"))); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); +} + #[test] fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cancelling() { let mut h = output_viewer_fixture(); @@ -6758,7 +7602,7 @@ fn render_lighting_methods_show_reasons_and_budgets_without_changing_method_or_d let reason = match method { ImageMethod::Raster => "render.method_limit_raster", ImageMethod::CpuRaytrace => "render.lighting_samples_need_area", - ImageMethod::GpuRaytrace => "render.light_gpu_punctual", + ImageMethod::GpuRaytrace => "render.lighting_shadow_cpu", }; assert!(crate::scenario::rect_of(&format!("dialog:note:{reason}")).is_some()); if method == ImageMethod::GpuRaytrace { @@ -7140,7 +7984,7 @@ fn render_lighting_shadow_edits_are_undoable_and_preset_reviews_reject_changed_d assert!(!h.app.render_workspace.view.raytrace.shadows); assert_eq!(h.app.session.undo.len(), undo + 1); assert!(matches!(&h.app.session.doc.render.setups["Studio"].job, - Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options }) if !options.shadows)); + Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) if !options.shadows)); h.app.run("edit.undo", json!({})).unwrap(); setups::load(&mut h.app); assert_eq!(h.app.session.doc, before); @@ -7290,6 +8134,135 @@ fn corners(b: &solidcraft_engine::geom::Aabb3) -> Vec { out } +fn cold_render_entry_fixture() -> Harness { + let document = { + let mut author = Harness::new(); + author.app.run("solid.box", json!({"length":60,"width":20,"height":20})).unwrap(); + let saved_camera = Camera { distance: 321.0, ..Default::default() }; + author + .app + .run("render.settings.set", json!({"name":"Studio","set":{"width":1024,"height":4096,"camera":saved_camera,"job":{"method":"raster"}}})) + .unwrap(); + author.app.run("render.settings.set", json!({"name":"Other","set":{"width":321,"job":{"method":"raster"}}})).unwrap(); + (*author.app.session.doc).clone() + }; + let mut h = Harness::new(); + crate::documents::open_tab(&mut h.app, Session::opened(document, None)).unwrap(); + h.call("ui.resize", json!({"width":980,"height":720})); + h.app.render_workspace.view.live_paused = true; + assert!(!h.app.session.is_dirty()); + h +} + +#[test] +fn cold_render_entry_fit_keeps_shot_switch_clean_without_updating_saved_cameras() { + for legacy in [false, true] { + let mut h = cold_render_entry_fixture(); + h.app.preferences.render_legacy_image_defaults = legacy; + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + enter(&mut h.app, true).unwrap(); + if legacy { + assert!(h.app.pending_fit.is_some()); + assert!(h.app.render_workspace.entry_fit.is_some()); + } else { + assert!(h.app.pending_fit.is_none()); + assert!(h.app.render_workspace.entry_fit.is_none()); + assert_eq!(h.app.cam, document.render.setups["Studio"].camera, "a composed saved shot is an exact camera, not a new fit"); + } + h.frames(4); + assert!(h.app.pending_fit.is_none()); + assert!(h.app.render_workspace.entry_fit.is_none()); + assert_ne!(h.app.cam, camera, "the cold automatic fit must actually move the camera"); + setups::refresh_dirty(&mut h.app); + assert!(!h.app.render_workspace.view.dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(!h.app.session.is_dirty()); + switch_shot(&mut h.app, "Other".into()); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Other"); + assert_eq!(h.app.render_workspace.view.draft.width, 321); + 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); + } +} + +#[test] +fn render_entry_fit_preserves_real_camera_and_numeric_draft_confirmation() { + for kind in ["camera", "numeric"] { + for timing in ["before-entry", "pending-fit", "settled-fit"] { + let mut h = cold_render_entry_fixture(); + // Exercise entry Fit rather than the separate authored-camera activation policy. + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":Camera::default()}})).unwrap(); + if timing == "before-entry" { + setups::load(&mut h.app); + } else { + enter(&mut h.app, true).unwrap(); + assert!(h.app.pending_fit.is_some()); + if timing == "settled-fit" { + h.frames(4); + } + } + if kind == "camera" { + h.app.cancel_view_animation(); + h.app.cam.yaw += 0.25; + } else { + h.app.render_workspace.view.draft.width = 205; + } + if timing == "before-entry" { + enter(&mut h.app, true).unwrap(); + assert!(h.app.render_workspace.entry_fit.is_none()); + } + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + h.frames(4); + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "{kind} {timing}"); + switch_shot(&mut h.app, "Other".into()); + assert!(inspector::confirmation_open(&h.app), "{kind} {timing}"); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + 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); + } + } +} + +#[test] +fn cold_cpu_entry_after_resize_uses_the_settled_render_layout_for_its_fit() { + for fov in [0.0, 0.8] { + for warm in [(1600, 1000), (700, 480)] { + let mut h = cold_render_entry_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"width":1024,"height":768,"camera":Camera::default(), + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":16,"seed":0}}}}}), + ) + .unwrap(); + let session = Session::opened((*h.app.session.doc).clone(), None); + crate::documents::open_tab(&mut h.app, session).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":warm.0,"height":warm.1})); + h.frames(4); + h.app.ui.perspective = fov > 0.0; + h.app.cam.fov = fov; + let source = h.app.cam; + let document = h.app.session.doc.clone(); + h.call("ui.resize", json!({"width":1100,"height":760})); + enter(&mut h.app, true).unwrap(); + h.frames(6); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let expected = h.app.try_fitted_bounds(source, &scene.bounds).expect("the final measured Render layout must admit a fit"); + assert_eq!(h.app.cam, expected, "warm {warm:?}, fov {fov}: an automatic fit must settle in the current Render layout"); + assert!(h.app.pending_fit.is_none()); + assert!(!h.app.render_workspace.view.dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(!h.app.session.is_dirty()); + } + } +} + /// Entering Render fits the product to the setup in effect, not to the draft that setup /// replaces: in a cold workspace whose saved Studio setup is portrait (1024 × 4096) the fit /// waits for the setup to load, so with Frame open the product sits inside the final 1:4 @@ -7375,6 +8348,84 @@ fn render_results_batch_fixture() -> Harness { h } +#[test] +fn scene_and_output_section_all_shots_use_pointer_queue_actions_and_keep_saved_camera_policy() { + for (kind, target) in [("nothing", "render:scene:all-shots"), ("output", "render:output:section-all-shots")] { + let mut h = render_results_batch_fixture(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.render_workspace.view.live_paused = true; + h.app.run("view.render_select", json!({"kind":kind})).unwrap(); + h.app.render_workspace.view.draft.width = 128; + h.app.render_workspace.view.draft.height = 128; + h.app.render_workspace.view.draft.background = [31, 51, 71]; + h.app.render_workspace.view.dirty = true; + h.frames(3); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(h.app.render_workspace.view.job.is_none(), "painting {kind} must not submit a batch"); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let saved_camera = h.app.session.doc.render.setups.values().next().unwrap().camera; + let navigation = h.app.cam; + h.step(&json!({"click":{"handle":target}})).unwrap(); + h.frames(1); + let queue = h.app.session.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 2), "{kind}"); + let handle = h.app.session.render_job_handle(queue.job.unwrap()).unwrap(); + let status = handle.status().unwrap(); + assert_eq!((status.request.width, status.request.height), (128, 128)); + assert_eq!(status.request.background, [31, 51, 71]); + assert_eq!(status.request.camera, saved_camera, "the existing batch policy replaces only each saved camera"); + assert_eq!(h.app.session.doc.render.setups.values().next().unwrap().width, 8); + assert!(ribbon::perform_job(&mut h.app, "render.batch").is_err(), "an active queue cannot be duplicated"); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert_eq!(h.app.cam, navigation); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn all_shots_batch_waits_for_live_cleanup_and_keeps_the_captured_current_settings() { + let Some(mut h) = live_cpu_fixture() else { return }; + for (index, name) in ["A", "B"].iter().enumerate() { + let camera = Camera { yaw: 0.2 + index as f64 * 0.3, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":camera,"width":8,"height":8,"job":{"method":"raster"}}})).unwrap(); + } + h.app.render_workspace.view.draft.width = 7; + h.app.render_workspace.view.draft.height = 5; + live::advance(&mut h.app, &h.ctx, 1.0); + live::advance(&mut h.app, &h.ctx, 1.3); + assert_eq!(live::inspect(&h.app)["pending"], true); + let expected = image_request(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + ribbon::perform_job(&mut h.app, "render.batch").unwrap(); + assert!(live::final_pending(&h.app)); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(ribbon::perform_job(&mut h.app, "render.batch").is_err()); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while h.app.session.render_queue_state().job.is_none() { + live::advance(&mut h.app, &h.ctx, 1.4); + assert!(std::time::Instant::now() < deadline, "batch did not leave live cleanup: {}", live::inspect(&h.app)); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(!live::final_pending(&h.app)); + assert_eq!(live::inspect(&h.app)["draining"], 0); + let job = h.app.session.render_queue_state().job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let status = handle.status().unwrap(); + assert_eq!((status.request.width, status.request.height), (7, 5)); + assert_eq!(status.request.camera, h.app.session.doc.render.setups["A"].camera); + assert_eq!(json!(status.request.raytrace.as_ref().unwrap().progressive), expected["settings"]["job"]["options"]["progressive"]); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + let _ = h.app.run("render.cancel", json!({"job":job})); +} + #[test] fn render_results_batch_output_footer_only_starts_on_click_and_cancel_drops_waiting_shots() { let mut h = render_results_batch_fixture(); @@ -7404,6 +8455,6240 @@ fn render_results_batch_output_footer_only_starts_on_click_and_cancel_drops_wait assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); } +#[cfg(not(target_arch = "wasm32"))] +fn live_cpu_fixture() -> Option { + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("native CPU live tests require raytrace-cpu"); + return None; + } + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Subject"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 81 }); + h.app.viewport.rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(8.0, 8.0))); + Some(h) +} + +#[cfg(not(target_arch = "wasm32"))] +fn wait_live_complete(h: &mut Harness, now: f64) -> serde_json::Value { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + live::advance(&mut h.app, &h.ctx, now); + let state = live::inspect(&h.app); + assert!(state["error"].is_null(), "{state}"); + if state["complete"] == true { + return state; + } + assert!(std::time::Instant::now() < deadline, "live image did not finish: {state}"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn automatic_live_cpu_pixels_refresh_without_replacing_final_export_or_saved_settings() { + use solidcraft_engine::render::job::{JobId, Phase}; + let Some(mut h) = live_cpu_fixture() else { return }; + let reply = h + .app + .session + .execute( + "render.start", + &json!({"settings":{"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":82}}}}}), + ) + .unwrap(); + let final_job: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let final_handle = h.app.session.render_job_handle(final_job).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while final_handle.status().unwrap().progress.phase != Phase::Completed { + assert!(std::time::Instant::now() < deadline); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let bytes = final_handle.frame().unwrap().unwrap().png().to_vec(); + assert_eq!(h.app.session.render_retained_results().unwrap().len(), 1); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let settings = setups::draft(&h.app).unwrap(); + live::advance(&mut h.app, &h.ctx, 10.0); + assert_eq!(live::inspect(&h.app)["pending"], false, "visual edits are grouped before capture"); + let first = wait_live_complete(&mut h, 10.3); + let live_job: JobId = serde_json::from_value(first["job"].clone()).unwrap(); + assert_ne!(live_job.session, final_job.session, "automatic pixels belong to an isolated session"); + assert_eq!(first["samples"], 3); + assert!(first["hash"].as_str().is_some_and(|hash| !hash.is_empty())); + assert_eq!(setups::draft(&h.app).unwrap(), settings, "live resolution must never change final settings"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(h.app.session.render_retained_results().unwrap().len(), 1); + assert_eq!(h.app.session.render_selected_result(), Some(final_job)); + assert_eq!(final_handle.frame().unwrap().unwrap().png(), bytes); + let path = h.dir.join("automatic-preview.png"); + assert!(h.app.session.execute("render.export", &json!({"job":live_job,"path":path.to_string_lossy()})).is_err()); + assert!(!path.exists(), "automatic output cannot become the final export source"); + + h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#204080"})).unwrap(); + live::advance(&mut h.app, &h.ctx, 11.0); + assert!(!live::picking_current(&h.app), "old pixels must not authorize picking a changed scene"); + let second = wait_live_complete(&mut h, 11.3); + assert_ne!(second["hash"], first["hash"], "the actual image must reflect the material edit"); + assert!(live::picking_current(&h.app)); + assert_eq!(h.app.session.render_selected_result(), Some(final_job)); + assert_eq!(final_handle.frame().unwrap().unwrap().png(), bytes); + + h.app.cam.yaw += 0.3; + assert!(!live::picking_current(&h.app), "same-frame navigation cannot pick or highlight against the previous camera's pixels"); + assert_eq!(live::inspect(&h.app)["complete"], false); + live::advance(&mut h.app, &h.ctx, 12.0); + let third = wait_live_complete(&mut h, 12.3); + assert_ne!(third["generation"], second["generation"]); + assert_ne!(third["hash"], second["hash"], "camera movement must refresh real live pixels"); + assert_eq!(h.app.session.render_retained_results().unwrap().len(), 1); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cancelled_first_manual_cpu_checkpoint_resumes_live_without_retaining_or_exporting_it() { + use solidcraft_engine::render::job::Phase; + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 64; + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().samples_per_pixel = 64; + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + cache_render_images(&mut h.app, &h.ctx); + if displayed_image(&h.app).is_some_and(|image| image.preview.is_some()) { + break; + } + assert!(std::time::Instant::now() < deadline, "actual CPU checkpoint was not published: {:?}", handle.status().unwrap()); + assert_ne!(handle.status().unwrap().progress.phase, Phase::Completed, "the fixture must cancel while a real checkpoint is displayed"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(h.app.render_workspace.view.result); + ribbon::perform_job(&mut h.app, "render.cancel").unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap().progress.phase, Phase::Cancelled); + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result); + assert!(displayed_image(&h.app).is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + live::advance(&mut h.app, &h.ctx, 1.0); + let resumed = wait_live_complete(&mut h, 1.3); + assert_eq!(resumed["suspended"], false); + assert_eq!(resumed["is_current"], true); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(ribbon::action_ready(&h.app, "render.export").is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn live_edits_coalesce_and_pause_drains_late_capture_without_document_or_result_changes() { + let Some(mut h) = live_cpu_fixture() else { return }; + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + live::advance(&mut h.app, &h.ctx, 0.0); + h.app.render_workspace.view.draft.exposure_ev = 0.1; + live::advance(&mut h.app, &h.ctx, 0.1); + h.app.render_workspace.view.draft.exposure_ev = 0.2; + live::advance(&mut h.app, &h.ctx, 0.2); + live::advance(&mut h.app, &h.ctx, 0.39); + assert_eq!(live::inspect(&h.app)["pending"], false); + let generation = live::inspect(&h.app)["generation"].clone(); + live::advance(&mut h.app, &h.ctx, 0.41); + assert_eq!(live::inspect(&h.app)["pending"], true); + assert_eq!(live::inspect(&h.app)["generation"], generation); + let revision = h.app.session.revision; + h.app.session.pending_moves.insert(99, solidcraft_engine::doc::IDENTITY); + live::advance(&mut h.app, &h.ctx, 0.42); + assert_ne!(live::inspect(&h.app)["generation"], generation, "placement previews invalidate even without a document revision"); + assert_eq!(h.app.session.revision, revision); + h.app.run("view.render_live", json!({"paused":true})).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + live::advance(&mut h.app, &h.ctx, 1.0); + let state = live::inspect(&h.app); + if state["pending"] == false && state["draining"] == 0 { + break; + } + assert!(std::time::Instant::now() < deadline, "late live capture did not drain: {state}"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(live::inspect(&h.app)["job"].is_null()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert_eq!(h.app.session.render_selected_result(), None); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.render_job_host().unwrap().admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn current_live_pixels_use_only_the_depth_correct_feedback_callback_and_stale_pixels_have_none() { + let Some(mut h) = live_cpu_fixture() else { return }; + live::advance(&mut h.app, &h.ctx, 1.0); + wait_live_complete(&mut h, 1.3); + h.app.viewport.gpu = Some(crate::gpu::GpuTarget { + format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, + depth: Some(egui_wgpu::wgpu::TextureFormat::Depth24PlusStencil8), + samples: 1, + tess: false, + oit: false, + }); + h.app.render_workspace.host = Some(host_executor(4096, true, 1).unwrap()); + sync_backend(&mut h.app); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Subject".into() }]; + let count = |shapes: &[egui::epaint::ClippedShape]| { + let mut feedback = 0; + let mut model = 0; + for shape in shapes { + if let egui::Shape::Callback(callback) = &shape.shape + && let Some(callback) = callback.callback.downcast_ref::() + { + feedback += usize::from(callback.downcast_ref::().is_some()); + model += usize::from(callback.downcast_ref::().is_some()); + } + } + (feedback, model) + }; + let rect = h.app.viewport.rect.unwrap(); + let mut painted = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| show(&mut h.app, ui)); + painted.textures_delta.clear(); + assert_eq!(count(&painted.shapes), (1, 0), "live pixels receive one feedback pass and no shaded product redraw"); + let scene = h.app.render_workspace.scene.as_ref().unwrap(); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(h.app.cam.target); + let expected = product_projection(h.app.cam, radius, live::projection_rect(&h.app, shot::render_rect(&h.app, rect)), None).to_f32(); + let feedback = painted + .shapes + .iter() + .find_map(|shape| { + if let egui::Shape::Callback(callback) = &shape.shape { + callback + .callback + .downcast_ref::() + .and_then(|callback| callback.downcast_ref::()) + } else { + None + } + }) + .unwrap(); + assert_eq!(feedback.0.view_proj, expected); + assert!( + feedback.0.hl_slot.lock().unwrap().as_ref().is_some_and(|scene| !scene.tris.is_empty() || !scene.blocks.is_empty()), + "the selected target reuses existing highlight geometry" + ); + h.app.cam.yaw += 0.3; + let mut stale = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| show(&mut h.app, ui)); + stale.textures_delta.clear(); + assert_eq!(count(&stale.shapes), (0, 0), "old-camera pixels cannot receive current-camera target feedback"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn live_image_target_outlines_keep_new_material_and_lighting_visible_without_clearing_selection() { + use solidcore_record::Vec3; + use solidcraft_engine::Sel; + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.viewport.rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(64.0, 64.0))); + let world = h.app.session.world_state().unwrap(); + let body = &world.body("Subject").unwrap().body; + // Select the analytic top face; tessellation is only target feedback. + let face = (0..body.face_count()) + .find(|index| body.planar_face(*index).is_some_and(|plane| plane.origin.z == 5.0 && plane.normal() == Vec3::Z)) + .unwrap(); + let point = Vec3::new(5.0, 10.0, 5.0); + h.app.session.selection = vec![Sel::Face { body: "Subject".into(), index: face, point }]; + h.app.viewport.hover = Some(crate::viewport::Hit::Face { body: "Subject".into(), index: face, point }); + let selected = h.app.session.selection.clone(); + live::advance(&mut h.app, &h.ctx, 1.0); + let before = wait_live_complete(&mut h, 1.3); + let outlines = |app: &SolveApp| { + let feedback = crate::viewport::build_highlight(app).merged(); + assert!( + feedback.tris.is_empty() && feedback.pbr.is_empty() && feedback.trans.is_empty(), + "target feedback cannot replace image colour or shadows" + ); + assert!(!feedback.lines.is_empty(), "depth-tested visible outlines must identify the target"); + assert!(feedback.overlay.is_empty() && feedback.xray.is_empty(), "target outlines cannot bypass product depth"); + }; + outlines(&h.app); + h.app.run("appearance.assign", json!({"faces":[[5,10,5]],"color":"#ff0000"})).unwrap(); + assert_eq!(h.app.session.selection, selected, "applying a look keeps the appearance target selected"); + live::advance(&mut h.app, &h.ctx, 2.0); + let after = wait_live_complete(&mut h, 2.3); + assert_ne!(after["hash"], before["hash"], "the selected face's actual image must show its new material"); + assert!(live::picking_current(&h.app)); + outlines(&h.app); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + // Whole-body and unselected hovered faces preserve the same image response. + h.app.session.selection = vec![Sel::Body { name: "Subject".into() }]; + outlines(&h.app); + h.app.session.selection.clear(); + outlines(&h.app); + h.app.viewport.hover = None; + h.app.viewport.hover_bodies = vec!["Subject".into()]; + outlines(&h.app); + h.app.viewport.hover_bodies.clear(); + h.app.session.selection = selected.clone(); + let outline_key = crate::viewport::highlight_key(&h.app); + h.app.preferences.render_legacy_image_defaults = true; + assert_ne!(crate::viewport::highlight_key(&h.app), outline_key, "the cached feedback must follow the compatibility preference"); + assert!(!crate::viewport::build_highlight(&h.app).merged().tris.is_empty(), "legacy Render retains its opaque selected face"); + h.app.preferences.render_legacy_image_defaults = false; + outlines(&h.app); + assert_eq!(h.app.session.selection, selected); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + enter(&mut h.app, false).unwrap(); + assert!(!crate::viewport::build_highlight(&h.app).merged().tris.is_empty(), "Design keeps its existing selected face fill"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn live_image_imported_mesh_keeps_selected_and_hovered_face_and_body_feedback() { + use solidcore_record::Vec3; + use solidcraft_engine::{ + Sel, + doc::{Document, FeatureKind, MeshData}, + render::job::{CpuHost, CpuProgressiveOptions}, + }; + + // Original synthetic triangle geometry follows the real reference-mesh path; + // its display outlines must never become selectable modeling edges. + let mut doc = Document::default(); + doc.add_feature( + FeatureKind::MeshImport { + file: "feedback-plane.stl".into(), + meshes: vec![MeshData { + name: "Reference".into(), + positions: vec![-2., -2., 0., 2., -2., 0., 2., 2., 0., -2., 2., 0.].into(), + triangles: vec![0, 1, 2, 0, 2, 3].into(), + color: None, + }], + }, + Some("Reference"), + ) + .unwrap(); + let mut h = Harness::new(); + h.app = SolveApp::new(Session::new(doc), crate::Services::default()); + // This context's texture deltas must reach the real GPU renderer, rather than + // being discarded by the scenario harness's renderer-free frames. + h.ctx = crate::fonts::test_context(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[9,-1,0],"operation":"new","body_name":"Solid"})).unwrap(); + h.app.run("solid.box", json!({"length":2,"width":4,"height":1,"corner":[0,-2,0],"operation":"new","body_name":"Occluder"})).unwrap(); + h.app.ui.show_grid = false; + h.app.ui.ground_shadow = false; + h.app.set_origin_shown(false); + h.app.cam.set_view(solidcraft_engine::render::StandardView::Top); + h.app.fit_view(); + // The real workflow draws Design before entering Render. Keep its shared + // reference triangles so whole-body feedback uses the actual instance path. + let design_scene = crate::viewport::build_scene(&h.app); + let reference_shared = design_scene.instanced.iter().find(|draw| draw.tris.bounds == [[-2.0, -2.0, 0.0], [2.0, 2.0, 0.0]]).unwrap(); + assert_eq!(reference_shared.look, crate::gpu::InstanceLook::Opaque); + assert_eq!(reference_shared.count(), 1, "Design must draw the reference as a real shared-mesh placement"); + let reference_shared = reference_shared.tris.clone(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 81 }); + h.app.viewport.rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(256., 256.))); + live::advance(&mut h.app, &h.ctx, 1.0); + let picture = wait_live_complete(&mut h, 1.3); + assert_eq!(picture["complete"], true); + assert!(live::has_picture(&h.app) && live::picking_current(&h.app)); + + let world = h.app.session.world_state().unwrap(); + let reference = world.body("Reference").unwrap(); + let mesh = reference.mesh(); + assert!(mesh.display_only_edges && !mesh.edges.is_empty()); + assert!((0..mesh.edges.len()).all(|edge| !mesh.edge_pickable(edge))); + assert_eq!(reference.body.face_count(), 1); + let expected_vertices = mesh.triangles.len() * 3; + let solid = world.body("Solid").unwrap(); + assert!((0..solid.mesh().edges.len()).any(|edge| solid.mesh().edge_pickable(edge))); + let solid_face = (0..solid.body.face_count()).find(|face| solid.body.planar_face(*face).is_some_and(|plane| plane.normal() == Vec3::Z)).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let tokens = crate::theme::Tokens::get(); + let hover_color = [ + tokens.body.r().saturating_add(tokens.hover_face_lift), + tokens.body.g().saturating_add(tokens.hover_face_lift), + tokens.body.b().saturating_add(tokens.hover_face_lift), + 255, + ]; + + // Expand actual highlighted placements too: an empty CPU triangle list alone + // does not mean that a whole-body GPU highlight is missing. + let filled_vertices = |app: &SolveApp, expected_color: [u8; 4]| { + let feedback = crate::viewport::build_highlight(app).merged(); + assert!(feedback.overlay.is_empty() && feedback.xray.is_empty(), "feedback must remain depth-tested"); + assert!(feedback.selected_planned.is_empty() && feedback.hover_planned.is_empty()); + assert!(feedback.selected_blocks.is_empty() && feedback.hover_blocks.is_empty() && feedback.recoloured.is_empty()); + let mut tris = feedback.tris.clone(); + for mesh in feedback.selected_instanced.iter().chain(&feedback.hover_instanced) { + mesh.expand_into(&mut tris); + } + let vertices = tris.as_chunks::<{ crate::gpu::TRI_SIZE }>().0; + for vertex in vertices { + let color = crate::gpu::PaletteIndex(u32::from_le_bytes(vertex[24..28].try_into().unwrap())); + assert_eq!(feedback.palette.get(color), Some(expected_color), "target fill keeps its existing theme color"); + } + vertices.len() + }; + let target = |app: &mut SolveApp, body: &str, face: usize, case: usize| { + app.session.selection.clear(); + app.viewport.hover = None; + app.viewport.hover_bodies.clear(); + app.ui.pick_bodies = case == 3; + let point = Vec3::ZERO; + match case { + 0 => app.session.selection = vec![Sel::Face { body: body.into(), index: face, point }], + 1 => app.session.selection = vec![Sel::Body { name: body.into() }], + _ => { + let hit = crate::viewport::Hit::Face { body: body.into(), index: face, point }; + let picked = crate::viewport::candidate(app, std::slice::from_ref(&hit)).unwrap().1; + assert_eq!(picked, if case == 3 { Sel::Body { name: body.into() } } else { Sel::Face { body: body.into(), index: face, point } }); + app.viewport.hover = Some(hit); + } + } + }; + let mut missing = Vec::new(); + for (case, label) in ["selected face", "selected body", "hovered face", "hovered body"].into_iter().enumerate() { + let color = match case { + 0 => crate::viewport::c4(tokens.sel_face), + 1 => crate::viewport::c4(tokens.body_selected), + _ => hover_color, + }; + target(&mut h.app, "Reference", 0, case); + let selected = h.app.session.selection.clone(); + h.app.preferences.render_legacy_image_defaults = true; + assert_eq!(filled_vertices(&h.app, color), expected_vertices, "legacy {label} fixture must show every triangle once"); + h.app.preferences.render_legacy_image_defaults = false; + assert!(live::has_picture(&h.app)); + if filled_vertices(&h.app, color) != expected_vertices { + missing.push(label); + } + assert_eq!(h.app.session.selection, selected, "painting cannot replace the selected target"); + + // B-rep targets retain outline-only feedback over the same live picture. + target(&mut h.app, "Solid", solid_face, case); + let outlines = crate::viewport::build_highlight(&h.app).merged(); + assert!(outlines.tris.is_empty() && outlines.selected_instanced.is_empty() && outlines.hover_instanced.is_empty()); + assert!(!outlines.lines.is_empty(), "{label}: real B-rep edges retain live-image outlines"); + } + let mut missing_pixels = Vec::new(); + if let Some(mut gpu) = crate::gpu::EguiFixture::new(&mut h.app, [256, 256]) { + let draw = |gpu: &mut crate::gpu::EguiFixture, h: &mut Harness, pointer| { + let pixels = gpu.frame(&h.ctx, vec![pointer], |ui| show(&mut h.app, ui)); + assert_eq!( + (gpu.product_highlight_callbacks, gpu.viewport_callbacks), + (1, 0), + "every measured live-image frame must emit its feedback callback without a shaded-product redraw" + ); + pixels + }; + h.app.session.selection.clear(); + h.app.viewport.hover = None; + h.app.viewport.hover_bodies.clear(); + draw(&mut gpu, &mut h, egui::Event::PointerGone); + let clean = draw(&mut gpu, &mut h, egui::Event::PointerGone); + assert!(live::has_picture(&h.app) && live::picking_current(&h.app), "pixel fixture must paint the actual current live image"); + let projection = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let visible = projection.to_screen(Vec3::new(-1.0, 0.0, 0.0)).unwrap(); + let covered = projection.to_screen(Vec3::new(1.0, 0.0, 0.0)).unwrap(); + let solid_inside = projection.to_screen(Vec3::new(10.0, 0.0, 2.0)).unwrap(); + let solid_bounds = egui::Rect::from_two_pos( + projection.to_screen(Vec3::new(9.0, -1.0, 2.0)).unwrap(), + projection.to_screen(Vec3::new(11.0, 1.0, 2.0)).unwrap(), + ); + let patch = |pixels: &[u8], at: egui::Pos2| { + let (x, y) = (at.x.round() as usize, at.y.round() as usize); + assert!((3..253).contains(&x) && (3..253).contains(&y), "interior patch must stay inside the image: {at:?}"); + (y - 2..=y + 2) + .flat_map(|row| { + (x - 2..=x + 2).flat_map(move |column| pixels[(row * 256 + column) * 4..(row * 256 + column) * 4 + 4].iter().copied()) + }) + .collect::>() + }; + assert_eq!(clean, draw(&mut gpu, &mut h, egui::Event::PointerGone), "the unselected photo must be stable before pixel comparisons"); + for (case, label) in ["selected face", "selected body", "hovered face", "hovered body"].into_iter().enumerate() { + target(&mut h.app, "Reference", 0, case); + let pointer = if case < 2 { egui::Event::PointerGone } else { egui::Event::PointerMoved(visible) }; + draw(&mut gpu, &mut h, pointer.clone()); + if case == 1 || case == 3 { + let feedback = crate::viewport::build_highlight(&h.app); + let instances = if case == 1 { &feedback.selected_instanced } else { &feedback.hover_instanced }; + assert!( + instances.iter().any(|draw| Arc::ptr_eq(&draw.tris, &reference_shared) && draw.count() == 1), + "{label}: the actual callback must receive the Reference's shared-triangle instance stream" + ); + assert!(feedback.tris.is_empty(), "{label}: a CPU triangle fallback would miss the native regression"); + } + let pixels = draw(&mut gpu, &mut h, pointer); + if case >= 2 { + let hit = h.app.viewport.hover.as_ref().unwrap(); + assert!( + matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Reference"), + "{label}: actual pointer must hit the reference face" + ); + let picked = crate::viewport::candidate(&h.app, std::slice::from_ref(hit)).unwrap().1; + assert!( + matches!(&picked, Sel::Body { name } if case == 3 && name == "Reference") + || matches!(&picked, Sel::Face { body, index: 0, .. } if case == 2 && body == "Reference"), + "the real pointer must use the requested face/body filter: {picked:?}" + ); + } + if patch(&pixels, visible) == patch(&clean, visible) { + missing_pixels.push(label); + } + assert_eq!(patch(&pixels, covered), patch(&clean, covered), "{label}: the front body must occlude reference feedback"); + assert_eq!(patch(&pixels, solid_inside), patch(&clean, solid_inside), "{label}: unrelated product pixels must retain the live photo"); + + target(&mut h.app, "Solid", solid_face, case); + let pointer = if case < 2 { egui::Event::PointerGone } else { egui::Event::PointerMoved(solid_inside) }; + draw(&mut gpu, &mut h, pointer.clone()); + let outlines = draw(&mut gpu, &mut h, pointer); + assert_eq!( + patch(&outlines, solid_inside), + patch(&clean, solid_inside), + "{label}: ordinary B-rep feedback must not fill its photo interior" + ); + assert_eq!(patch(&outlines, visible), patch(&clean, visible), "{label}: B-rep feedback must leave the reference photo unchanged"); + let changed_edges = clean + .as_chunks::<4>() + .0 + .iter() + .zip(outlines.as_chunks::<4>().0) + .enumerate() + .filter(|(index, (before, after))| { + let point = egui::pos2((index % 256) as f32 + 0.5, (index / 256) as f32 + 0.5); + before != after && solid_bounds.expand(3.0).contains(point) && !solid_bounds.shrink(4.0).contains(point) + }) + .count(); + assert!(changed_edges > 0, "{label}: normal B-rep outlines must reach actual displayed pixels"); + } + } + target(&mut h.app, "Reference", 0, 0); + enter(&mut h.app, false).unwrap(); + assert_eq!(filled_vertices(&h.app, crate::viewport::c4(tokens.sel_face)), expected_vertices, "Design retains its selected reference face fill"); + assert!((0..mesh.edges.len()).all(|edge| !mesh.edge_pickable(edge)), "feedback must not promote display-only edges to modeling picks"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert!(missing.is_empty(), "live-image reference mesh lost target feedback: {missing:?}"); + assert!(missing_pixels.is_empty(), "live-image reference mesh feedback never reached displayed pixels: {missing_pixels:?}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn live_capture_aspect_matches_product_navigation_and_frame_without_changing_output_size() { + let Some(mut h) = live_cpu_fixture() else { return }; + let output = [h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height]; + for stage in [Stage::Look, Stage::Frame] { + select_stage(&mut h.app, stage.key()); + for dimensions in [egui::vec2(1200.0, 600.0), egui::vec2(900.0, 1400.0)] { + let viewport = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), dimensions); + h.app.viewport.rect = Some(viewport); + live::advance(&mut h.app, &h.ctx, 20.0); + let state = live::inspect(&h.app); + assert!(state["error"].is_null(), "{state}"); + let request = &state["request"]; + let width = request["settings"]["width"].as_u64().unwrap(); + let height = request["settings"]["height"].as_u64().unwrap(); + assert!(width <= 512 && height <= 512); + let canvas = shot::render_rect(&h.app, viewport); + let projected = live::projection_rect(&h.app, canvas); + assert!((f64::from(projected.width() / projected.height()) - width as f64 / height as f64).abs() < 1e-5); + assert!(canvas.contains_rect(projected)); + assert_eq!(request["settings"]["camera"], json!(h.app.cam)); + let centre = crate::viewport::projection(&h.app, projected).to_screen(h.app.cam.target).unwrap(); + assert!(centre.distance(projected.center()) < 0.01); + assert_eq!([h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height], output); + } + } + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().samples_per_pixel = u32::MAX; + live::advance(&mut h.app, &h.ctx, 20.0); + assert!(!live::inspect(&h.app)["error"].is_null()); + for width in [360.0, 600.0] { + let bar = egui::Rect::from_min_size(egui::pos2(20.0, 20.0), egui::vec2(width, crate::ui_kit::StageBar::HEIGHT)); + let mut painted = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 300.0))), ..Default::default() }, + |ui| crate::render_ui::stage_bar(&mut h.app, ui, bar), + ); + painted.textures_delta.clear(); + let pause = crate::scenario::rect_of("render:live:pause").unwrap(); + let note = crate::scenario::rect_of("render:live:status").unwrap(); + assert!(bar.contains_rect(pause), "Pause remains visible even with a long refusal in a narrow bar"); + assert!(pause.right() < note.left()); + assert!(note.width() <= crate::theme::Tokens::get().control_height * 10.0); + assert!(bar.contains_rect(note)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn final_image_waits_for_live_capture_cleanup_and_keeps_the_click_time_request() { + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.draft.width = 7; + h.app.render_workspace.view.draft.height = 5; + live::advance(&mut h.app, &h.ctx, 1.0); + live::advance(&mut h.app, &h.ctx, 1.3); + assert_eq!(live::inspect(&h.app)["pending"], true); + let expected = image_request(&h.app).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert!(live::final_pending(&h.app)); + assert!(ribbon::busy(&h.app)); + assert!(ribbon::perform_job(&mut h.app, "render.start").is_err(), "waiting final requests cannot be duplicated"); + assert!(h.app.render_workspace.view.job.is_none()); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while h.app.render_workspace.view.job.is_none() { + live::advance(&mut h.app, &h.ctx, 1.4); + assert!(std::time::Instant::now() < deadline, "final request did not leave live cleanup: {}", live::inspect(&h.app)); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(!live::final_pending(&h.app)); + assert_eq!(live::inspect(&h.app)["draining"], 0); + let id = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.status().unwrap(); + assert_eq!((status.request.width, status.request.height), (7, 5)); + let sampling = status.request.raytrace.as_ref().unwrap().progressive.unwrap(); + assert_eq!(json!(sampling), expected["settings"]["job"]["options"]["progressive"]); + assert_eq!(json!(status.request.camera), expected["settings"]["camera"]); + assert!(h.app.render_workspace.view.result && h.app.render_workspace.view.follow_job); + let _ = handle.cancel(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn waiting_final_can_be_cancelled_and_refuses_changed_source_instead_of_rendering_a_new_scene() { + for changed in [false, true] { + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.draft.width = 8; + h.app.render_workspace.view.draft.height = 8; + live::advance(&mut h.app, &h.ctx, 1.0); + live::advance(&mut h.app, &h.ctx, 1.3); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert!(live::final_pending(&h.app)); + if changed { + h.app.run("appearance.assign", json!({"bodies":["Subject"],"color":"#204080"})).unwrap(); + } else { + ribbon::perform_job(&mut h.app, "render.cancel").unwrap(); + assert!(!live::final_pending(&h.app)); + } + h.app.run("view.render_live", json!({"paused":true})).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + live::advance(&mut h.app, &h.ctx, 1.4); + let state = live::inspect(&h.app); + if state["pending"] == false && state["draining"] == 0 && !live::final_pending(&h.app) { + break; + } + assert!(std::time::Instant::now() < deadline, "waiting final did not drain: {state}"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert_eq!(h.app.session.render_job_host().unwrap().admitted_bytes(), 0); + if changed { + assert!(h.app.status.as_ref().is_some_and(|status| status.0 == h.app.tr("render.live.final_changed"))); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn fixed_cpu_live_sampling_is_a_separate_progressive_copy_and_inspection_does_not_launch_it() { + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.primary_samples = 4; + let document = h.app.session.doc.clone(); + let before = setups::draft(&h.app).unwrap(); + let initial = inspect_state(&h.app); + assert_eq!(initial["live"]["pending"], false); + assert_eq!(initial, inspect_state(&h.app), "inspection only reads existing metadata"); + assert_eq!(h.app.session.render_job_host().unwrap().admitted_bytes(), 0); + live::advance(&mut h.app, &h.ctx, 1.0); + let request = live::inspect(&h.app)["request"].clone(); + assert_eq!(request["settings"]["job"]["options"]["progressive"]["samples_per_pixel"], 16); + assert!(request["settings"]["job"]["options"]["primary_samples"].is_null() || request["settings"]["job"]["options"]["primary_samples"] == 1); + assert_eq!(setups::draft(&h.app).unwrap(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn fixed_cpu_live_reflection_attempts_use_the_film_without_changing_final_sampling() { + use solidcraft_engine::render::job::ReflectionMode; + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.primary_samples = 4; + cpu::set_reflection(&mut h.app, "Subject", Some(ReflectionMode::Mirror)).unwrap(); + let reflections = h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap(); + reflections.samples = 4; + reflections.max_bounces = 1; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + live::advance(&mut h.app, &h.ctx, 1.0); + let state = live::inspect(&h.app); + assert!(state["error"].is_null(), "{state}"); + let options = &state["request"]["raytrace"]; + assert_eq!(options["progressive"]["samples_per_pixel"], 16); + assert_eq!(options["reflections"]["samples"], 1); + assert_eq!(options["primary_samples"].as_u64().unwrap_or(1), 1); + let pixels = wait_live_complete(&mut h, 1.3); + assert_eq!(pixels["samples"], 16); + assert!(pixels["hash"].as_str().is_some_and(|hash| !hash.is_empty())); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + assert_eq!(h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().samples, 4); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.session.doc.render.setups.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn new_document_final_keeps_the_old_live_capture_cleanup_barrier() { + let Some(mut h) = live_cpu_fixture() else { return }; + live::advance(&mut h.app, &h.ctx, 1.0); + live::advance(&mut h.app, &h.ctx, 1.3); + assert_eq!(live::inspect(&h.app)["pending"], true); + let host = h.app.session.render_job_host().unwrap().clone(); + h.app.session = Session::default(); + h.app.session.set_render_job_host(Some(host)).unwrap(); + h.app.run("solid.box", json!({"length":4,"width":5,"height":6,"body_name":"New document"})).unwrap(); + reset_document(&mut h.app); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.draft.width = 8; + h.app.render_workspace.view.draft.height = 8; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert!(live::final_pending(&h.app), "reset must retain a late old-document capture until its leases are released"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while h.app.render_workspace.view.job.is_none() { + live::advance(&mut h.app, &h.ctx, 1.4); + assert!(std::time::Instant::now() < deadline, "new-document final did not drain: {}", live::inspect(&h.app)); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(live::inspect(&h.app)["draining"], 0); + let id = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + assert_eq!(handle.status().unwrap().scene_generation, h.app.session.revision); + let _ = handle.cancel(); +} + +#[test] +fn cpu_presentation_saves_reopens_and_reaches_runtime_bindings_with_one_exposure() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{ + OutputOptions, ReflectionOptions, ToneMap, + finishing::{Backdrop, BackdropMode, Finishing}, + photographic::Photographic, + }; + let mut h = Harness::new(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.session.set_render_job_host(None).unwrap(); + h.app.render_workspace.view.name = "CPU presentation".into(); + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 32; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.studio.tone_map = ToneMap::AcesFitted; + h.app.render_workspace.view.studio.finishing = + Finishing { rgb_gain: [1.3, 0.8, 1.1], photographic: Photographic { grain: 0.03, seed: 42, ..Default::default() }, ..Default::default() }; + h.app.render_workspace.view.studio.backdrop_enabled = true; + h.app.render_workspace.view.studio.backdrop = Backdrop { mode: BackdropMode::Radial, ..Default::default() }; + h.app.render_workspace.view.studio.linear_exr = true; + let expected = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &expected.job else { panic!("CPU setup expected") }; + let output = options.output.as_deref().copied().unwrap(); + assert_eq!(output.tone_map, ToneMap::AcesFitted); + assert!(output.linear_exr); + assert!(studio::cpu_output(&h.app.render_workspace.view).is_some()); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.studio = studio::View::default(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["CPU presentation"], expected); + let container = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&container).unwrap(); + assert_eq!(reopened.render.setups["CPU presentation"], expected); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + // An empty temporary reflection block selects the runtime route without a saved body binding. + h.app.render_workspace.view.raytrace.reflections = Some(ReflectionOptions { bodies: Vec::new(), samples: 1, max_bounces: 1 }); + let runtime = image_request(&h.app).unwrap(); + assert_eq!(runtime["integrator"], "raytrace"); + assert_eq!(runtime["raytrace"]["output"], json!(output)); + assert_eq!(runtime["raytrace"]["exposure_ev"], 1.5); + assert_eq!(runtime["settings"]["exposure_ev"], 0.0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.render_workspace.view.raytrace.reflections = None; + // An explicit saved identity object also survives an unedited load/snapshot. + let mut identity = expected; + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut identity.job { + options.output = Some(Box::new(OutputOptions::default())); + } + h.app.run("render.settings.set", json!({"name":"CPU presentation","set":identity})).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), identity); +} + +#[test] +fn first_cpu_effect_edit_preserves_visible_baseline_and_undoes_once() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "First CPU effect".into(); + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 32; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.draft.background = [3, 7, 11]; + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + assert!(!h.app.session.doc.render.setups.contains_key("First CPU effect")); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:bloom-enable"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + let saved = &h.app.session.doc.render.setups["First CPU effect"]; + assert_eq!((saved.width, saved.height, saved.exposure_ev, saved.background), (64, 32, 1.5, [3, 7, 11])); + let Some(RenderJob::CpuRaytrace { options, .. }) = &saved.job else { panic!("CPU output must not select a GPU job") }; + assert!(options.output.as_ref().unwrap().finishing.bloom.is_some()); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!h.app.session.doc.render.setups.contains_key("First CPU effect")); + assert!(h.app.render_workspace.view.job.is_none()); +} + +fn cpu_output_hint_frame(h: &mut Harness, events: Vec) -> String { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 2000.0))), events, ..Default::default() }, + |ui| inspector::output_editor(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + output.textures_delta.clear(); + text +} + +#[test] +fn cpu_alpha_help_and_checkbox_are_available_without_mutating_intent_on_paint() { + let mut h = Harness::new(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let text = cpu_output_hint_frame(&mut h, vec![]); + assert!(text.contains(h.app.tr("render.cpu_transparent_help"))); + assert!(!h.app.render_workspace.view.transparent); + for expected in [true, false] { + let at = crate::scenario::rect_of("render:transparent-background").unwrap().center(); + for pressed in [true, false] { + cpu_output_hint_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert_eq!(h.app.render_workspace.view.transparent, expected, "CPU alpha remains an explicit reversible choice"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn cpu_gradient_backdrop_and_retained_master_controls_preserve_the_cpu_method() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::finishing::{Backdrop, BackdropMode}; + let mut h = Harness::new(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "CPU backdrop".into(); + let gradient = Backdrop { mode: BackdropMode::Radial, ..Default::default() }; + environment::commit_gradient(&mut h.app, true, gradient).unwrap(); + let saved = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &saved.job else { panic!("CPU job expected") }; + assert_eq!(options.output.as_ref().unwrap().backdrop, Some(gradient)); + environment::commit_backdrop(&mut h.app, [21, 37, 55], false).unwrap(); + let cleared = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &cleared.job else { panic!("CPU job expected") }; + assert!(options.output.as_ref().unwrap().backdrop.is_none()); + assert_eq!(cleared.background, [21, 37, 55]); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_cpu_output_ui_capture_keeps_common_effects_and_exports_its_actual_raw_master() { + use solidcraft_engine::render::job::{JobId, Phase}; + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app + .run( + "render.settings.set", + json!({"name":"CPU output capture","set":{"camera":h.app.cam,"width":8,"height":8,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81}, + "output":{"tone_map":"aces_fitted","finishing":{"rgb_gain":[1.2,0.8,1.1],"photographic":{"grain":0.03,"seed":42}, + "bloom":{"strength":0.2,"threshold":0.5,"radius":1}},"backdrop":{"mode":"radial"},"linear_exr":true}}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "CPU output capture".into(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.frames(3); + let checked = image_params(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let job: JobId = h.app.render_workspace.view.job.expect("the real UI Render action must capture the CPU setup"); + let handle = h.app.session.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); + assert!(status.request.raytrace.as_ref().unwrap().output.as_ref().unwrap().linear_exr); + assert_eq!(json!(status.request.raytrace.as_ref().unwrap().output), checked["settings"]["job"]["options"]["output"]); + h.frames(3); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(studio::linear_export_available(&h.app)); + linear_format_choices::choose(&mut h, "render:format-exr"); + assert!(h.app.render_workspace.view.studio.export_exr); + let frame = handle.frame().unwrap().unwrap(); + let path = h.dir.join("actual-cpu-output.exr"); + h.app.session.execute("render.export", &json!({"job":job,"path":path,"format":"exr"})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.linear_exr().unwrap()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn cpu_output_identity_presence_tracks_external_edits_undo_and_local_saved_changes() { + use solidcraft_engine::render::job::OutputOptions; + let mut h = Harness::new(); + let camera = h.app.cam; + h.app + .run("render.settings.set", json!({"name":"CPU identity","set":{"camera":camera,"width":64,"height":32,"job":{"method":"cpu_raytrace"}}})) + .unwrap(); + h.app.render_workspace.view.name = "CPU identity".into(); + setups::load(&mut h.app); + for output in [json!(OutputOptions::default()), serde_json::Value::Null] { + let before = setups::snapshot(&h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"CPU identity","set":{"job":{"method":"cpu_raytrace","options":{"output":output}}}})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), h.app.session.doc.render.setups["CPU identity"]); + assert_eq!(h.app.cam, camera); + assert!(!h.app.render_workspace.view.dirty); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + assert!(!h.app.render_workspace.view.dirty); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), h.app.session.doc.render.setups["CPU identity"]); + } + // A local save must refresh the marker too; subsequent removal is not a local override. + h.app.render_workspace.view.raytrace.output = Some(Box::new(OutputOptions::default())); + h.app.render_workspace.view.studio.finishing.rgb_gain = [1.2, 0.8, 1.1]; + setups::save(&mut h.app).unwrap(); + let before = setups::snapshot(&h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"CPU identity","set":{"job":{"method":"cpu_raytrace","options":{"output":null}}}})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), h.app.session.doc.render.setups["CPU identity"]); + assert!(!h.app.render_workspace.view.dirty); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + assert!(!h.app.render_workspace.view.dirty); +} + +#[test] +fn cpu_gradient_and_colour_edits_preserve_the_saved_shot_camera_and_live_navigation() { + use solidcraft_engine::render::job::finishing::{Backdrop, BackdropMode}; + let mut h = Harness::new(); + let saved_camera = Camera { yaw: 0.2, distance: 80.0, ..Default::default() }; + h.app + .run( + "render.settings.set", + json!({"name":"CPU camera","set":{"camera":saved_camera,"width":64,"height":32,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":3,"seed":81}}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "CPU camera".into(); + setups::load(&mut h.app); + let live_camera = Camera { yaw: 1.3, distance: 120.0, ..saved_camera }; + h.app.cam = live_camera; + let undo = h.app.session.undo.len(); + environment::commit_gradient(&mut h.app, true, Backdrop { mode: BackdropMode::Radial, ..Default::default() }).unwrap(); + let gradient = h.app.session.doc.render.setups["CPU camera"].clone(); + assert_eq!(gradient.camera, saved_camera); + assert_eq!(h.app.cam, live_camera); + assert_eq!((gradient.width, gradient.height, gradient.exposure_ev), (64, 32, 1.5)); + assert_eq!(h.app.session.undo.len(), undo + 1); + environment::commit_backdrop(&mut h.app, [21, 37, 55], false).unwrap(); + assert_eq!(h.app.session.doc.render.setups["CPU camera"].camera, saved_camera); + assert_eq!(h.app.cam, live_camera); + assert_eq!(h.app.session.undo.len(), undo + 2); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["CPU camera"], gradient); + assert_eq!(h.app.cam, live_camera); +} + +#[test] +fn gpu_sample_editor_keeps_exact_requested_pass_count_and_saved_intent() { + for (legacy, entered, expected) in [(false, 17, 17), (false, 31, 31), (true, 17, 32)] { + let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = legacy; + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 32; + h.app.render_workspace.view.samples = 64; + h.app.render_workspace.view.seed = 71; + h.app.render_workspace.view.max_depth = 7; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + setups::save(&mut h.app).unwrap(); + inspector::select_editor(&mut h.app, inspector::Editor::Sampling); + h.frames(3); + if crate::scenario::rect_of("render:gpu-samples").is_none() { + h.step(&json!({"click":{"handle":"dialog:section:Path tracing"}})).unwrap(); + h.frames(3); + } + let field = crate::scenario::rect_of("render:gpu-samples").unwrap(); + let at = egui::pos2(field.right() - 10.0, field.center().y); + h.step(&json!({"click":[at.x,at.y],"double":true})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":entered.to_string()})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.samples, expected, "legacy={legacy}, entered={entered}"); + let request = image_request(&h.app).unwrap(); + let settings = &request["settings"]; + let options = &settings["job"]["options"]; + assert_eq!(options["samples"], expected); + assert_eq!(options["seed"], 71); + assert_eq!(options["max_depth"], 7); + assert_eq!(settings["exposure_ev"], 1.25); + assert_eq!((settings["width"].as_u64(), settings["height"].as_u64()), (Some(64), Some(32))); + assert!(h.app.render_workspace.view.job.is_none(), "editing a pass count does not start a final render"); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.samples, expected); + assert_eq!(image_request(&h.app).unwrap(), request); + } +} + +fn frame_lens_edit_keeps_job_draft_unsaved(method: &str) { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{CpuProgressiveOptions, ThinLens}; + let other_method = if method == "cpu_raytrace" { "gpu_path" } else { "cpu_raytrace" }; + for draft_method in [method, other_method] { + for moved_camera in [false, true] { + let mut h = Harness::new(); + let saved_camera = Camera { fov: 0.7, distance: 20.0, ..Default::default() }; + let options = if method == "cpu_raytrace" { + json!({"progressive":{"samples_per_pixel":8,"seed":81}}) + } else { + json!({"samples":8,"max_depth":4,"seed":81}) + }; + h.app + .run( + "render.settings.set", + json!({"name":"Lens isolation","set":{"width":64,"height":32,"camera":saved_camera, + "job":{"method":method,"options":options}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Lens isolation".into(); + h.app.cam = if moved_camera { Camera { distance: 30.0, roll: 0.3, ..saved_camera } } else { saved_camera }; + setups::load(&mut h.app); + let draft_kind = if draft_method == "cpu_raytrace" { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }; + if draft_method != method { + // The Scene inspector changes the active method without saving it. Opening + // Frame and editing DOF must not commit that separate renderer choice. + select_image_method(&mut h.app, draft_kind); + } + if draft_method == "cpu_raytrace" { + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 93 }); + h.app.render_workspace.view.raytrace.path = Some(serde_json::from_value(json!({"max_depth":3})).unwrap()); + h.app.render_workspace.view.raytrace.lights = Some(Vec::new()); + } else { + h.app.render_workspace.view.samples = 17; + h.app.render_workspace.view.max_depth = 5; + h.app.render_workspace.view.seed = 93; + } + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + 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 saved = before.render.setups["Lens isolation"].clone(); + let mut expected_saved = saved.clone(); + let mut expected_draft = setups::snapshot(&h.app).unwrap(); + assert_ne!(expected_draft.job, saved.job, "the fixture must have an independent unsaved job draft"); + let lens = ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 20.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 must use an image job"), + } + } + shot::set_lens(&mut h.app, "Lens isolation", Some(lens)).unwrap(); + assert!(h.app.render_workspace.view.dirty, "{method} saved/{draft_method} draft: a lens edit must leave unrelated job intent unsaved"); + assert_eq!(h.app.session.doc.render.setups["Lens isolation"], expected_saved, "{method} saved/{draft_method} draft: save only the lens"); + assert_eq!( + setups::draft(&h.app).unwrap(), + expected_draft, + "{method} saved/{draft_method} draft: preserve the independent active job draft" + ); + assert_eq!(h.app.render_workspace.view.method, draft_kind); + assert_eq!(h.app.cam, live_camera); + assert_eq!(h.app.session.doc.render.setups["Lens isolation"].camera, saved_camera); + 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["Lens isolation"], expected_saved); + assert_eq!(h.app.cam, live_camera); + } + } +} + +#[test] +fn cpu_frame_lens_edit_keeps_unrelated_job_draft_unsaved() { + frame_lens_edit_keeps_job_draft_unsaved("cpu_raytrace"); +} + +#[test] +fn gpu_frame_lens_edit_keeps_unrelated_job_draft_unsaved() { + frame_lens_edit_keeps_job_draft_unsaved("gpu_path"); +} + +#[test] +fn cpu_frame_lens_edits_roundtrip_offline_undo_once_and_preserve_saved_and_live_cameras() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::ThinLens; + for legacy in [false, true] { + let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = legacy; + let saved_camera = Camera { fov: 0.7, distance: 20.0, ..Default::default() }; + h.app + .run( + "render.settings.set", + json!({"name":"Focus","set":{"width":64,"height":32,"camera":saved_camera,"exposure_ev":1.5, + "job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":8,"seed":81},"lights":[], + "output":{"tone_map":"aces_fitted","linear_exr":true}}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Focus".into(); + h.app.cam = Camera { distance: 30.0, roll: 0.3, ..saved_camera }; + setups::load(&mut h.app); + let live_camera = h.app.cam; + let before = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let saved = h.app.session.doc.render.setups["Focus"].clone(); + let mut painted = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 2400.0))), ..Default::default() }, + |ui| shot::editor(&mut h.app, ui, "Focus"), + ); + painted.textures_delta.clear(); + assert!(crate::scenario::rect_of("render:shot:dof").is_some(), "CPU uses the existing Frame lens editor"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + let lens = ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 20.0 }; + shot::set_lens(&mut h.app, "Focus", Some(lens)).unwrap(); + assert_eq!(h.app.session.undo.len(), history.0 + 1); + let changed = &h.app.session.doc.render.setups["Focus"]; + assert_eq!(changed.camera, saved_camera); + assert_eq!(h.app.cam, live_camera); + assert_eq!((changed.width, changed.height, changed.exposure_ev), (64, 32, 1.5)); + let RenderJob::CpuRaytrace { options, .. } = changed.job.as_ref().unwrap() else { panic!("CPU method changed") }; + assert_eq!(options.lens, Some(lens)); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 8); + assert!(options.output.as_ref().unwrap().linear_exr); + assert_eq!(options.output.as_ref().unwrap().tone_map, solidcraft_engine::render::job::ToneMap::AcesFitted); + assert_eq!(h.app.render_workspace.view.raytrace.lens, Some(lens)); + let mut runtime = json!({"settings":{"camera":live_camera}}); + cpu::params(&h.app, &mut runtime).unwrap(); + assert_eq!(runtime["raytrace"]["lens"], json!(lens)); + assert_eq!(runtime["settings"]["camera"], json!(live_camera)); + assert_eq!(h.app.session.undo.len(), history.0 + 1, "building a lens request is read-only"); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(&reopened.render.setups["Focus"], changed); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Focus"], saved); + assert!(!h.app.render_workspace.view.studio.lens_enabled); + assert_eq!(h.app.cam, live_camera); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.render_workspace.view.studio.lens_enabled); + assert_eq!(h.app.render_workspace.view.studio.lens, lens); + assert_eq!(h.app.cam, live_camera); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.cam.fov = 0.0; + shot::set_lens(&mut h.app, "Focus", None).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Focus"].camera, saved_camera); + assert_eq!(h.app.cam.fov, 0.0, "removing an active lens never adopts navigation"); + let RenderJob::CpuRaytrace { options, .. } = h.app.session.doc.render.setups["Focus"].job.as_ref().unwrap() else { + panic!("CPU method changed") + }; + assert!(options.lens.is_none()); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 8); + } +} + +#[test] +fn cpu_fixed_lens_intent_requires_explicit_progressive_adoption_and_zero_can_be_removed() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::ThinLens; + let mut h = Harness::new(); + let camera = Camera { fov: 0.7, distance: 20.0, ..Default::default() }; + h.app + .run( + "render.settings.set", + json!({"name":"Fixed","set":{"width":64,"height":32,"camera":camera, + "job":{"method":"cpu_raytrace","options":{"primary_samples":4}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Fixed".into(); + setups::load(&mut h.app); + let before = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let positive = ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 20.0 }; + assert!(shot::set_lens(&mut h.app, "Fixed", Some(positive)).unwrap_err().contains("progressive")); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + let zero = ThinLens { aperture_radius_mm: 0.0, ..positive }; + shot::set_lens(&mut h.app, "Fixed", Some(zero)).unwrap(); + let saved = h.app.session.doc.render.setups["Fixed"].clone(); + let RenderJob::CpuRaytrace { options, .. } = saved.job.as_ref().unwrap() else { panic!("CPU method changed") }; + assert_eq!(options.lens, Some(zero)); + assert!(options.progressive.is_none()); + assert_eq!(options.primary_samples, 4); + h.app.cam.fov = 0.0; + shot::set_lens(&mut h.app, "Fixed", None).unwrap(); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Fixed"], saved); + assert_eq!(h.app.cam.fov, 0.0, "removing a lens never navigates or saves the current camera"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn fresh_cpu_default_frame_perspective_then_first_dof_edit_saves_visible_job_once_offline() { + use egui::{Event, Modifiers, PointerButton}; + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::CpuHost; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("fresh CPU lens default test requires raytrace-cpu"); + return; + } + h.app.preferences.render_legacy_image_defaults = false; + h.app.render_workspace.view.live_paused = true; + let original = h.app.session.doc.clone(); + let original_undo = h.app.session.undo.len(); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 16); + assert!(Arc::ptr_eq(&original, &h.app.session.doc), "opening the fresh CPU route is read-only"); + assert_eq!(h.app.session.undo.len(), original_undo); + assert!(!h.app.session.doc.render.setups.contains_key("Studio")); + let camera = Camera { fov: 0.7, ..h.app.cam }; + shot::set_camera(&mut h.app, "Studio", camera).unwrap(); + assert!(h.app.session.doc.render.setups["Studio"].job.is_none(), "the explicit Perspective edit saves only its camera"); + assert_eq!(h.app.session.undo.len(), original_undo + 1); + let visible = setups::snapshot(&h.app).unwrap(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.session.set_render_job_host(None).unwrap(); + h.app.render_workspace.image_host = None; + h.app.render_workspace.host = None; + assert!(image_host(&h.app, ImageMethod::CpuRaytrace).is_err()); + let paint = |h: &mut Harness, events: Vec| { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 2400.0))), + events, + ..Default::default() + }, + |ui| shot::editor(&mut h.app, ui, "Studio"), + ); + output.textures_delta.clear(); + }; + paint(&mut h, Vec::new()); + paint(&mut h, Vec::new()); + let at = crate::scenario::rect_of("render:shot:dof").unwrap().center(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo, "painting Frame never autosaves the transient CPU job"); + assert!(h.app.render_workspace.view.job.is_none()); + for pressed in [true, false] { + paint( + &mut h, + vec![Event::PointerMoved(at), Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], + ); + } + assert_eq!(h.app.session.undo.len(), undo + 1, "the actual first DOF checkbox click saves one complete numerical job"); + let saved = &h.app.session.doc.render.setups["Studio"]; + assert_eq!(saved.camera, camera); + assert_eq!(h.app.cam, camera); + assert_eq!((saved.width, saved.height, saved.exposure_ev), (visible.width, visible.height, visible.exposure_ev)); + let RenderJob::CpuRaytrace { options, .. } = saved.job.as_ref().unwrap() else { panic!("visible CPU method was not persisted") }; + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.lens, Some(h.app.render_workspace.view.studio.lens)); + assert!(options.lens.unwrap().aperture_radius_mm > 0.0); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + let after = h.app.session.doc.clone(); + paint(&mut h, Vec::new()); + assert!(Arc::ptr_eq(&after, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(*h.app.session.doc, *before); + assert_eq!(h.app.cam, camera); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn clicked_cpu_alpha_saves_reopens_and_exports_exact_straight_png_with_unchanged_raw_master() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{CpuHost, Phase}; + for legacy in [false, true] { + let mut h = Harness::new(); + h.app.preferences.render_legacy_image_defaults = legacy; + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1600,"height":2200})); + let path = h.dir.join("Half.obj"); + std::fs::write(&path, "o Half\nv -4 -4 0\nv 0 -4 0\nv 0 4 0\nv -4 4 0\nf 1 2 3\nf 1 3 4\n").unwrap(); + h.app.run("file.insert_mesh", json!({"path":path})).unwrap(); + let mut camera = Camera { distance: 10.0, ..Default::default() }; + camera.set_view(solidcraft_engine::render::StandardView::Top); + h.app + .run( + "render.settings.set", + json!({"name":"Cutout","set":{"camera":camera,"width":1,"height":1,"background":[255,255,255], + "job":{"method":"cpu_raytrace","options":{"primary_samples":4,"lights":[],"output":{"linear_exr":true}}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Cutout".into(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + inspector::select_editor(&mut h.app, inspector::Editor::Output); + h.frames(3); + let original = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:transparent-background"}})).unwrap(); + assert!(h.app.render_workspace.view.transparent); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(matches!(&h.app.session.doc.render.setups["Cutout"].job, Some(RenderJob::CpuRaytrace { transparent_background: true, .. }))); + assert_eq!(h.app.session.doc.features, original.features); + assert_eq!(h.app.session.doc.materials, original.materials); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(!h.app.render_workspace.view.transparent); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.render_workspace.view.transparent); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + h.app.session.set_render_job_host(Some(host)).unwrap(); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "Cutout".into(); + setups::load(&mut h.app); + enter(&mut h.app, true).unwrap(); + h.frames(3); + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + assert!(h.app.render_workspace.view.transparent); + if !available { + continue; + } + let doc = h.app.session.doc.clone(); + let request = image_request(&h.app).unwrap(); + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + assert_eq!(checked["request"]["transparent_background"], true); + assert_eq!(checked["transparency"], "coverage_alpha"); + let runtime=h.app.session.execute("render.preflight",&json!({"integrator":"raytrace","settings":{"width":1,"height":1,"camera":camera,"background":[255,255,255]},"transparent_background":true,"raytrace":checked["request"]["raytrace"]})).unwrap(); + assert_eq!(checked["request"], runtime["request"]); + h.frames(2); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + let png = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(png.get_pixel(0, 0).0, [0, 0, 0, 128]); + let path = h.dir.join(format!("cpu-cutout-{legacy}.png")); + h.app.session.execute("render.export", &json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + let mut opaque = request["settings"].clone(); + opaque["job"]["transparent_background"] = json!(false); + let started = h.app.session.execute("render.start", &json!({"settings":opaque})).unwrap(); + let opaque_id = serde_json::from_value(started["job"].clone()).unwrap(); + let opaque_handle = h.app.session.render_job_handle(opaque_id).unwrap(); + assert_eq!(opaque_handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap().progress.phase, Phase::Completed); + assert_eq!(opaque_handle.frame().unwrap().unwrap().linear_exr(), frame.linear_exr()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + } +} + +#[test] +fn cpu_denoise_effect_control_saves_once_reopens_offline_and_tracks_undo_without_launch() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.render_workspace.view.live_paused = true; + h.app + .run( + "render.settings.set", + json!({"name":"CPU filter","set":{"camera":h.app.cam,"width":16,"height":8, + "job":{"method":"cpu_raytrace","transparent_background":true,"options":{"progressive":{"samples_per_pixel":3,"seed":81}}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "CPU filter".into(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + h.frames(3); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.render_workspace.view.job.is_none()); + h.step(&json!({"click":{"handle":"render:denoise-enable"}})).unwrap(); + h.frames(3); + let saved = &h.app.session.doc.render.setups["CPU filter"]; + let Some(RenderJob::CpuRaytrace { options, .. }) = &saved.job else { panic!("CPU job expected") }; + assert!(options.denoise); + assert!(h.app.render_workspace.view.transparent); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["transparent_background"], true); + assert_eq!((saved.width, saved.height), (16, 8)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["denoise"], true); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(!h.app.render_workspace.view.studio.denoise); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.render_workspace.view.studio.denoise); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "CPU filter".into(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.studio.denoise); + assert!(h.app.render_workspace.view.raytrace.denoise); + assert!(h.app.render_workspace.view.transparent); + let mut runtime = json!({"settings":{"camera":h.app.cam}}); + cpu::params(&h.app, &mut runtime).unwrap(); + assert_eq!(runtime["raytrace"]["denoise"], true); + assert!(runtime.get("denoise").is_none(), "the CPU filter must not enter the GPU runtime schema"); +} + +#[test] +fn cpu_common_glass_controls_preserve_unsupported_effects_and_all_cpu_options() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + h.app.render_workspace.view.draft.width = 8; + h.app.render_workspace.view.draft.height = 8; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe("starter.glass.amber-tint").unwrap(); + h.app.render_workspace.view.materials.enabled = true; + // Keep the direct ordinal adapter's all-options preservation oracle; the + // subsequent shared controls retain their real stable target. + let mut ordinal = binding.clone(); + ordinal.target.stable_target = None; + h.app.render_workspace.view.materials.bindings = vec![ordinal]; + let mut params = json!({"settings":{"camera":h.app.cam}}); + cpu::params(&h.app, &mut params).unwrap(); + let previous = params["raytrace"].clone(); + materials::params(&h.app, &mut params).unwrap(); + for (key, value) in previous.as_object().unwrap() { + if key != "dielectrics" { + assert_eq!(¶ms["raytrace"][key], value, "shared Glass must preserve CPU {key}"); + } + } + for (coat, maps, scatter, shadows) in + [(true, false, false, false), (false, true, false, false), (false, false, true, false), (false, false, false, true)] + { + let mut unsupported = binding.clone(); + unsupported.glass_enabled = !(coat || maps); + unsupported.coat_enabled = coat; + unsupported.maps_enabled = maps; + if scatter { + unsupported.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + } + unsupported.glass.shadows = shadows; + h.app.render_workspace.view.materials.bindings = vec![unsupported]; + if coat { + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["coats"][0]["coat"], json!({"weight":1.0,"roughness":0.12,"ior":1.5})); + assert_eq!(request["settings"]["job"]["method"], "cpu_raytrace"); + assert_eq!(request["settings"]["exposure_ev"], 1.5); + } else { + assert!(image_request(&h.app).is_err()); + } + let retained = &h.app.render_workspace.view.materials.bindings[0]; + assert_eq!((retained.coat_enabled, retained.maps_enabled, retained.glass.shadows), (coat, maps, shadows)); + assert_eq!(retained.glass.subsurface.is_some(), scatter); + assert_eq!(retained.glass.recipe, binding.glass.recipe); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn clicked_cpu_glass_render_save_reopen_hydrates_and_previews_edits_without_changing_mass() { + cpu_glass_ui_save_reopen_workflow(false); +} +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn clicked_cpu_general_closed_glass_path_render_save_reopen_keeps_geometry_mass_and_reviewed_numbers() { + cpu_glass_ui_save_reopen_workflow(true); +} +#[cfg(not(target_arch = "wasm32"))] +fn cpu_glass_ui_save_reopen_workflow(general: bool) { + use solidcraft_engine::render::job::{CpuHost, Phase}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("CPU Glass UI test requires raytrace-cpu"); + return; + } + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1600,"height":2200})); + if general { + h.app.run("solid.cylinder", json!({"radius":5,"height":3,"body_name":"Optics"})).unwrap(); + } else { + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + } + h.app.run("material.assign", json!({"bodies":["Optics"],"material":"Steel"})).unwrap(); + let physical = h.app.run("component.properties", json!({"component":"root"})).unwrap(); + assert!(physical["total"]["mass_g"].as_f64().unwrap() > 0.0); + let camera = Camera { + target: solidcore_record::Vec3::new(if general { 0.0 } else { 5.0 }, if general { 0.0 } else { 5.0 }, 1.5), + distance: 20.0, + yaw: 0.3, + pitch: 0.4, + fov: 0.5, + ..Default::default() + }; + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"camera":camera,"width":8,"height":8,"background":[255,255,255],"job":{"method":"cpu_raytrace","options":{ + "path":general.then_some(json!({"max_depth":12})),"lights":[],"environment":{"color":[1,1,1],"intensity":1},"progressive":{"samples_per_pixel":3,"seed":81}}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + setups::load(&mut h.app); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Optics".into()}]})).unwrap(); + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.material_custom")})).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:starter.glass.amber-tint"}})).unwrap(); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let temporary = image_request(&h.app).unwrap(); + assert_eq!(temporary["settings"]["optics"][0]["optics"]["boundary"], "closed_mesh"); + if general { + assert_eq!(temporary["settings"]["job"]["options"]["path"]["max_depth"], 12); + } + assert_eq!(temporary["settings"]["optics"][0]["optics"]["ior"], 1.51); + let checked = h.app.session.execute("render.preflight", &temporary).unwrap(); + assert_eq!(checked["request"]["raytrace"]["dielectrics"][0]["boundary"], if general { "closed_mesh" } else { "closed_box" }); + assert_eq!(checked["request"]["raytrace"]["dielectrics"][0]["ior"], 1.51); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let terminal = handle.wait_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(terminal.progress.phase, Phase::Completed, "{:?}", terminal.error); + let png = handle.frame().unwrap().unwrap().png().to_vec(); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + h.frames(2); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.frames(2); + let saved = h.app.tr("render.appearance_editor.saved").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{saved}")}})).unwrap(); + h.step(&json!({"click":{"handle":"render:optics-save"}})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.features, doc.features); + assert_eq!(h.app.session.doc.materials, doc.materials); + assert_eq!(h.app.run("component.properties", json!({"component":"root"})).unwrap(), physical); + assert_eq!(h.app.session.doc.render.setups["Studio"].optics.len(), 1); + let captured = h.app.session.execute("render.preflight", &image_request(&h.app).unwrap()).unwrap(); + assert_eq!(captured["request"], checked["request"]); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + h.app.session.set_render_job_host(Some(host)).unwrap(); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + setups::load(&mut h.app); + enter(&mut h.app, true).unwrap(); + h.frames(3); + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Optics".into()}]})).unwrap(); + let reopened_doc = h.app.session.doc.clone(); + h.frames(3); + assert!(Arc::ptr_eq(&reopened_doc, &h.app.session.doc)); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "hydrated saved controls are not a temporary override on paint"); + if crate::scenario::rect_of("render:glass:ior-field").is_none() { + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + } + h.frames(2); + assert!(h.widget("1.51").is_some(), "the Glass IOR field displays the saved numerical value"); + let same = h.app.session.execute("render.preflight", &image_request(&h.app).unwrap()).unwrap(); + assert_eq!(same["request"], checked["request"]); + let result = h.app.session.execute("render.start", &image_request(&h.app).unwrap()).unwrap(); + let id = serde_json::from_value(result["job"].clone()).unwrap(); + let complete = h.app.session.render_job_handle(id).unwrap(); + assert_eq!(complete.wait_timeout(std::time::Duration::from_secs(10)).unwrap().progress.phase, Phase::Completed); + assert_eq!(complete.frame().unwrap().unwrap().png(), png); + let field = crate::scenario::rect_of("render:glass:ior-field").unwrap().center(); + h.step(&json!({"click":[field.x,field.y],"double":true})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"1.6"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(2); + let prospective = image_request(&h.app).unwrap(); + assert_eq!(prospective["settings"]["optics"][0]["optics"]["ior"], 1.6, "ordinary image/live capture sees the edited saved binding immediately"); + assert_eq!(h.app.session.doc.render.setups["Studio"].optics.iter().next().unwrap().optics.ior, 1.51); + assert!(Arc::ptr_eq(&reopened_doc, &h.app.session.doc)); + h.app.session.execute("render.preflight", &prospective).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:enable"}})).unwrap(); + assert!( + image_request(&h.app).unwrap()["settings"]["optics"].as_array().is_none_or(Vec::is_empty), + "disabling saved Glass removes only its prospective row" + ); + assert_eq!(h.app.session.doc.render.setups["Studio"].optics.len(), 1); + h.frames(1); + if crate::scenario::rect_of("render:optics-discard-edit").is_none() { + h.step(&json!({"click":{"handle":format!("dialog:section:{saved}")}})).unwrap(); + } + h.step(&json!({"click":{"handle":"render:optics-discard-edit"}})).unwrap(); + h.frames(2); + assert_eq!(image_request(&h.app).unwrap()["settings"]["optics"][0]["optics"]["ior"], 1.51); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + assert!(Arc::ptr_eq(&reopened_doc, &h.app.session.doc)); +} + +#[test] +fn saved_glass_prospective_overlay_keeps_other_targets_and_refuses_stale_sources() { + let mut h = Harness::new(); + for (name, corner) in [("First", [0, 0, 0]), ("Second", [20, 0, 0])] { + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":name,"corner":corner,"operation":"new"})).unwrap(); + } + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":8,"height":8,"job":{"method":"cpu_raytrace"}}})).unwrap(); + for (index, name, ior) in [(0, "First", 1.4), (1, "Second", 1.6)] { + h.app + .run( + "render.optics.bind", + json!({"name":"Studio","body_index":index,"body_name":name,"expected_revision":h.app.session.revision,"optics":{"ior":ior}}), + ) + .unwrap(); + } + setups::load(&mut h.app); + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + let first = h.app.render_workspace.view.draft.optics.iter().find(|value| target.stable_target.as_ref() == Some(&value.target)).unwrap().clone(); + let second = h.app.render_workspace.view.draft.optics.iter().find(|value| value.target != first.target).unwrap().clone(); + let mut binding = materials::Binding::from_saved(target, &h.app, first.optics); + binding.glass.ior = 1.7; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings = vec![binding]; + let doc = h.app.session.doc.clone(); + let candidate: RenderSetup = serde_json::from_value(image_request(&h.app).unwrap()["settings"].clone()).unwrap(); + assert_eq!(candidate.optics.len(), 2); + assert_eq!(candidate.optics.iter().find(|value| value.target == first.target).unwrap().optics.ior, 1.7); + assert_eq!(candidate.optics.iter().find(|value| value.target == second.target).unwrap(), &second); + assert!(setups::snapshot(&h.app).is_err(), "an ordinary shot save cannot quietly persist the old saved optical values"); + h.app.render_workspace.view.materials.bindings[0].glass_enabled = false; + let off: RenderSetup = serde_json::from_value(image_request(&h.app).unwrap()["settings"].clone()).unwrap(); + assert_eq!(off.optics.iter().collect::>(), vec![&second]); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1,"corner":[50,0,0],"operation":"new"})).unwrap(); + assert!(image_request(&h.app).is_err(), "a stale pending edit must be reviewed rather than attached to the next body"); + assert!(!h.app.render_workspace.view.materials.bindings[0].glass_enabled, "refusal retains the exact prospective draft"); +} + +#[test] +fn saved_zero_thickness_glass_hydration_never_creates_a_prospective_edit_on_paint() { + for method in ["cpu_raytrace", "gpu_path"] { + let mut h = Harness::new(); + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1600,"height":2200})); + let path = h.dir.join("ZeroSheet.obj"); + std::fs::write(&path, "o ZeroSheet\nv -10 -10 0\nv 10 -10 0\nv 10 10 0\nv -10 10 0\nf 1 2 3\nf 1 3 4\n").unwrap(); + h.app.run("file.insert_mesh", json!({"path":path})).unwrap(); + let body = h.app.run("render.scene", json!({})).unwrap()["bodies"][0]["name"].as_str().unwrap().to_owned(); + let mut camera = Camera { distance: 10.0, ..Default::default() }; + camera.set_view(solidcraft_engine::render::StandardView::Top); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":camera,"width":8,"height":8,"job":{"method":method}}})).unwrap(); + h.app + .run( + "render.optics.bind", + json!({"name":"Studio","body_index":0,"body_name":body,"expected_revision":h.app.session.revision, + "optics":{"boundary":"thin_sheet","thickness_mm":0.0,"ior":1.51,"absorption_per_mm":[0.1,0.2,0.0],"shadow_transmission":false}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + setups::load(&mut h.app); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:body}]})).unwrap(); + h.frames(2); + let before = image_request(&h.app).unwrap(); + assert_eq!(before["settings"]["optics"][0]["optics"]["thickness_mm"], 0.0); + let document = 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()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:glass:thickness-field").is_some(), "the actual hydrated thickness editor was painted"); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "valid zero thickness is not an unsaved optical edit: {method}"); + assert_eq!(image_request(&h.app).unwrap(), before, "painting the opened Glass section preserves exact captured intent: {method}"); + assert!(Arc::ptr_eq(&document, &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!(h.app.render_workspace.view.job.is_none()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cold_saved_cpu_lens_hydrates_its_camera_and_render_reentry_preserves_the_dirty_render_view() { + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, ThinLens}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("native CPU lens hydration test requires raytrace-cpu"); + return; + } + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Subject"})).unwrap(); + let saved_camera = Camera { fov: 35f64.to_radians(), distance: 168.6, target: solidcore_record::Vec3::new(5.0, 10.0, 2.5), ..Default::default() }; + let lens = ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 168.6 }; + let progressive = CpuProgressiveOptions { samples_per_pixel: 3, seed: 81 }; + h.app + .run( + "render.settings.set", + json!({"name":"Lens","set":{"camera":saved_camera,"width":8,"height":8, + "job":{"method":"cpu_raytrace","options":{"lens":lens,"progressive":progressive}}}}), + ) + .unwrap(); + let design = (*h.app.session.doc).clone(); + let reopened = solidcraft_engine::doc::Document::from_json(&design.to_json()).unwrap(); + crate::documents::open_tab(&mut h.app, Session::opened(reopened, None)).unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.render_workspace.view.name = "Lens".into(); + h.app.cancel_view_animation(); + h.app.cam = Camera { distance: 211.0, target: solidcore_record::Vec3::new(-12.0, 7.0, 9.0), ..Default::default() }; + h.app.ui.perspective = false; + let original_design_camera = h.app.cam; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.cam, saved_camera); + assert!(h.app.ui.perspective); + assert!(h.app.pending_fit.is_none() && h.app.render_workspace.entry_fit.is_none()); + assert_eq!(setups::snapshot(&h.app).unwrap(), document.render.setups["Lens"]); + assert!(!h.app.render_workspace.view.dirty); + h.app.viewport.rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(8.0, 8.0))); + live::advance(&mut h.app, &h.ctx, 1.0); + let completed = wait_live_complete(&mut h, 1.3); + assert!(completed["error"].is_null()); + assert_eq!(completed["request"]["settings"]["camera"], json!(saved_camera)); + assert_eq!(completed["request"]["settings"]["job"]["options"]["lens"], json!(lens)); + assert!(completed["hash"].as_str().is_some_and(|hash| !hash.is_empty())); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + + h.app.cam.yaw += 0.3; + h.app.render_workspace.view.draft.width = 7; + setups::refresh_dirty(&mut h.app); + let render_camera = h.app.cam; + assert!(h.app.render_workspace.view.dirty); + enter(&mut h.app, false).unwrap(); + assert_eq!(h.app.cam, original_design_camera); + assert!(!h.app.ui.perspective); + let changed_design = Camera { yaw: 0.4, distance: 250.0, ..original_design_camera }; + h.app.cam = changed_design; + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.cam, render_camera); + assert!(h.app.ui.perspective); + assert_eq!(h.app.render_workspace.view.draft.width, 7); + assert!(h.app.render_workspace.view.dirty); + assert!(h.app.pending_fit.is_none()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["camera"], json!(render_camera)); + enter(&mut h.app, false).unwrap(); + assert_eq!(h.app.cam, changed_design); + assert!(!h.app.ui.perspective); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(!h.app.session.is_dirty()); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.render_camera.is_none(), "new documents cannot inherit a retired Render camera"); +} + +#[test] +fn legacy_entry_keeps_the_previous_fit_and_does_not_remember_a_render_camera() { + let mut h = cold_render_entry_fixture(); + h.app.preferences.render_legacy_image_defaults = true; + let design = h.app.cam; + enter(&mut h.app, true).unwrap(); + assert!(h.app.pending_fit.is_some()); + h.frames(4); + let render_camera = h.app.cam; + assert_ne!(render_camera, h.app.session.doc.render.setups["Studio"].camera); + enter(&mut h.app, false).unwrap(); + assert_eq!(h.app.cam, design); + assert!(h.app.render_workspace.view.render_camera.is_none()); +} + +#[test] +fn live_source_labels_use_captured_executor_names_instead_of_the_selected_method() { + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + for (executor, key) in [("cpu-raytrace", "render.method_cpu"), ("gpu-path", "render.method_gpu")] { + for current in [true, false] { + let expected = + crate::i18n::format(if current { "render.live.source_current" } else { "render.live.source_outdated" }, &[("method", h.app.tr(key))]); + assert_eq!(live::source_text(&h.app, executor, current), expected); + } + } + let expected = crate::i18n::format("render.live.source_outdated", &[("method", "test-image-executor")]); + assert_eq!(live::source_text(&h.app, "test-image-executor", false), expected, "unrecognised captures cannot claim CPU or GPU transport"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn live_source_badge_follows_real_pixels_and_its_settings_gear_opens_output_without_editing() { + fn draw(h: &mut Harness, events: Vec, width: f32) -> Vec { + crate::scenario::clear_handles(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, crate::ui_kit::StageBar::HEIGHT)); + let mut output = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect.expand(20.0)), events, ..Default::default() }, |ui| { + crate::render_ui::stage_bar(&mut h.app, ui, rect) + }); + output.textures_delta.clear(); + output.shapes + } + let Some(mut h) = live_cpu_fixture() else { return }; + live::advance(&mut h.app, &h.ctx, 1.0); + wait_live_complete(&mut h, 1.3); + let current = crate::i18n::format("render.live.source_current", &[("method", h.app.tr("render.method_cpu"))]); + assert_eq!(live::source_note(&h.app), (current.clone(), "render.live.quality_help")); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let settings = setups::draft(&h.app).unwrap(); + let shapes = draw(&mut h, vec![], 1440.0); + assert!(shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == current))); + assert!( + !shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == h.app.tr("render.stage_preview_note"))) + ); + let gear = crate::scenario::rect_of("render:preview:settings").unwrap(); + assert!(crate::scenario::rect_of("render:stage_tools").unwrap().contains_rect(gear)); + for pressed in [true, false] { + draw( + &mut h, + vec![ + egui::Event::PointerMoved(gear.center()), + egui::Event::PointerButton { pos: gear.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + 1440.0, + ); + } + assert_eq!(inspector::selected_editor(&h.app), inspector::Editor::Output); + assert_eq!(h.app.cam, camera); + assert_eq!(setups::draft(&h.app).unwrap(), settings); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + + for width in [1100.0, 800.0] { + for stale in [false, true] { + h.app.cam = camera; + if stale { + h.app.cam.yaw += 0.2; + } + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + draw(&mut h, vec![], width); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + let bar = crate::scenario::rect_of("render:stage_bar").unwrap(); + let gear = crate::scenario::rect_of("render:preview:settings").unwrap(); + assert!(gear.is_positive() && tools.contains_rect(gear) && bar.contains_rect(gear), "{width}/{stale}: gear {gear:?} outside {tools:?}"); + for pressed in [true, false] { + draw( + &mut h, + vec![ + egui::Event::PointerMoved(gear.center()), + egui::Event::PointerButton { + pos: gear.center(), + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }, + ], + width, + ); + } + assert_eq!(inspector::selected_editor(&h.app), inspector::Editor::Output); + assert!(h.app.render_workspace.view.job.is_none()); + } + } + h.app.cam = camera; + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + + // A method change before the next lifecycle tick cannot rename an existing CPU image. + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let previous = crate::i18n::format("render.live.source_outdated", &[("method", h.app.tr("render.method_cpu"))]); + assert_eq!(live::source_note(&h.app), (previous.clone(), "render.live.source_outdated_help")); + live::advance(&mut h.app, &h.ctx, 2.0); + assert_eq!(live::source_note(&h.app), (previous, "render.live.source_outdated_help"), "a refused update retains the captured source name"); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert_eq!(live::source_note(&h.app), (h.app.tr("render.stage_preview_note").to_string(), "render.preview_lighting_help")); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.preferences.render_legacy_image_defaults = true; + assert_eq!(live::source_note(&h.app), (h.app.tr("render.stage_preview_note").to_string(), "render.preview_lighting_help")); + h.app.preferences.render_legacy_image_defaults = false; + h.app.render_workspace.view.result = true; + draw(&mut h, vec![], 1440.0); + assert!(crate::scenario::rect_of("render:preview_note").is_none(), "the result viewer has its own captured-image information"); + assert!(crate::scenario::rect_of("render:preview:settings").is_none()); +} + +#[test] +fn result_fit_and_header_actions_stay_inside_the_free_canvas_with_long_retained_shot_names() { + use solidcraft_engine::render::job::{JobId, Phase}; + for side in ["left", "right"] { + for dpi in [1.0, 2.0] { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1100,"height":760})); + h.ctx.set_pixels_per_point(dpi); + h.app.run("view.render_dock", json!({"panel":"inspector","side":side})).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + let mut jobs = Vec::new(); + for (name, background) in [ + ("CPU lens acceptance with a long captured shot name for the retained image", [20, 40, 60]), + ("GPU lens acceptance with a second long captured shot name for the result", [90, 70, 50]), + ] { + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":96,"height":54,"background":background}})).unwrap(); + let job: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + for _ in 0..100 { + host.pump(16384).unwrap(); + if h.app.session.render_job_handle(job).unwrap().status().unwrap().progress.phase == Phase::Completed { + break; + } + } + assert_eq!(h.app.session.render_job_handle(job).unwrap().status().unwrap().progress.phase, Phase::Completed); + h.app.session.label_render_job(job, name).unwrap(); + jobs.push(job); + } + h.app.run("render.result.select", json!({"index":1})).unwrap(); + h.app.run("render.result.view", json!({"view":"fit"})).unwrap(); + h.frames(6); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let frame = h.app.session.render_job_handle(jobs[1]).unwrap().frame().unwrap().unwrap(); + let free = h.app.shell.content.unwrap(); + let canvas = h.app.viewport.rect.unwrap(); + assert!(free.contains_rect(canvas), "{side}/{dpi}: canvas {canvas:?} escaped original free {free:?}"); + let fitted = result_rect(h.app.render_workspace.view.result_camera, [96, 54], canvas); + assert!(canvas.contains_rect(fitted), "{side}/{dpi}: fitted image {fitted:?} escapes canvas {canvas:?}"); + assert!(free.contains_rect(fitted)); + for target in [ + "render:compare:live", + "render:compare:result:0", + "render:compare:result:1", + "render:results", + "render:result-discard", + "render:result:view:model", + "render:result:view:fit", + "render:result:view:actual", + "render:result-copy", + "render:result-export", + "render:result-close", + ] { + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(rect.is_positive() && free.contains_rect(rect), "{side}/{dpi}: header {target} {rect:?} is covered outside {free:?}"); + } + // The actual popup must offer the retained source inside the same free + // canvas, and pointer selection must use that source before discarding. + for index in [0, 1] { + h.step(&json!({"click":{"handle":"render:results"}})).unwrap(); + h.frames(2); + for option in [0, 1] { + let rect = crate::scenario::rect_of(&format!("render:result:select:{option}")).unwrap(); + assert!(rect.is_positive() && free.contains_rect(rect), "{side}/{dpi}: popup source{option} {rect:?} escapes {free:?}"); + } + h.step(&json!({"click":{"handle":format!("render:result:select:{index}")}})).unwrap(); + h.frames(2); + assert_eq!(h.app.session.render_selected_result(), Some(jobs[index])); + assert_eq!(h.app.render_workspace.view.completed, Some(jobs[index])); + } + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance *= 0.5; + h.frames(2); + h.step(&json!({"click":{"handle":"render:result:view:fit"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Fit); + let canvas = h.app.viewport.rect.unwrap(); + assert!(h.app.shell.content.unwrap().contains_rect(result_rect(h.app.render_workspace.view.result_camera, [96, 54], canvas))); + let path = h.dir.join("bounded-result.png"); + h.app.session.execute("render.export", &json!({"job":jobs[1],"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert_eq!(h.app.session.render_selected_result(), Some(jobs[1])); + } + } +} + +#[test] +fn cpu_path_checkbox_adopts_visible_sampling_in_one_undo_and_reopens_offline() { + use solidcraft_engine::doc::render_settings::RenderJob; + for legacy in [false, true] { + let mut h = sampling_policy_fixture(false); + h.app.preferences.render_legacy_image_defaults = legacy; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let before = setups::draft(&h.app).unwrap(); + h.frames(3); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + h.step(&json!({"click":{"handle":"render:cpu-path"}})).unwrap(); + h.frames(3); + let saved = &h.app.session.doc.render.setups[&h.app.render_workspace.view.name]; + assert_eq!((saved.width, saved.height, saved.exposure_ev), (before.width, before.height, before.exposure_ev)); + let Some(RenderJob::CpuRaytrace { options, .. }) = &saved.job else { panic!("explicit CPU path edit must keep CPU") }; + assert_eq!(options.path, Some(Default::default())); + assert_eq!( + options.progressive, + before.job.as_ref().and_then(|job| match job { + RenderJob::CpuRaytrace { options, .. } => options.progressive, + _ => None, + }) + ); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.job.is_none()); + let bytes = serde_json::to_vec(&*h.app.session.doc).unwrap(); + let reopened: solidcraft_engine::doc::Document = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(reopened, *h.app.session.doc); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.render_workspace.view.raytrace.path.is_some()); + h.app.render_workspace.view.raytrace.path = None; + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.raytrace.path.is_some()); + } +} +#[test] +fn cpu_path_adoption_keeps_fixed_and_selected_optical_intent_when_unsupported() { + use solidcraft_engine::render::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; + let mut h = sampling_policy_fixture(true); + let document = h.app.session.doc.clone(); + let options = h.app.render_workspace.view.raytrace.clone(); + h.step(&json!({"click":{"handle":"render:cpu-path"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.raytrace, options); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + let mut h = sampling_policy_fixture(false); + let reflection = ReflectionOptions { + bodies: vec![ReflectionBody { body: "Kept reflector".into(), mode: ReflectionMode::Mirror }], + samples: 1, + max_bounces: 2, + }; + h.app.render_workspace.view.raytrace.reflections = Some(reflection.clone()); + h.frames(2); + let document = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:cpu-path"}})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, Some(reflection)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn inspector_focus_never_changes_the_saved_output_camera_live_aspect_or_normalized_picking_frame() { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ThinLens}; + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.preferences.render_legacy_image_defaults = false; + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1100,"height":760})); + h.frames(5); + let camera = Camera { fov: 35f64.to_radians(), distance: 168.6, target: solidcore_record::Vec3::new(5.0, 10.0, 2.5), ..h.app.cam }; + let lens = ThinLens { aperture_radius_mm: 1.0, focus_distance_mm: 168.6 }; + h.app + .run( + "render.settings.set", + json!({"name":"Framing","set":{"camera":camera,"width":160,"height":120, + "job":{"method":"cpu_raytrace","options":{"lens":lens,"progressive":CpuProgressiveOptions { samples_per_pixel:3,seed:81 }}}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Framing".into(); + setups::load(&mut h.app); + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + setups::refresh_dirty(&mut h.app); + h.app.run("view.render_frame", json!({"aspect":"16:9","thirds":true})).unwrap(); + select_stage(&mut h.app, "look"); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let dirty = h.app.render_workspace.view.dirty; + let output = setups::draft(&h.app).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + for side in ["left", "right"] { + for dpi in [1.0, 2.0] { + for [width, height] in [[1100, 760], [1440, 1600]] { + h.ctx.set_pixels_per_point(dpi); + h.call("ui.resize", json!({"width":width,"height":height})); + h.app.run("view.render_dock", json!({"panel":"inspector","side":side})).unwrap(); + for kind in ["shot", "sampling", "effects", "output"] { + let selection = if kind == "shot" { json!({"kind":kind,"id":"Framing"}) } else { json!({"kind":kind}) }; + h.app.run("view.render_select", selection).unwrap(); + h.frames(4); + live::advance(&mut h.app, &h.ctx, 200.0); + let state = live::inspect(&h.app); + let request = &state["request"]; + let w = request["settings"]["width"].as_u64().unwrap(); + let hpx = request["settings"]["height"].as_u64().unwrap(); + // This is the original 1073 native failure oracle, independent of any + // new frame helper/handle: Sampling yielded 471×512 for 160×120 output. + assert_eq!(w * 120, hpx * 160, "{side}/{dpi}/{width}x{height}/{kind}: live {w}x{hpx} changed authored 4:3 framing: {state}"); + assert!(w > 0 && hpx > 0 && w <= 512 && hpx <= 512); + assert_eq!(request["settings"]["camera"], json!(camera)); + assert_eq!(request["settings"]["job"]["options"]["lens"], json!(lens)); + let viewport = h.app.viewport.rect.unwrap(); + let frame = crate::scenario::rect_of("render:product:frame").unwrap(); + let free = crate::shell::workspace_content(&h.app, crate::render_ui::canvas(&h.app, viewport)); + assert!(frame.is_positive() && free.contains_rect(frame), "{kind}: rendered frame must fit the actual unobscured canvas"); + assert!((f64::from(frame.width() / frame.height()) - w as f64 / hpx as f64).abs() < 1e-5); + let projection = crate::viewport::projection(&h.app, frame); + for point in corners(&scene.bounds) { + let actual = projection.to_screen(point).unwrap(); + let normalized = (actual - frame.min) / frame.size(); + let (x, y, _) = camera.to_screen(point, 160.0, 120.0, radius).unwrap(); + assert!( + (f64::from(normalized.x) - x / 160.0).abs() < 1e-5 && (f64::from(normalized.y) - y / 120.0).abs() < 1e-5, + "{side}/{dpi}/{width}x{height}/{kind}: normalized pick projection changed for {point:?}" + ); + } + assert_eq!(shot::overlay_visible(&h.app), kind == "shot"); + assert_eq!(crate::scenario::rect_of("render:frame:overlay").is_some(), kind == "shot"); + if kind == "shot" { + let guide = shot::preview_rect(&h.app, viewport).unwrap(); + assert!( + (guide.width() / guide.height() - 16.0 / 9.0).abs() < 1e-5, + "the transient guide aspect remains contextual and independent" + ); + } + assert_eq!(h.app.cam, camera); + assert_eq!(setups::draft(&h.app).unwrap(), output); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } + } + } + } +} + +#[test] +fn rendered_output_frame_ignores_transient_guides_but_legacy_keeps_its_contextual_projection() { + let mut h = frame_editor_fixture(); + h.app.render_workspace.view.live_paused = true; + h.app.preferences.render_legacy_image_defaults = false; + h.app.render_workspace.view.draft.width = 160; + h.app.render_workspace.view.draft.height = 120; + select_stage(&mut h.app, "look"); + let viewport = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(1100.0, 760.0)); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + for aspect in ["16:9", "1:1", "9:16"] { + h.app.run("view.render_frame", json!({"aspect":aspect,"thirds":true,"safe_area":true})).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + let frame = shot::render_rect(&h.app, viewport); + assert!((frame.width() / frame.height() - 4.0 / 3.0).abs() < 1e-5); + let guide = shot::preview_rect(&h.app, viewport).unwrap(); + assert_ne!(frame, guide); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + assert!(!shot::overlay_visible(&h.app)); + assert_eq!(shot::render_rect(&h.app, viewport), frame); + h.app.preferences.render_legacy_image_defaults = true; + assert_eq!(shot::render_rect(&h.app, viewport), viewport); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + assert_eq!(shot::render_rect(&h.app, viewport), shot::preview_rect(&h.app, viewport).unwrap()); + h.app.preferences.render_legacy_image_defaults = false; + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn live_framing_rounds_unrepresentable_coprime_sizes_within_the_same_ceiling_and_refuses_invalid_authored_size() { + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.draft.width = 997; + h.app.render_workspace.view.draft.height = 563; + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().samples_per_pixel = 3; + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + for dimensions in [egui::vec2(1100.0, 760.0), egui::vec2(1440.0, 1600.0)] { + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, dimensions); + h.app.viewport.rect = Some(viewport); + live::advance(&mut h.app, &h.ctx, 300.0); + let state = live::inspect(&h.app); + let width = state["request"]["settings"]["width"].as_u64().unwrap(); + let height = state["request"]["settings"]["height"].as_u64().unwrap(); + assert!(width > 0 && height > 0 && width <= 512 && height <= 512); + assert!((width * 563).abs_diff(height * 997) <= 997, "nearest-pixel fallback must remain within one source-aspect pixel: {state}"); + let frame = live::projection_rect(&h.app, shot::render_rect(&h.app, viewport)); + assert!((f64::from(frame.width() / frame.height()) - width as f64 / height as f64).abs() < 1e-5); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (997, 563)); + } + for [width, height] in [[0, 120], [160, 0], [u32::MAX, 120], [160, u32::MAX]] { + h.app.render_workspace.view.draft.width = width; + h.app.render_workspace.view.draft.height = height; + live::advance(&mut h.app, &h.ctx, 301.0); + let state = live::inspect(&h.app); + assert!(state["request"]["error"].as_str().is_some(), "a small live copy cannot make invalid output {width}x{height} valid: {state}"); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (width, height)); + assert_eq!(state["pending"], false); + assert_eq!(state["running"], false); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); +} + +#[test] +fn cpu_aging_saved_and_runtime_requests_retain_the_same_stack_camera_and_other_effect_intent() { + use solidcraft_engine::render::job::aging::{AgingKind, AgingLayer}; + let mut h = Harness::new(); + h.app.render_workspace.view.live_paused = true; + h.app.preferences.render_legacy_image_defaults = false; + h.app.run("solid.box", json!({"body_name":"Aged body","length":10,"width":10,"height":2})).unwrap(); + h.app.run("render.settings.set", json!({"name":"CPU aging","set":{"width":8,"height":8,"camera":h.app.cam, + "job":{"method":"cpu_raytrace","transparent_background":true,"options":{"progressive":{"samples_per_pixel":3,"seed":81},"denoise":true,"path":{"max_depth":2},"output":{"linear_exr":true}}}}})).unwrap(); + h.app.render_workspace.view.name = "CPU aging".into(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + setups::load(&mut h.app); + let targets = materials::read_targets(&mut h.app).unwrap(); + let identity = targets.iter().find(|target| target.name == "Aged body").unwrap().stable_target.clone().unwrap(); + h.app.render_workspace.view.studio.aging.push(AgingLayer::preset(AgingKind::Dust)).unwrap(); + h.app.render_workspace.view.studio.aging.get_mut(0).unwrap().target = Some(identity.clone()); + let camera = h.app.cam; + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + setups::save(&mut h.app).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.features, before.features); + assert_eq!(h.app.session.doc.materials, before.materials); + let expected = image_request(&h.app).unwrap(); + assert_eq!(expected["settings"]["job"]["options"]["aging"][0]["target"]["definition"], "Aged body"); + assert!(expected["settings"]["job"]["options"]["aging"][0]["target"].get("body_index").is_none()); + assert_eq!(expected["settings"]["job"]["options"]["path"]["max_depth"], 2); + assert_eq!(expected["settings"]["job"]["options"]["denoise"], true); + assert_eq!(expected["settings"]["job"]["transparent_background"], true); + assert_eq!(expected["settings"]["job"]["options"]["output"]["linear_exr"], true); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "CPU aging".into(); + setups::load(&mut h.app); + assert_eq!(h.app.cam, camera, "numeric reload never navigates the camera"); + assert_eq!(image_request(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.studio.aging.get(0).unwrap().target.as_ref(), Some(&identity)); + // A temporary reflection binding forces the runtime route. The stable aging + // intent must travel beside it, rather than being lost with the typed job. + h.app.render_workspace.view.raytrace.path = None; + h.app.session.execute("render.scene", &json!({})).unwrap(); + cpu::set_reflection(&mut h.app, "Aged body", Some(solidcraft_engine::render::job::ReflectionMode::RoughSpecular)).unwrap(); + let runtime = image_request(&h.app).unwrap(); + assert_eq!(runtime["aging"], expected["settings"]["job"]["options"]["aging"]); + assert_eq!(runtime["raytrace"]["denoise"], true); + assert_eq!(runtime["transparent_background"], true); + assert_eq!(runtime["raytrace"]["output"]["linear_exr"], true); + assert!(runtime["settings"].get("job").is_none_or(serde_json::Value::is_null)); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.job.is_none()); +} + +// Dropdown IDs are egui state salts, not scenario handles. Find the actual +// current visible Add Light control inside the selected lighting editor. +fn click_gpu_light_add(h: &mut Harness, kind: &str) { + h.frames(3); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); + assert_eq!(inspector::selected_editor(&h.app), inspector::Editor::Lighting); + let editor = crate::scenario::rect_of("render:lighting:editor").unwrap(); + fn painted_label(shape: &egui::Shape, clip: egui::Rect, control: egui::Rect, label: &str) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.text() == label && clip.contains(text.pos) && control.contains(text.pos), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| painted_label(shape, clip, control, label)), + _ => false, + } + } + let label = h.app.tr("render.tree_add_light").to_string(); + let tree = h.output.accesskit_update.as_ref().unwrap(); + let controls: Vec<_> = tree + .nodes + .iter() + .filter(|(_, node)| node.role() == egui::accesskit::Role::ComboBox && !node.is_disabled()) + .filter_map(|(_, node)| node.bounds()) + .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + .filter(|rect| { + editor.contains(rect.center()) + && h.ctx.content_rect().contains_rect(*rect) + && h.shapes.iter().any(|shape| painted_label(&shape.shape, shape.clip_rect, *rect, &label)) + }) + .collect(); + assert_eq!(controls.len(), 1, "one current fully visible Add Light dropdown inside the lighting editor"); + let point = controls[0].center(); + h.step(&json!({"click":[point.x,point.y]})).unwrap(); + h.frames(2); + let target = format!("render:lighting:add:{kind}"); + let row = crate::scenario::rect_of(&target).unwrap(); + assert!(h.ctx.content_rect().contains_rect(row), "the fresh popup row is fully visible"); + h.step(&json!({"click":{"handle":target}})).unwrap(); +} + +// These portable GPU requests carry lighting in the typed saved-job contract. +// Do not accept a missing top-level runtime field as a numeric light value. +fn gpu_lighting_request(request: &serde_json::Value) -> &serde_json::Value { + assert!(request.get("lighting").is_none()); + assert!(request.get("progressive").is_none()); + assert_eq!(request["settings"]["job"]["method"], "gpu_path"); + let lighting = &request["settings"]["job"]["options"]["lighting"]; + assert!(lighting.is_object()); + lighting +} + +fn edit_gpu_light_number(h: &mut Harness, key: &str, text: &str) { + h.frames(3); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert!(matches!(h.app.render_workspace.view.selection, RenderSelection::Light(_))); + let target = format!("render:light:{key}"); + let field = crate::scenario::rect_of(&target).unwrap(); + assert!(h.ctx.content_rect().contains_rect(field), "edit only a current fully visible numeric control: {key}"); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":target},"double":true})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":text})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.undo.len(), undo + 1, "one authored edit for {key}"); +} + +#[test] +fn gpu_hard_directional_controls_materialize_three_defaults_and_keep_sun_separate() { + use solidcraft_engine::schema::render_lights::Geometry; + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + let camera = h.app.cam; + let initial = light::rows(&h.app).unwrap(); + assert_eq!(initial.len(), 3); + assert!(initial.iter().all(|l| l.implicit)); + h.app.run("view.render_select", json!({"kind":"light","id":"directional:1"})).unwrap(); + let original = h.app.session.doc.clone(); + h.frames(3); + assert!(Arc::ptr_eq(&original, &h.app.session.doc), "opening a zero-softness hard source never normalizes it into a Sun"); + h.step(&json!({"widget":h.app.tr("render.light_duplicate").to_string()})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:3".into())); + let duplicated = light::rows(&h.app).unwrap(); + assert_eq!(duplicated.len(), 4); + for (a, b) in duplicated.iter().zip(&initial) { + assert_eq!((a.colour, a.intensity), (b.colour, b.intensity)); + let (Geometry::Directional { direction: a, angular_radius_rad: None }, Geometry::Directional { direction: b, angular_radius_rad: None }) = + (a.geometry, b.geometry) + else { + panic!("hard sources") + }; + assert_eq!(a, b); + } + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(2); + click_gpu_light_add(&mut h, "sun"); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + let sun = light::rows(&h.app).unwrap()[0].clone(); + let Geometry::Directional { angular_radius_rad: Some(radius), .. } = sun.geometry else { panic!("finite Sun") }; + assert_eq!(radius, 0.02); + h.frames(2); + let before = h.app.session.doc.clone(); + h.step(&json!({"widget":h.app.tr("render.light_duplicate").to_string()})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "a finite Sun cannot silently become a second hard source"); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(2); + click_gpu_light_add(&mut h, "directional"); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:5".into())); + let before = h.app.session.doc.clone(); + h.frames(3); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.render_workspace.view.studio.directional_lights.iter().count(), 5); + // Literal world axis, independent of the angle/position adapter and camera. + for (key, value) in [("direction:0", "1"), ("direction:1", "0"), ("direction:2", "0")] { + edit_gpu_light_number(&mut h, key, value); + } + assert_eq!(light::rows(&h.app).unwrap().last().unwrap().geometry, Geometry::Directional { direction: [1.0, 0.0, 0.0], angular_radius_rad: None }); + assert_eq!(h.app.cam, camera); + let request = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&request)["directional_lights"].as_array().unwrap().len(), 5); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][4]["direction"], json!([1.0, 0.0, 0.0])); + let before = h.app.session.doc.clone(); + h.step(&json!({"widget":h.app.tr("render.lighting_solo").to_string()})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.render_workspace.view.lights.visibility.active()); + let visible = image_request(&h.app).unwrap(); + let sources = gpu_lighting_request(&visible)["directional_lights"].as_array().unwrap(); + assert!(sources.iter().take(4).all(|l| l["intensity"] == 0.0)); + assert!(sources[4]["intensity"].as_f64().unwrap() > 0.0); + h.step(&json!({"widget":h.app.tr("render.lighting_solo").to_string()})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_mute").to_string()})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + let muted = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&muted)["directional_lights"][4]["intensity"].as_f64(), Some(0.0)); + h.step(&json!({"widget":h.app.tr("render.lighting_mute").to_string()})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.light_delete").to_string()})).unwrap(); + assert_eq!(light::rows(&h.app).unwrap().len(), 5); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(light::rows(&h.app).unwrap().len(), 6); + assert_eq!(solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(), *h.app.session.doc); +} + +#[test] +fn gpu_sun_insert_and_remove_remap_existing_hard_source_visibility_selection_and_editor_draft() { + use solidcraft_engine::schema::render_lights::Geometry; + for solo in [false, true] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + let original = light::rows(&h.app).unwrap()[0].clone(); + assert_eq!(original.name_key, "render.light_default_key"); + let toggle = if solo { "render.lighting_solo" } else { "render.lighting_mute" }; + h.step(&json!({"widget":h.app.tr(toggle).to_string()})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + let draft = light::editor_draft(&h.app).unwrap(); + assert_eq!(draft.0, "directional:0"); + assert_eq!(draft.2, 3.0_f64.log2()); + assert_eq!(draft.3, 0.0); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + click_gpu_light_add(&mut h, "sun"); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into()), "Add selects the actual new Sun"); + let sun_draft = light::editor_draft(&h.app).unwrap(); + assert_eq!(sun_draft.2, 0.0, "the new Sun must not reuse the old hard source's EV draft at the same old address"); + assert_eq!(sun_draft.3, 0.02_f64.to_degrees()); + let current = light::rows(&h.app).unwrap(); + assert!(matches!(current[0].geometry, Geometry::Directional { angular_radius_rad: Some(_), .. })); + assert_eq!(current[1].geometry, original.geometry); + assert_eq!((current[1].colour, current[1].intensity), (original.colour, original.intensity)); + assert_eq!(current[1].name_key, "render.light_default_fill", "display-only fallback names follow their current ordinal"); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), solo.then_some("directional:1")); + assert_eq!(h.app.render_workspace.view.lights.visibility.muted.contains("directional:1"), !solo); + assert!(!h.app.render_workspace.view.lights.visibility.muted.contains("directional:0")); + let request = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][0]["intensity"].as_f64(), Some(if solo { 3.0 } else { 0.0 })); + assert_eq!(gpu_lighting_request(&request)["sun"]["radiance"][0].as_f64(), Some(if solo { 0.0 } else { 1.0 })); + h.step(&json!({"click":{"handle":"render:tree:light:1"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:1".into())); + assert_eq!(light::editor_draft(&h.app).unwrap().2, 3.0_f64.log2()); + let document = h.app.session.doc.clone(); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + let selected = h.app.render_workspace.view.selection.clone(); + let draft = light::editor_draft(&h.app); + assert!(light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":"directional","softness":0.5}))).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(h.app.render_workspace.view.selection, selected); + assert_eq!(light::editor_draft(&h.app), draft, "a rejected edit applies no identity map or cache invalidation"); + if solo { + // Programmatic removal of a different light preserves the selected hard source. + light::edit(&mut h.app, "render.lights.remove", Some("directional:0"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + } else { + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.light_delete").to_string()})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + } + h.frames(2); + let actual = light::rows(&h.app).unwrap()[0].clone(); + assert_eq!(actual.geometry, original.geometry); + assert_eq!(actual.name_key, original.name_key); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), solo.then_some("directional:0")); + assert_eq!(h.app.render_workspace.view.lights.visibility.muted.contains("directional:0"), !solo); + assert_eq!(light::editor_draft(&h.app).unwrap().0, "directional:0"); + let request = image_request(&h.app).unwrap(); + assert!(gpu_lighting_request(&request)["sun"].is_null()); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][0]["intensity"].as_f64(), Some(if solo { 3.0 } else { 0.0 })); + } +} + +#[test] +fn unrelated_gpu_settings_override_cannot_inherit_old_light_identity_state() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{DirectionalLightOptions, DirectionalLights, StudioLighting}; + let mut h = render_lights_fixture(); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_solo").to_string()})).unwrap(); + h.app.run("render.lights.mute", json!({"id":"directional:1","mute":true})).unwrap(); + let mut unrelated = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::GpuPath { options, .. }) = &mut unrelated.job else { panic!("gpu") }; + options.lighting = Some(StudioLighting { + directional_lights: DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.0, 0.0], intensity: 9.0 }]) + .unwrap(), + ..Default::default() + }); + h.app.run("render.lights.add", json!({"name":"Studio","settings":unrelated,"set":{"kind":"directional"}})).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.active(), "verified mapping belongs to the supplied override, not the old UI rows"); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:1".into())); + let request = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][0]["intensity"].as_f64(), Some(9.0)); + assert!(gpu_lighting_request(&request)["directional_lights"][1]["intensity"].as_f64().unwrap() > 0.0); +} + +#[test] +fn unverified_sun_undo_redo_clears_transient_light_identity_instead_of_reusing_ordinals() { + for solo in [false, true] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + let toggle = if solo { "render.lighting_solo" } else { "render.lighting_mute" }; + h.step(&json!({"widget":h.app.tr(toggle).to_string()})).unwrap(); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + click_gpu_light_add(&mut h, "sun"); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), solo.then_some("directional:1")); + assert_eq!(h.app.render_workspace.view.lights.visibility.muted.contains("directional:1"), !solo); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert!(!h.app.render_workspace.view.lights.visibility.active()); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert!(light::editor_draft(&h.app).is_none()); + assert_eq!(light::rows(&h.app).unwrap().len(), 3); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + h.step(&json!({"widget":h.app.tr(toggle).to_string()})).unwrap(); + assert!(h.app.render_workspace.view.lights.visibility.active()); + h.app.run("edit.redo", json!({})).unwrap(); + h.frames(3); + assert!(!h.app.render_workspace.view.lights.visibility.active(), "a new override after Undo must not move onto the restored Sun"); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert!(light::editor_draft(&h.app).is_none()); + let request = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&request)["sun"]["radiance"][0].as_f64(), Some(1.0)); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][0]["intensity"].as_f64(), Some(3.0)); + } +} + +#[test] +fn verified_numerical_light_undo_redo_preserves_same_source_visibility_and_selection() { + let mut h = render_lights_fixture(); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_mute").to_string()})).unwrap(); + light::edit(&mut h.app, "render.lights.set", Some("directional:0"), Some(json!({"intensity_ev":2}))).unwrap(); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 4.0); + for (command, intensity) in [("edit.undo", 3.0_f64), ("edit.redo", 4.0)] { + h.app.run(command, json!({})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + assert!(h.app.render_workspace.view.lights.visibility.muted.contains("directional:0")); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, intensity); + assert_eq!(light::editor_draft(&h.app).unwrap().2, intensity.log2()); + } +} + +#[test] +fn same_shape_gpu_light_replacement_or_reorder_has_no_ordinal_identity_proof() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{DirectionalLightOptions, DirectionalLights}; + for reorder in [false, true] { + let mut h = render_lights_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{"directional_lights":[ + {"direction":[0,0,1],"color":[1,0,0],"intensity":2}, + {"direction":[1,0,1],"color":[0,0,1],"intensity":4} + ]}}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_solo").to_string()})).unwrap(); + h.app.run("render.lights.mute", json!({"id":"directional:1","mute":true})).unwrap(); + let mut replacement = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::GpuPath { options, .. }) = &mut replacement.job else { panic!("gpu") }; + let lighting = options.lighting.as_mut().unwrap(); + let mut entries: Vec<_> = lighting.directional_lights.iter().copied().collect(); + if reorder { + entries.reverse(); + } else { + entries[0] = DirectionalLightOptions { direction: [0.0, 1.0, 1.0], color: [0.0, 1.0, 0.0], intensity: 9.0 }; + } + lighting.directional_lights = DirectionalLights::new(&entries).unwrap(); + h.app.run("render.settings.set", json!({"name":"Studio","set":replacement})).unwrap(); + h.frames(3); + assert!(!h.app.render_workspace.view.lights.visibility.active(), "same kind/count is not evidence of surviving source identity"); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert!(light::editor_draft(&h.app).is_none()); + let request = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][0]["intensity"].as_f64(), Some(if reorder { 4.0 } else { 9.0 })); + assert_eq!(gpu_lighting_request(&request)["directional_lights"][1]["intensity"].as_f64(), Some(if reorder { 2.0 } else { 4.0 })); + } +} + +#[test] +fn gpu_point_spot_real_controls_save_degree_cones_ranges_undo_and_reopen_exact_runtime_capture() { + use solidcraft_engine::schema::render_lights::Geometry; + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + h.frames(3); + let camera = h.app.cam; + let implicit = light::rows(&h.app).unwrap(); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + click_gpu_light_add(&mut h, "spot"); + h.frames(3); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("spot:0".into())); + for (a, b) in light::rows(&h.app).unwrap().iter().take(3).zip(&implicit) { + assert_eq!((a.geometry, a.intensity, a.colour), (b.geometry, b.intensity, b.colour)); + assert!(!a.implicit); + } + let before = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + h.frames(5); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), (revision, undo)); + for (key, text) in [ + ("position_mm:0", "-3.25"), + ("position_mm:1", "7.5"), + ("position_mm:2", "120.125"), + ("emitted_axis:1", "2"), + ("emitted_axis:0", "1"), + ("emitted_axis:2", "-2"), + ("inner_half_angle_radians", "15.125"), + ("outer_half_angle_radians", "42.5"), + ("reference_distance_mm", "128.25"), + ("minimum_distance_mm", "0.02"), + ] { + edit_gpu_light_number(&mut h, key, text); + } + let source = light::rows(&h.app).unwrap().into_iter().find(|l| l.id == "spot:0").unwrap(); + let Geometry::Spot { position_mm, emitted_axis, inner_half_angle_radians, outer_half_angle_radians, reference_distance_mm, minimum_distance_mm } = + source.geometry + else { + panic!("spot") + }; + assert_eq!(position_mm, [-3.25, 7.5, 120.125]); + assert_eq!(emitted_axis, [1.0, 2.0, -2.0]); + assert_eq!((inner_half_angle_radians, outer_half_angle_radians), (15.125_f64.to_radians(), 42.5_f64.to_radians())); + assert_eq!((reference_distance_mm, minimum_distance_mm), (128.25, 0.02)); + let expected = setups::snapshot(&h.app).unwrap(); + let request = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&request)["punctual_lights"][0]["position_mm"], json!([-3.25, 7.5, 120.125])); + assert_eq!(gpu_lighting_request(&request)["punctual_lights"][0]["cone"]["emitted_axis"], json!([1.0, 2.0, -2.0])); + assert_eq!(gpu_lighting_request(&request)["punctual_lights"][0]["cone"]["inner_half_angle_radians"], json!(inner_half_angle_radians)); + assert_eq!(gpu_lighting_request(&request)["punctual_lights"][0]["reference_distance_mm"], 128.25); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + h.app.run("edit.redo", json!({})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = solidcraft_engine::Session::new(reopened); + setups::load(&mut h.app); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), request); + assert_eq!(h.app.cam, camera, "editing lights never navigates the product camera"); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + click_gpu_light_add(&mut h, "point"); + h.frames(3); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("point:1".into()), "Point and Spot share source slots"); + h.step(&json!({"widget":h.app.tr("render.lighting_solo").to_string()})).unwrap(); + let filtered = image_request(&h.app).unwrap(); + assert_eq!(gpu_lighting_request(&filtered)["punctual_lights"][0]["intensity"], 0.0); + assert_eq!(gpu_lighting_request(&filtered)["punctual_lights"][1]["intensity"], 1.0); + let saved = solidcraft_engine::render_lights::inspect(&h.app.session.doc.render.setups["Studio"]).unwrap(); + assert_eq!(saved.iter().find(|l| l.id == "spot:0").unwrap(), &source, "solo affects only the runtime copy"); +} + +#[test] +fn cpu_adaptive_actual_sampling_control_preserves_saved_flags_and_reopens_with_one_undo() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::adaptive::AdaptiveSampling; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + h.app.cam.fov = 35.0_f64.to_radians(); + h.app.session.set_render_job_host(None).unwrap(); + h.app + .run( + "render.settings.set", + json!({"name":"Adaptive CPU","set":{"width":64,"height":32,"camera":h.app.cam,"exposure_ev":1.25, + "job":{"method":"cpu_raytrace","transparent_background":true,"options":{"progressive":{"samples_per_pixel":48,"seed":81}, + "path":{"max_depth":3},"denoise":true,"lens":{"aperture_radius_mm":0.1,"focus_distance_mm":100.0}, + "lights":[],"output":{"tone_map":"aces_fitted","linear_exr":true}}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "Adaptive CPU".into(); + setups::load(&mut h.app); + inspector::select_editor(&mut h.app, inspector::Editor::Sampling); + h.frames(3); + if crate::scenario::rect_of("render:adaptive-enable").is_none() { + h.step(&json!({"click":{"handle":format!("dialog:section:{}",h.app.tr("render.children.adaptive"))}})).unwrap(); + } + h.frames(3); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + let mut expected = h.app.session.doc.render.setups["Adaptive CPU"].clone(); + let policy = AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }; + let Some(RenderJob::CpuRaytrace { options, .. }) = expected.job.as_mut() else { panic!("CPU job expected") }; + options.adaptive = Some(policy); + h.frames(3); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"render:adaptive-enable"}})).unwrap(); + h.frames(3); + assert_eq!( + h.app.session.doc.render.setups["Adaptive CPU"], expected, + "one actual edit must retain all lens/path/filter/alpha/raw/output/sample/camera intent" + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.job.is_none()); + let saved = image_request(&h.app).unwrap(); + assert_eq!(saved["settings"]["job"]["options"]["adaptive"], json!(policy)); + let mut runtime = json!({"settings":{"camera":camera}}); + cpu::params(&h.app, &mut runtime).unwrap(); + assert_eq!(runtime["raytrace"]["adaptive"], json!(policy)); + assert_eq!(runtime["raytrace"]["progressive"], json!({"samples_per_pixel":48,"seed":81})); + assert!(runtime.get("adaptive").is_none(), "CPU intent must not enter the top-level GPU adaptive lane"); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert!(h.app.render_workspace.view.studio.adaptive.is_none()); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.render_workspace.view.studio.adaptive, Some(policy)); + let container = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&container).unwrap(); + assert_eq!(reopened.render.setups["Adaptive CPU"], expected); + h.app.session = Session::new(reopened); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.name = "Adaptive CPU".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.studio.adaptive, Some(policy)); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); +} + +#[test] +fn cpu_adaptive_invalid_draft_is_visible_and_refused_without_silent_size_profile_or_sampling_changes() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions, adaptive::AdaptiveSampling}; + let mut h = sampling_policy_fixture(false); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 49, seed: 81 }); + h.app.render_workspace.view.studio.adaptive = Some(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }); + let before = h.app.render_workspace.view.clone(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + h.frames(3); + assert!(cpu::validate_progressive_image(&h.app).is_err()); + assert!(image_request(&h.app).is_err()); + let after = &h.app.render_workspace.view; + assert_eq!(after.raytrace.progressive, before.raytrace.progressive); + assert_eq!(after.studio.adaptive, before.studio.adaptive); + assert_eq!((after.draft.width, after.draft.height, after.raytrace.budget), (before.draft.width, before.draft.height, CpuBudget::Compact)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.undo.len(), h.app.session.redo.len())); + assert!(after.job.is_none()); + assert!( + cpu::profile_for_size(&h.app, u64::from(after.draft.width), u64::from(after.draft.height)).is_some(), + "an explicit larger profile can be offered without silently selecting it" + ); +} + +#[test] +fn cpu_general_glass_path_availability_uses_reviewed_unsaved_saved_optics_without_committing_them() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Glass"})).unwrap(); + h.app.run("render.settings.set", json!({"name":"Reviewed Glass","set":{"job":{"method":"gpu_path","options":{"denoise":true}}}})).unwrap(); + h.app + .run( + "render.optics.bind", + json!({"name":"Reviewed Glass","body_index":0,"body_name":"Glass","expected_revision":h.app.session.revision, + "optics":{"ior":1.51,"boundary":"closed_mesh","subsurface":{"scattering_per_mm":0.1,"anisotropy":0}}}), + ) + .unwrap(); + h.app.render_workspace.view.name = "Reviewed Glass".into(); + setups::load(&mut h.app); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + h.app.render_workspace.view.raytrace.primary_samples = 1; + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + let source = h.app.render_workspace.view.draft.optics.iter().next().unwrap().optics; + assert!(materials::path_compatibility(&h.app).unwrap_err().contains("subsurface")); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let mut edited = materials::Binding::from_saved(target, &h.app, source); + edited.glass.subsurface = None; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings = vec![edited]; + materials::path_compatibility(&h.app).unwrap(); + assert!(cpu::path_reason(&h.app).is_none()); + assert!(h.app.render_workspace.view.raytrace.path.is_none(), "availability is not adoption"); + assert!(h.app.session.doc.render.setups["Reviewed Glass"].optics.iter().next().unwrap().optics.subsurface.is_some()); + 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); + // Discarding the review restores the actual saved incompatibility. + h.app.render_workspace.view.materials.bindings.clear(); + assert!(materials::path_compatibility(&h.app).unwrap_err().contains("subsurface")); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); +} + +#[test] +fn render_ui_at_world_points_hit_the_painted_surface_and_letterbox_does_not_select() { + use solidcore_record::Vec3; + use solidcraft_engine::Sel; + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + for side in ["left", "right"] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"corner":[-10,-10,-10],"length":20,"width":20,"height":20,"body_name":"Pick target"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.ui.layout = layout; + h.app.preferences.render_inspector_side = side.into(); + h.app.preferences.render_browser_side = if side == "left" { "right" } else { "left" }.into(); + h.app.render_workspace.view.draft.width = 160; + h.app.render_workspace.view.draft.height = 120; + h.app.cam_anim = None; + h.app.cam.target = Vec3::ZERO; + h.app.cam.yaw = 0.0; + h.app.cam.pitch = std::f64::consts::FRAC_PI_2; + h.app.cam.roll = 0.0; + h.app.cam.distance = 100.0; + h.app.cam.fov = 0.0; + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + for ([width, height], dpi, shots) in [([1100, 760], 1.0, false), ([1440, 1000], 2.0, true)] { + h.ctx.set_pixels_per_point(dpi); + h.app.preferences.render_shots_strip = shots; + h.call("ui.resize", json!({"width":width,"height":height})); + h.frames(4); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let model = h.app.session.model.state(); + let request = image_request(&h.app).unwrap(); + let outer = h.app.viewport.rect.unwrap(); + let frame = crate::scenario::rect_of("render:product:frame").unwrap(); + let world = Vec3::new(5.0, 2.0, 10.0); + // Independent camera maths in the original authored 160x120 output: + // no viewport::projection/camera_rect helper participates in this oracle. + let (x, y, _) = camera.to_screen(world, 160.0, 120.0, 40.0).unwrap(); + let expected = frame.min + frame.size() * egui::vec2((x / 160.0) as f32, (y / 120.0) as f32); + let at = h.at(&json!({"world":[world.x,world.y,world.z]})).unwrap(); + let actual = egui::pos2(at[0] as f32, at[1] as f32); + assert!(actual.distance(expected) < 0.01, "ui.at must use the painted output frame: {actual:?} != {expected:?}"); + let generic = crate::viewport::projection(&h.app, outer); + let explicit = crate::viewport::projection(&h.app, frame); + assert_eq!(generic.rect, frame); + assert_eq!(explicit.rect, frame, "an explicit render frame must not be framed twice"); + assert!(generic.to_screen(world).unwrap().distance(expected) < 0.01); + assert!(explicit.to_screen(world).unwrap().distance(expected) < 0.01); + assert!(!crate::shell::covered(&h.app, actual)); + h.step(&json!({"move":at})).unwrap(); + assert!(matches!(&h.app.viewport.hover, Some(crate::viewport::Hit::Face { body, .. }) if body == "Pick target")); + h.step(&json!({"click":at})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Pick target".into() }]); + // select.set always refreshes display once, including repeat selection; + // it does not change the document or create a history entry. + let selected_history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert_eq!(selected_history, (history.0 + 1, history.1, history.2)); + assert!(Arc::ptr_eq(&h.app.session.model.state(), &model)); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + let free = crate::shell::workspace_content(&h.app, crate::render_ui::canvas(&h.app, outer)); + let outside = if frame.left() - free.left() > 2.0 { + egui::pos2((free.left() + frame.left()) * 0.5, frame.center().y) + } else { + assert!(frame.top() - free.top() > 2.0); + egui::pos2(frame.center().x, (free.top() + frame.top()) * 0.5) + }; + assert!(free.contains(outside) && !frame.contains(outside)); + h.step(&json!({"click":[outside.x,outside.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Pick target".into() }], "letterbox cannot select or clear scene geometry"); + assert_eq!(h.app.cam, camera); + assert_eq!(image_request(&h.app).unwrap(), request); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), selected_history); + assert!(Arc::ptr_eq(&h.app.session.model.state(), &model), "gray click cannot rebuild geometry"); + assert!(h.app.render_workspace.view.job.is_none()); + } + } + } +} + +#[test] +fn rendered_camera_layout_cache_and_fit_share_the_exact_frame_without_moving_outer_controls() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for side in ["left", "right"] { + let mut h = Harness::new(); + h.app.ui.layout = mode; + h.call("ui.resize", json!({"width":1440,"height":1600})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Framed product"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.preferences.render_inspector_side = side.into(); + h.app.preferences.render_browser_side = if side == "left" { "right" } else { "left" }.into(); + h.app.render_workspace.view.draft.width = 160; + h.app.render_workspace.view.draft.height = 120; + h.app.cam.fov = 0.6; + h.app.cam_anim = None; + setups::save(&mut h.app).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let fov = h.app.cam.fov; + for kind in ["shot", "sampling", "effects", "output"] { + let selection = if kind == "shot" { json!({"kind":kind,"id":h.app.render_workspace.view.name}) } else { json!({"kind":kind}) }; + h.app.run("view.render_select", selection).unwrap(); + h.frames(4); + let outer = h.app.viewport.rect.unwrap(); + let frame = crate::scenario::rect_of("render:product:frame").unwrap(); + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert_eq!(layout.viewport, frame, "the cached projection must describe painted pixels"); + assert!(frame.contains_rect(layout.drawable)); + assert!(frame.contains_rect(layout.middle)); + assert_eq!(picture_layout(&h.app, layout), *layout, "Fit cannot frame an already-framed cache twice"); + assert_eq!(camera_rect(&h.app, outer), frame); + assert_eq!(camera_rect(&h.app, frame), frame); + assert_eq!(crate::viewport::axis_rect(&h.app, outer), layout.axis_view, "outer control calls retain the reserved compass"); + if layout.axis_view.is_positive() { + assert!(outer.contains_rect(layout.axis_view)); + } + if layout.navigation.is_positive() { + assert!(outer.contains_rect(layout.navigation)); + } + h.step(&json!({"key":"F6"})).unwrap(); + h.settle(); + assert_product_fits_canvas(&h.app); // Preserve the preexisting actual-camera/corner oracle. + assert_eq!(h.app.cam.fov, fov); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } + } + } +} + +#[test] +fn gray_letterbox_gestures_use_the_real_camera_scale_and_never_select_or_assign_geometry() { + use solidcore_record::Vec3; + use solidcraft_engine::Sel; + for fov in [0.0, 0.6] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1600})); + h.app.run("solid.box", json!({"corner":[-10,-10,-10],"length":20,"width":20,"height":20,"body_name":"Navigation target"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.draft.width = 160; + h.app.render_workspace.view.draft.height = 120; + h.app.cam = Camera { target: Vec3::ZERO, distance: 100.0, fov, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..h.app.cam }; + h.app.cancel_view_animation(); + h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); + h.app.session.selection = vec![Sel::Body { name: "Navigation target".into() }]; + h.frames(4); + let outer = h.app.viewport.rect.unwrap(); + let frame = crate::scenario::rect_of("render:product:frame").unwrap(); + let free = crate::shell::workspace_content(&h.app, crate::render_ui::canvas(&h.app, outer)); + let from = egui::pos2(frame.center().x, (frame.bottom() + free.bottom()) * 0.5); + let delta = egui::vec2(30.0, -18.0); + assert!(free.contains(from) && !frame.contains(from) && !crate::shell::covered(&h.app, from)); + assert!(free.contains(from + delta) && !frame.contains(from + delta)); + let project = |camera: Camera| { + let (x, y, _) = camera.to_screen(Vec3::ZERO, 160.0, 120.0, 40.0).unwrap(); + frame.min + frame.size() * egui::vec2((x / 160.0) as f32, (y / 120.0) as f32) + }; + let before = h.app.cam; + let at = project(before); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let selection = h.app.session.selection.clone(); + h.step(&json!({"drag":[[from.x,from.y],[(from+delta).x,(from+delta).y]],"steps":1})).unwrap(); + h.frames(2); + assert_ne!(h.app.cam.target, before.target, "gray free canvas must accept the shared Pan gesture"); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch, h.app.cam.distance, h.app.cam.fov), (before.yaw, before.pitch, before.distance, before.fov)); + assert!( + project(h.app.cam).distance(at + delta) < 0.02, + "world point must follow logical pixels in the actual framed projection, not the outer canvas scale" + ); + assert_eq!(h.app.session.selection, selection); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn gray_canvas_empty_space_orbit_ignores_cropped_geometry_and_its_hidden_surface_pivot() { + use solidcore_record::Vec3; + use solidcraft_engine::Sel; + for (preset, ctrl) in [("fusion", true), (crate::prefs::OPENSCAD_NAV, false)] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1600})); + h.app.run("solid.box", json!({"corner":[-1000,-1000,-10],"length":2000,"width":2000,"height":20,"body_name":"Cropped body"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.draft.width = 160; + h.app.render_workspace.view.draft.height = 120; + h.app.preferences.nav = preset.into(); + h.app.preferences.orbit_around = crate::prefs::OrbitAround::Cursor; + h.app.viewport.nav = None; + h.app.cancel_view_animation(); + h.app.cam = Camera { target: Vec3::ZERO, distance: 100.0, fov: 0.0, yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..h.app.cam }; + h.app.session.selection = vec![Sel::Body { name: "Cropped body".into() }]; + h.frames(4); + let outer = h.app.viewport.rect.unwrap(); + let frame = crate::scenario::rect_of("render:product:frame").unwrap(); + let free = crate::shell::workspace_content(&h.app, crate::render_ui::canvas(&h.app, outer)); + let from = egui::pos2(frame.center().x, (frame.bottom() + free.bottom()) * 0.5); + let to = from + egui::vec2(36.0, -24.0); + assert!(free.contains(from) && !frame.contains(from) && !crate::shell::covered(&h.app, from)); + assert!(free.contains(to) && !frame.contains(to)); + let proj = crate::viewport::projection(&h.app, outer); + let (origin, direction) = proj.ray(from); + let distance = (10.0 - origin.z) / direction.z; + let extrapolated = origin + direction * distance; + assert!( + distance > 0.0 && extrapolated.x.abs() < 1000.0 && extrapolated.y.abs() < 1000.0, + "the invisible continuation really crosses the cropped body's top face" + ); + assert!(!crate::viewport::pick(&h.app, &proj, frame.center()).is_empty(), "visible geometry remains pickable"); + assert!(crate::viewport::pick(&h.app, &proj, from).is_empty(), "letterbox has no hidden surface"); + assert!(crate::viewport::pick_all(&h.app, &proj, from).is_empty(), "Select Other cannot enumerate invisible surfaces"); + assert!(crate::viewport::pick_for_tool(&h.app, &proj, from).is_empty(), "tool picks obey the same image boundary"); + assert!(crate::select_other::rows(&h.app, &proj, from).is_empty()); + assert!(crate::viewport::pick_cached(&mut h.app, &proj, from).is_empty(), "surface zoom uses the same clipped candidates"); + assert_eq!(crate::prefs::pivot_under(&h.app, &proj, from), Vec3::ZERO, "gray cursor orbit uses the visible body's centre"); + let before = h.app.cam; + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let selection = h.app.session.selection.clone(); + h.step(&json!({"drag":[[from.x,from.y],[to.x,to.y]],"ctrl":ctrl,"steps":1})).unwrap(); + h.frames(2); + assert_ne!((h.app.cam.yaw, h.app.cam.pitch), (before.yaw, before.pitch), "{preset}: empty gray canvas accepts the preset's orbit gesture"); + assert!(h.app.cam.target.len() < 1e-9, "the hidden extrapolated surface cannot become the orbit pivot"); + assert_eq!((h.app.cam.distance, h.app.cam.fov), (before.distance, before.fov)); + assert_eq!(h.app.session.selection, selection); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn light_stage_describes_world_coordinates_without_inert_frame_settings_or_edits() { + fn draw(h: &mut Harness, width: f32, events: Vec) -> egui::FullOutput { + crate::scenario::clear_handles(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, crate::ui_kit::StageBar::HEIGHT)); + let mut output = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect.expand(20.0)), events, ..Default::default() }, |ui| { + crate::render_ui::stage_bar(&mut h.app, ui, rect) + }); + // This fixture inspects shapes and handles without a texture backend. + output.textures_delta.clear(); + output + } + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + for custom in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = method; + h.app.render_workspace.view.draft.width = 32; + h.app.render_workspace.view.draft.height = 24; + if custom { + h.app.render_workspace.view.raytrace.preset = None; + h.app.render_workspace.view.raytrace.lights = + Some(serde_json::from_value(json!([{"direction":[0.0,1.0,0.0],"color":[0.7,1.0,0.4],"intensity":2.0}])).unwrap()); + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.sun_enabled = true; + h.app.render_workspace.view.studio.sun.direction = [0.0, 1.0, 0.0]; + if method == ImageMethod::CpuRaytrace { + // The read-only header fixture explicitly authors the valid + // transport required by its finite Sun, before snapshots. + h.app.render_workspace.view.raytrace.path = Some(Default::default()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.shadows = true; + } + } + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let settings = setups::draft(&h.app).unwrap(); + let request = image_request(&h.app).unwrap(); + let lights = light::rows(&h.app).unwrap(); + let preview = light::preview(&h.app).unwrap(); + assert!(!lights.is_empty()); + let lights = serde_json::to_value(lights).unwrap(); + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + h.app.ui.layout = layout; + for width in [800.0, 1440.0] { + let output = draw(&mut h, width, vec![]); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>(); + assert!(text.iter().any(|s| s == h.app.tr("render.light_space_world"))); + for obsolete in ["render.fixed_camera", "render.fixed_world", "render.light_anchor_pending"] { + assert!(!text.iter().any(|s| s == h.app.tr(obsolete)), "no inert coordinate-frame control: {obsolete}"); + } + let note = crate::scenario::rect_of("render:light_space_note").unwrap(); + let bar = crate::scenario::rect_of("render:stage_bar").unwrap(); + assert!(bar.contains_rect(note), "world-coordinate note fits the shared toolbar"); + for pressed in [true, false] { + draw( + &mut h, + width, + vec![ + egui::Event::PointerMoved(note.center()), + egui::Event::PointerButton { + pos: note.center(), + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }, + ], + ); + } + assert_eq!(h.app.cam, camera); + assert_eq!(setups::draft(&h.app).unwrap(), settings); + assert_eq!(image_request(&h.app).unwrap(), request); + assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } + } + h.app.cam.yaw += 0.7; + h.app.cam.pitch -= 0.2; + assert_eq!(serde_json::to_value(light::rows(&h.app).unwrap()).unwrap(), lights, "orbit does not reauthor world-space light geometry"); + assert_eq!(light::preview(&h.app).unwrap(), preview, "preview receives unchanged world-space light values"); + assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cpu_subsurface_real_glass_pointer_enable_render_save_undo_and_cold_hydration_keep_optical_intent() { + use solidcraft_engine::render::job::{CpuHost, Integrator, Phase}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":3000})); + h.app.preferences.render_legacy_image_defaults = false; + let host = CpuHost::for_platform().unwrap(); + let available = host.descriptor_for(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + h.app.run("solid.box", json!({"length":10,"width":10,"height":2,"body_name":"Scattering"})).unwrap(); + h.frames(3); + let camera = Camera { + target: solidcore_record::Vec3::new(5.0, 5.0, 0.5), + distance: 0.5, + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + fov: 0.6, + ..Default::default() + }; + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"camera":camera,"width":8,"height":8,"job":{"method":"cpu_raytrace","options":{ + "path":{"max_depth":16},"progressive":{"samples_per_pixel":3,"seed":9},"lights":[], + "environment":{"color":[1,1,1],"intensity":1},"output":{"linear_exr":true} + }}}}), + ) + .unwrap(); + h.app + .run( + "render.optics.bind", + json!({"name":"Studio","body_index":0,"body_name":"Scattering","expected_revision":h.app.session.revision, + "optics":{"ior":1.0,"boundary":"closed_mesh","absorption_per_mm":[0.1,0.2,0.0]}}), + ) + .unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Scattering".into()}]})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.frames(3); + assert_eq!(h.app.cam, camera, "opening the authored shot must hydrate its camera"); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:subsurface-enable"}})).unwrap(); + h.frames(2); + for (handle, text) in [("render:glass:subsurface-rate", "0.3"), ("render:glass:subsurface-g", "0.37")] { + let field = crate::scenario::rect_of(handle).unwrap(); + assert!(crate::scenario::rect_of("render:inspector").unwrap().contains_rect(field), "type only into a visible actual numeric 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":text})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(2); + } + let temporary = image_request(&h.app).unwrap(); + assert_eq!(temporary["settings"]["optics"][0]["optics"]["subsurface"]["scattering_per_mm"], 0.3); + assert_eq!(temporary["settings"]["optics"][0]["optics"]["subsurface"]["anisotropy"], 0.37); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let optics = temporary["settings"]["optics"].clone(); + let target = h.app.render_workspace.view.materials.bindings[0].target.clone(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.frames(2); + let gpu = image_request(&h.app).unwrap(); + assert_eq!(gpu["settings"]["optics"], optics, "method switches preserve full rate, phase bias and stable optical identity"); + assert_eq!(gpu["settings"]["camera"], json!(camera)); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].target, target); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.frames(2); + assert_eq!(image_request(&h.app).unwrap(), temporary); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let old_pixels = if available { + h.app.session.execute("render.preflight", &temporary).unwrap(); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + Some((frame.png().to_vec(), frame.linear_exr().unwrap().to_vec())) + } else { + assert!(h.app.session.execute("render.preflight", &temporary).is_err(), "offline editing cannot claim a producer"); + None + }; + h.frames(2); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.frames(2); + let saved_section = h.app.tr("render.appearance_editor.saved").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{saved_section}")}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.appearance_editor.replace")})).unwrap(); + h.step(&json!({"click":{"handle":"render:optics-save"}})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + let saved = h.app.session.doc.clone(); + assert_eq!(saved.render.setups["Studio"].optics.iter().next().unwrap().optics.subsurface.unwrap().scattering_per_mm, 0.3); + assert_eq!(saved.features, before.features); + assert_eq!(saved.materials, before.materials); + assert_eq!(saved.appearances, before.appearances); + assert_eq!(saved.render.setups["Studio"].camera, before.render.setups["Studio"].camera); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, saved); + h.app.session = Session::new(solidcraft_engine::doc::Document::from_json(&saved.to_json()).unwrap()); + h.app.session.set_render_job_host(Some(host)).unwrap(); + reset_document(&mut h.app); + setups::load(&mut h.app); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Scattering".into()}]})).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera, "cold reopening must retain the shot camera without a helper override"); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["optics"], temporary["settings"]["optics"]); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "hydration is not a new temporary override"); + if let Some(expected) = old_pixels { + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!((frame.png().to_vec(), frame.linear_exr().unwrap().to_vec()), expected); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); +} + +fn celestial_editor_fixture(gpu: bool) -> Harness { + let mut h = Harness::new(); + let camera = solidcraft_engine::render::Camera { distance: 30.0, fov: 0.7, ..Default::default() }; + let sun = json!({"direction":[0.2,-0.3,0.9],"angular_radius_rad":0.02,"radiance":[301.25,202.5,103.75]}); + let sky = json!({"kind":"sky","gradient":{"zenith":[0.25,0.5,1.0],"horizon":[0.75,0.5,0.25],"ground":[0.125,0.25,0.5]},"rotation_rad":0.731,"intensity":1.75}); + let job = if gpu { + json!({"method":"gpu_path","options":{"samples":32,"max_depth":4,"seed":81,"denoise":true, + "lighting":{"sun":sun,"environment":[0,0,0]},"environment":sky,"linear_exr":true, + "lens":{"aperture_radius_mm":0.01,"focus_distance_mm":30}}}) + } else { + json!({"method":"cpu_raytrace","options":{ + "path":{"max_depth":4},"progressive":{"samples_per_pixel":3,"seed":81},"lights":[],"sun":sun,"sky":sky,"denoise":true, + "output":{"linear_exr":true},"lens":{"aperture_radius_mm":0.01,"focus_distance_mm":30}}}) + }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":16,"height":12,"camera":camera,"job":job}})).unwrap(); + h.app.cam = camera; + setups::load(&mut h.app); + h +} +#[test] +fn cpu_celestial_load_snapshot_undo_and_environment_edit_keep_all_authored_intent() { + let mut h = celestial_editor_fixture(false); + let before = h.app.session.doc.render.setups["Studio"].clone(); + let camera = h.app.cam; + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + assert_eq!(h.app.render_workspace.view.cpu.environment, cpu::Environment::Sky); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + environment_editor_frame(&mut h, vec![]); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + let captured = image_request(&h.app).unwrap(); + assert_eq!(captured["settings"]["job"], json!(before.job)); + let mut snapshot = json!({"settings":{}}); + cpu::params(&h.app, &mut snapshot).unwrap(); + assert_eq!(snapshot["raytrace"]["sun"], json!({"direction":[0.2,-0.3,0.9],"angular_radius_rad":0.02,"radiance":[301.25,202.5,103.75]})); + assert_eq!(snapshot["raytrace"]["sky"]["rotation_rad"], 0.731); + environment::commit_environment(&mut h.app, json!({"intensity":75.0})).unwrap(); + let changed = h.app.session.doc.render.setups["Studio"].clone(); + let mut expected = before.clone(); + if let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut expected.job { + let Some(solidcraft_engine::doc::render_settings::SkyEnvironment::Sky { intensity, .. }) = &mut options.sky else { panic!("Sky expected") }; + *intensity = 75.0; + } + assert_eq!(changed, expected); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), before); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), changed); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["Studio"], changed); +} +fn celestial_method_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 600.0))), events, ..Default::default() }, + |ui| { + method_dropdown(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} +fn celestial_method_click(h: &mut Harness, handle: &str) { + let at = crate::scenario::handle_at(handle).unwrap(); + for pressed in [true, false] { + celestial_method_frame( + h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } +} +#[test] +fn gpu_sky_to_cpu_has_reachable_explicit_indirect_switch_and_one_undo_without_dropping_fields() { + let mut h = celestial_editor_fixture(true); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + assert!(switch_celestial_method(&mut h.app, ImageMethod::CpuRaytrace, false).unwrap_err().contains(h.app.tr("render.cpu_celestial_switch"))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + for _ in 0..3 { + celestial_method_frame(&mut h, vec![]); + } + celestial_method_click(&mut h, "render:method"); + celestial_method_frame(&mut h, vec![]); + let at = crate::scenario::handle_at("render:method-cpu-indirect").unwrap(); + assert!((0.0..=308.0).contains(&at.x)); + celestial_method_click(&mut h, "render:method-cpu-indirect"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(h.app.render_workspace.view.lights.visibility.muted.contains("directional:0")); + let filtered = image_request(&h.app).unwrap(); + assert_eq!(filtered["settings"]["job"]["options"]["sun"]["radiance"], json!([0.0, 0.0, 0.0])); + let cpu = setups::snapshot(&h.app).unwrap(); + cpu.validate().unwrap(); + let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &cpu.job else { panic!("CPU expected") }; + let Some(solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options: gpu, .. }) = &saved.job else { panic!("GPU expected") }; + assert_eq!(options.sun, gpu.lighting.unwrap().sun); + assert_eq!(options.sky, gpu.environment); + assert_eq!(options.lens, gpu.lens); + assert_eq!(options.denoise, gpu.denoise); + assert!(options.output.as_ref().unwrap().linear_exr); + assert_eq!(options.path.unwrap().max_depth, 4); + assert_eq!(options.progressive.unwrap(), Default::default()); + assert!(options.shadows); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), saved); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), cpu); + switch_celestial_method(&mut h.app, ImageMethod::GpuRaytrace, false).unwrap(); + let roundtrip = setups::snapshot(&h.app).unwrap(); + let Some(solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options: again, .. }) = &roundtrip.job else { panic!("GPU expected") }; + assert_eq!(again.environment, gpu.environment); + assert_eq!(again.lighting, gpu.lighting); + assert_eq!(h.app.cam, camera); +} +#[test] +fn cpu_celestial_switch_refuses_incompatible_depth_or_sampling_atomically() { + for incompatible in ["depth", "adaptive", "transmission"] { + let mut h = celestial_editor_fixture(true); + if incompatible == "depth" { + h.app.render_workspace.view.max_depth = 17; + } else if incompatible == "transmission" { + h.app.render_workspace.view.studio.transmission_samples = 4; + } else { + h.app.render_workspace.view.raytrace.progressive = + Some(solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: 64, seed: 81 }); + h.app.render_workspace.view.studio.adaptive = + Some(solidcraft_engine::render::job::adaptive::AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }); + } + let before = setups::draft(&h.app).unwrap(); + let dormant = h.app.render_workspace.view.raytrace.clone(); + let adaptive = h.app.render_workspace.view.studio.adaptive; + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert!(switch_celestial_method(&mut h.app, ImageMethod::CpuRaytrace, true).is_err(), "{incompatible}"); + assert_eq!(setups::draft(&h.app).unwrap(), before); + assert_eq!(h.app.render_workspace.view.raytrace, dormant); + assert_eq!(h.app.render_workspace.view.studio.adaptive, adaptive); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn raw_unbound_cpu_celestial_options_cannot_be_lost_by_setup_snapshot_or_runtime_lowering() { + for sky in [false, true] { + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.path = Some(Default::default()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + if sky { + h.app.render_workspace.view.raytrace.sky = Some(Box::default()); + } else { + h.app.render_workspace.view.raytrace.sun = Some(Box::new(h.app.render_workspace.view.studio.sun)); + } + let before = h.app.render_workspace.view.raytrace.clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(setups::snapshot(&h.app).is_err()); + let mut request = json!({"settings":{}}); + assert!(cpu::params(&h.app, &mut request).is_err()); + assert_eq!(h.app.render_workspace.view.raytrace, before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn celestial_environment_numerical_edits_keep_saved_camera_and_real_navigation_dirty_even_when_capturing_hdr() { + for gpu in [false, true] { + for edit in ["gradient", "intensity", "hdr"] { + let mut h = celestial_editor_fixture(gpu); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + let saved_camera = saved.camera; + h.app.cam.yaw += 0.2; + let live_camera = h.app.cam; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + let undo = h.app.session.undo.len(); + match edit { + "gradient" => { + if gpu { + h.app.render_workspace.view.studio.gradient.zenith[0] = 0.375; + } else { + h.app.render_workspace.view.cpu.gradient.zenith[0] = 0.375; + } + environment::persist(&mut h.app); + } + "intensity" => environment::commit_environment(&mut h.app, json!({"intensity":75})).unwrap(), + _ => { + let path = h.dir.join("celestial-camera-preserved.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + let target = if gpu { hdr::Target::Gpu } else { hdr::Target::Cpu }; + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + if gpu { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + } else { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + } + environment::persist(&mut h.app); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + } + } + let changed = h.app.session.doc.render.setups["Studio"].clone(); + assert_eq!(changed.camera, saved_camera, "GPU={gpu}/{edit}: numerical commits cannot silently Update shot"); + assert_eq!(h.app.cam, live_camera); + assert_eq!(h.app.session.undo.len(), undo + 1, "one atomic numerical/source transaction"); + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "navigation remains a real draft after {edit}"); + assert_eq!(h.app.render_workspace.view.clean_setup.as_ref().unwrap().camera, saved_camera); + let old_sun = serde_json::to_value(&saved).unwrap(); + let new_sun = serde_json::to_value(&changed).unwrap(); + let sun_path = if gpu { "lighting" } else { "sun" }; + assert_eq!(old_sun["job"]["options"][sun_path], new_sun["job"]["options"][sun_path], "Sun/rig survives every source edit"); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], saved); + assert_eq!(h.app.cam, live_camera); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], changed); + assert_eq!(h.app.cam, live_camera); + } + } +} + +#[test] +fn celestial_lighting_metadata_uses_actual_profile_without_inventing_a_default_sized_image() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = celestial_editor_fixture(false); + let mut setup = h.app.session.doc.render.setups["Studio"].clone(); + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut setup.job { + options.budget = CpuBudget::Studio; + options.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 81 }); + options.punctual_lights = Some(vec![]); + options.area_lights = Some(vec![]); + } + h.app.run("render.settings.set", json!({"name":"Studio","set":setup})).unwrap(); + setups::load(&mut h.app); + let camera = h.app.cam; + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let rows = light::rows(&h.app).unwrap(); + assert_eq!(rows.len(), 1); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (16, 12)); + switch_celestial_method(&mut h.app, ImageMethod::GpuRaytrace, false).unwrap(); + switch_celestial_method(&mut h.app, ImageMethod::CpuRaytrace, false).unwrap(); + assert_eq!(setups::snapshot(&h.app).unwrap(), setup, "only the method transaction's actual authoring size/profile may govern admission"); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), history.1 + 2); +} +#[test] +fn celestial_metadata_success_does_not_bypass_exact_full_request_adoption_limits() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = celestial_editor_fixture(true); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":1024,"height":768}})).unwrap(); + setups::load(&mut h.app); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 81 }); + h.app.render_workspace.view.raytrace.budget = CpuBudget::Compact; + let mut metadata = h.app.render_workspace.view.clone(); + metadata.raytrace.path = Some(Default::default()); + metadata.raytrace.shadows = true; + metadata.raytrace.primary_samples = 1; + light::celestial_method(&h.app, &mut metadata, ImageMethod::CpuRaytrace).unwrap(); + assert_eq!((metadata.draft.width, metadata.draft.height), (1024, 768), "lighting-only validation cannot rewrite the authored image"); + let before = setups::draft(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let dormant = h.app.render_workspace.view.raytrace.clone(); + assert!(switch_celestial_method(&mut h.app, ImageMethod::CpuRaytrace, true).is_err(), "1024×768×64 exceeds Compact's unchanged camera budget"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(setups::draft(&h.app).unwrap(), before); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.raytrace, dormant); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); +} + +fn volume_editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 1200.0))), events, ..Default::default() }, + |ui| environment::atmosphere(&mut h.app, ui), + ); + output.textures_delta.clear(); +} + +fn volume_editor_click(h: &mut Harness, handle: &str) { + volume_editor_frame(h, vec![]); + let point = crate::scenario::rect_of(handle).expect("actual visible Atmosphere control").center(); + for pressed in [true, false] { + volume_editor_frame( + h, + vec![ + egui::Event::PointerMoved(point), + egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } +} + +fn volume_editor_number(h: &mut Harness, handle: &str, text: &str) { + // DragValue's real double-click text editor, never a guessed neighbouring field. + volume_editor_click(h, handle); + volume_editor_click(h, handle); + let command = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + volume_editor_frame(h, vec![egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: command }]); + volume_editor_frame(h, vec![egui::Event::Text(text.into())]); + volume_editor_frame( + h, + vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + volume_editor_frame(h, vec![]); +} + +fn cpu_volume_editor_fixture(path: bool, extinction: Option) -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Volume subject"})).unwrap(); + let camera = Camera { target: solidcore_record::Vec3::new(5.0, 5.0, 1.5), distance: 30.0, fov: 0.7, ..Default::default() }; + let volume = extinction.map(|extinction| { + json!({"min_mm":[-20,-20,-20],"max_mm":[20,20,20],"extinction_per_mm":extinction, + "scattering_albedo":[0.2,0.4,0.6],"anisotropy":0.3}) + }); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"camera":camera,"width":16,"height":12,"job":{"method":"cpu_raytrace","options":{ + "primary_samples":if path {1} else {4},"path":path.then_some(json!({"max_depth":4})), + "progressive":path.then_some(json!({"samples_per_pixel":3,"seed":81})),"lights":[], + "environment":{"color":[0.5,0.75,1.0],"intensity":0.25},"output":{"linear_exr":true},"volume":volume}}}}), + ) + .unwrap(); + h.app.cam = camera; + setups::load(&mut h.app); + h +} + +#[test] +fn cpu_atmosphere_pointer_fields_preserve_saved_camera_and_roundtrip_with_one_undo_each() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = cpu_volume_editor_fixture(true, None); + let host = solidcraft_engine::render::job::CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host)).unwrap(); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + h.app.cam.yaw += 0.2; + let camera = h.app.cam; + setups::refresh_dirty(&mut h.app); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for _ in 0..3 { + volume_editor_frame(&mut h, vec![]); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + for row in ["min", "max", "albedo"] { + for axis in 0..3 { + let rect = crate::scenario::rect_of(&format!("render:volume:{row}:{axis}")).unwrap(); + assert!( + rect.is_positive() && rect.left() >= 0.0 && rect.right() <= 308.0, + "{row}/{axis}: numeric cell must remain in the narrow inspector: {rect:?}" + ); + } + } + volume_editor_click(&mut h, "render:volume-enable"); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + let with_box = h.app.session.doc.render.setups["Studio"].clone(); + assert_eq!(with_box.camera, saved.camera); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.dirty, "real navigation remains a draft"); + volume_editor_number(&mut h, "render:volume:extinction", "0.0025"); + let changed = h.app.session.doc.render.setups["Studio"].clone(); + let mut expected = saved.clone(); + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut expected.job { + options.volume = Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0025, ..Default::default() }); + } + assert_eq!(changed, expected, "the exact box edit changes no lighting, sampling, output or saved camera field"); + assert_eq!(h.app.session.undo.len(), history.1 + 2, "one command for the finished numeric gesture"); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.dirty); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["volume"]["extinction_per_mm"], 0.0025); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], with_box); + assert_eq!(h.app.render_workspace.view.studio.volume.unwrap().extinction_per_mm, 0.001); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], changed); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + reset_document(&mut h.app); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap().job, changed.job); + assert_eq!(h.app.render_workspace.view.raytrace.volume, h.app.render_workspace.view.studio.volume); + let undo = h.app.session.undo.len(); + volume_editor_click(&mut h, "render:volume-enable"); + assert!(h.app.render_workspace.view.studio.volume.is_none()); + assert!(h.app.render_workspace.view.raytrace.volume.is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(setups::snapshot(&h.app).is_ok(), "removal cannot leave a stale raw-volume marker"); +} + +#[test] +fn cpu_atmosphere_explicit_indirect_action_preserves_inactive_and_absent_volume_intent() { + use solidcraft_engine::doc::render_settings::RenderJob; + for extinction in [None, Some(0.0)] { + let mut h = cpu_volume_editor_fixture(false, extinction); + let before = h.app.session.doc.render.setups["Studio"].clone(); + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + volume_editor_frame(&mut h, vec![]); + assert_eq!(h.app.session.doc.render.setups["Studio"], before, "paint never adopts sampling or transport"); + volume_editor_click(&mut h, "render:volume-enable-path"); + let mut expected = before.clone(); + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut expected.job { + options.path = Some(Default::default()); + options.progressive = Some(Default::default()); + options.primary_samples = 1; + options.shadows = true; + } + assert_eq!(h.app.session.doc.render.setups["Studio"], expected); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.studio.volume.is_some(), extinction.is_some()); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], before); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + if extinction.is_some() { + volume_editor_click(&mut h, "render:volume-enable"); + assert!(h.app.render_workspace.view.studio.volume.is_none(), "inactive authored box can be removed without enabling transport"); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + } + } +} + +#[test] +fn cpu_atmosphere_invalid_or_incompatible_edits_refuse_atomically_without_erasing_saved_intent() { + use solidcraft_engine::render::job::volume::HomogeneousVolume; + for incompatible in ["path", "denoise", "bounds", "nonfinite"] { + let mut h = cpu_volume_editor_fixture(incompatible != "path", None); + if incompatible == "denoise" { + h.app.render_workspace.view.studio.denoise = true; + } + let before = setups::draft(&h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let camera = h.app.cam; + let view = h.app.render_workspace.view.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let mut value = HomogeneousVolume::default(); + if incompatible == "bounds" { + value.min_mm = value.max_mm; + } + if incompatible == "nonfinite" { + value.extinction_per_mm = f64::NAN; + } + assert!(environment::commit_atmosphere(&mut h.app, Some(value)).is_err(), "{incompatible}"); + assert_eq!(setups::draft(&h.app).unwrap(), before); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.raytrace, view.raytrace); + assert_eq!(h.app.render_workspace.view.studio.volume, view.studio.volume); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn authored_atmosphere_method_switch_is_explicit_atomic_and_preserves_common_light_addresses() { + let mut h = environment_editor_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"width":16,"height":12,"job":{"method":"gpu_path","options":{ + "samples":3,"max_depth":4,"seed":81,"environment":null,"lighting":{"environment":[0.1,0.2,0.3],"directional_lights":[ + {"direction":[0,0,1],"color":[1,1,1],"intensity":2}]},"volume":{"extinction_per_mm":0.001}}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + let source = h.app.session.doc.render.setups["Studio"].clone(); + let rows = light::rows(&h.app).unwrap(); + assert_eq!(rows.len(), 1); + light::loaded(&mut h.app); + h.app.run("render.lights.mute", json!({"id":rows[0].id,"mute":true})).unwrap(); + let visibility = light::preview(&h.app).unwrap(); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(switch_volume_method(&mut h.app, ImageMethod::CpuRaytrace, false).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo); + switch_volume_method(&mut h.app, ImageMethod::CpuRaytrace, true).unwrap(); + assert_eq!( + h.app.render_workspace.view.studio.volume, + source.job.as_ref().and_then(|job| match job { + solidcraft_engine::doc::render_settings::RenderJob::GpuPath { options, .. } => options.volume, + _ => None, + }) + ); + assert_eq!(h.app.render_workspace.view.raytrace.path.unwrap().max_depth, 4); + assert_eq!(light::preview(&h.app).unwrap(), visibility, "mute identity survives only the proven address-preserving method conversion"); + assert!(h.app.render_workspace.view.lights.visibility.muted.contains(&rows[0].id)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(light::rows(&h.app).unwrap().iter().zip(rows.iter()).all(|(a, b)| a.id == b.id)); + switch_volume_method(&mut h.app, ImageMethod::GpuRaytrace, false).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Studio"], source); + assert_eq!(light::preview(&h.app).unwrap(), visibility); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 2); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn clicked_cpu_atmosphere_start_captures_saved_box_and_reopens_identical_png_and_linear_master() { + use solidcraft_engine::render::job::{CpuHost, Phase}; + let mut h = cpu_volume_editor_fixture(true, None); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("CPU Atmosphere actual Start test requires raytrace-cpu"); + return; + } + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + // Author the same physical box through the common visible control before Start. + volume_editor_click(&mut h, "render:volume-enable"); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + inspector::select_editor(&mut h.app, inspector::Editor::Output); + h.frames(3); + let request = image_params(&h.app).unwrap(); + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + assert_eq!(checked["request"]["raytrace"]["volume"]["extinction_per_mm"], 0.001); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let terminal = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(terminal.progress.phase, Phase::Completed, "{:?}", terminal.error); + let image = handle.frame().unwrap().unwrap(); + let png = image.png().to_vec(); + let exr = image.linear_exr().unwrap().to_vec(); + assert!(!png.is_empty() && !exr.is_empty()); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["Studio"], saved); + h.app.session = Session::new(reopened); + h.app.session.set_render_job_host(Some(host)).unwrap(); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + setups::load(&mut h.app); + h.app.cam = camera; + assert_eq!(image_params(&h.app).unwrap(), request); + let capture = h.app.session.execute("render.start", &request).unwrap(); + let id = serde_json::from_value(capture["job"].clone()).unwrap(); + let again = h.app.session.render_job_handle(id).unwrap(); + assert_eq!(again.wait_timeout(std::time::Duration::from_secs(30)).unwrap().progress.phase, Phase::Completed); + let image = again.frame().unwrap().unwrap(); + assert_eq!(image.png(), png); + assert_eq!(image.linear_exr().unwrap(), exr); + assert_eq!(h.app.session.doc.features, doc.features); + assert_eq!(h.app.session.doc.materials, doc.materials); +} + +#[test] +fn atmosphere_numeric_pointer_edit_keeps_proven_light_mute_solo_selection_and_its_undo_edge() { + let mut h = cpu_volume_editor_fixture(true, Some(0.001)); + let mut setup = h.app.session.doc.render.setups["Studio"].clone(); + if let Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options, .. }) = &mut setup.job { + options.lights = Some(vec![solidcraft_engine::render::job::DirectionalLightOptions { + direction: [0.0, 0.0, 1.0], + color: [1.0, 1.0, 1.0], + intensity: 2.0, + }]); + } + h.app.run("render.settings.set", json!({"name":"Studio","set":setup})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.raytrace.path.is_some()); + assert_eq!(h.app.render_workspace.view.studio.volume.unwrap().extinction_per_mm, 0.001); + let id = light::rows(&h.app).unwrap()[0].id.clone(); + h.app.run("render.lights.mute", json!({"id":id,"mute":true})).unwrap(); + h.app.run("render.lights.solo", json!({"id":id,"solo":true})).unwrap(); + h.app.render_workspace.view.selection = RenderSelection::Light(id.clone()); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + let rows = light::rows(&h.app).unwrap(); + let before = h.app.session.doc.render.setups["Studio"].clone(); + let undo = h.app.session.undo.len(); + volume_editor_number(&mut h, "render:volume:extinction", "0.003"); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.studio.volume.unwrap().extinction_per_mm, 0.003); + let after = h.app.session.doc.render.setups["Studio"].clone(); + for (command, expected) in [(None, &after), (Some("edit.undo"), &before), (Some("edit.redo"), &after)] { + if let Some(command) = command { + h.app.run(command, json!({})).unwrap(); + setups::sync_revision(&mut h.app); + } + assert_eq!(&h.app.session.doc.render.setups["Studio"], expected); + assert_eq!(light::rows(&h.app).unwrap(), rows); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light(id.clone())); + } + // An arbitrary same-shape replacement still has no operation proof. + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":17}})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.render_workspace.view.lights.visibility, Default::default()); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); +} + +#[test] +fn atmosphere_method_adoption_refuses_actual_image_budget_or_depth_without_partial_transfer() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + for reason in ["depth", "budget"] { + let mut h = environment_editor_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"width":1024,"height":768,"job":{"method":"gpu_path","options":{ + "environment":null,"lighting":{"environment":[0.1,0.2,0.3]},"volume":{"extinction_per_mm":0.001},"max_depth":4}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + if reason == "depth" { + h.app.render_workspace.view.max_depth = 17; + } else { + h.app.render_workspace.view.raytrace.budget = CpuBudget::Compact; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 81 }); + } + let before = setups::draft(&h.app).unwrap(); + let source = h.app.session.doc.clone(); + let camera = h.app.cam; + let raytrace = h.app.render_workspace.view.raytrace.clone(); + let volume = h.app.render_workspace.view.studio.volume; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert!(switch_volume_method(&mut h.app, ImageMethod::CpuRaytrace, true).is_err(), "{reason}"); + assert!(Arc::ptr_eq(&source, &h.app.session.doc)); + assert_eq!(setups::draft(&h.app).unwrap(), before); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.raytrace, raytrace); + assert_eq!(h.app.render_workspace.view.studio.volume, volume); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn first_atmosphere_or_indirect_pointer_commit_keeps_unsaved_default_light_identity() { + for adopt in [false, true] { + let mut h = Harness::new(); + assert!(h.app.session.doc.render.setups.is_empty()); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 12; + if !adopt { + h.app.render_workspace.view.raytrace.path = Some(Default::default()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + h.app.render_workspace.view.raytrace.primary_samples = 1; + } + light::loaded(&mut h.app); + let rows = light::rows(&h.app).unwrap(); + assert!(!rows.is_empty()); + let id = rows[0].id.clone(); + h.app.run("render.lights.mute", json!({"id":id,"mute":true})).unwrap(); + h.app.run("render.lights.solo", json!({"id":id,"solo":true})).unwrap(); + h.app.render_workspace.view.selection = RenderSelection::Light(id.clone()); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + volume_editor_frame(&mut h, vec![]); + assert!(h.app.session.doc.render.setups.is_empty(), "paint cannot create the first setup"); + volume_editor_click(&mut h, if adopt { "render:volume-enable-path" } else { "render:volume-enable" }); + assert!(h.app.session.doc.render.setups.contains_key("Studio")); + assert!(h.app.render_workspace.view.raytrace.path.is_some()); + assert_eq!(h.app.render_workspace.view.studio.volume.is_some(), !adopt); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!(light::rows(&h.app).unwrap(), rows); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light(id)); + } +} + +#[test] +fn atmosphere_and_celestial_pointer_adoption_is_one_transaction_with_complete_cold_saved_intent() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::volume::HomogeneousVolume; + let mut h = celestial_editor_fixture(true); + let mut source = h.app.session.doc.render.setups["Studio"].clone(); + if let Some(RenderJob::GpuPath { options, .. }) = &mut source.job { + options.denoise = false; + options.volume = Some(HomogeneousVolume { extinction_per_mm: 0.003, anisotropy: -0.4, ..Default::default() }); + } + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":source.job}})).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), source); + let rows = light::rows(&h.app).unwrap(); + let id = rows[0].id.clone(); + h.app.run("render.lights.mute", json!({"id":id,"mute":true})).unwrap(); + h.app.run("render.lights.solo", json!({"id":id,"solo":true})).unwrap(); + h.app.render_workspace.view.selection = RenderSelection::Light(id.clone()); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + let camera = h.app.cam; + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for _ in 0..3 { + celestial_method_frame(&mut h, vec![]); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "paint cannot adopt any transport or effect"); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + assert!(switch_volume_method(&mut h.app, ImageMethod::CpuRaytrace, false).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + celestial_method_click(&mut h, "render:method"); + celestial_method_frame(&mut h, vec![]); + assert_eq!(crate::scenario::handle_at("render:method-cpu-volume"), crate::scenario::handle_at("render:method-cpu-indirect")); + celestial_method_click(&mut h, "render:method-cpu-volume"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.session.undo.len(), history.1 + 1, "fog, Sky, Sun and transport publish in one command"); + assert_eq!(h.app.cam, camera); + assert_eq!(light::rows(&h.app).unwrap(), rows); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light(id.clone())); + let cpu = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &cpu.job else { panic!("CPU expected") }; + let Some(RenderJob::GpuPath { options: gpu, .. }) = &source.job else { panic!("GPU expected") }; + assert_eq!(options.volume, gpu.volume); + assert_eq!(options.sun, gpu.lighting.unwrap().sun); + assert_eq!(options.sky, gpu.environment); + assert_eq!(options.lens, gpu.lens); + assert_eq!(options.path.unwrap().max_depth, 4); + assert_eq!(options.progressive.unwrap(), Default::default()); + assert!(options.shadows && !options.denoise && options.output.as_ref().unwrap().linear_exr); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["sun"]["radiance"], json!([0.0, 0.0, 0.0])); + let undo = h.app.session.undo.len(); + volume_editor_number(&mut h, "render:volume:extinction", "0.006"); + let changed = setups::snapshot(&h.app).unwrap(); + let mut expected = cpu.clone(); + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut expected.job { + options.volume.as_mut().unwrap().extinction_per_mm = 0.006; + } + assert_eq!(changed, expected, "a numeric Atmosphere edit leaves finite Sun, full Sky, lens and output intact"); + assert_eq!(h.app.session.undo.len(), undo + 1); + for (command, expected) in [(None, &changed), (Some("edit.undo"), &cpu), (Some("edit.redo"), &changed)] { + if let Some(command) = command { + h.app.run(command, json!({})).unwrap(); + setups::sync_revision(&mut h.app); + } + assert_eq!(&setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light(id.clone())); + } + switch_celestial_method(&mut h.app, ImageMethod::GpuRaytrace, false).unwrap(); + let mut expected_gpu = source.clone(); + if let Some(RenderJob::GpuPath { options, .. }) = &mut expected_gpu.job { + options.volume.as_mut().unwrap().extinction_per_mm = 0.006; + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected_gpu); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + switch_celestial_method(&mut h.app, ImageMethod::CpuRaytrace, false).unwrap(); + assert_eq!(setups::snapshot(&h.app).unwrap(), changed); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + let mut cold = Harness::new(); + cold.app.session = Session::new(reopened); + reset_document(&mut cold.app); + setups::load(&mut cold.app); + cold.app.cam = camera; + let before = cold.app.session.doc.clone(); + let history = (cold.app.session.revision, cold.app.session.undo.len(), cold.app.session.redo.len()); + for _ in 0..3 { + volume_editor_frame(&mut cold, vec![]); + environment_editor_frame(&mut cold, vec![]); + } + assert_eq!(setups::snapshot(&cold.app).unwrap(), changed); + assert_eq!(image_request(&cold.app).unwrap()["settings"]["job"], json!(changed.job)); + assert!(Arc::ptr_eq(&before, &cold.app.session.doc)); + assert_eq!(history, (cold.app.session.revision, cold.app.session.undo.len(), cold.app.session.redo.len())); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn clicked_cpu_atmosphere_sun_sky_start_and_cold_saved_capture_keep_identical_png_and_raw_master() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{CpuHost, Phase, volume::HomogeneousVolume}; + let mut h = celestial_editor_fixture(false); + let mut saved = h.app.session.doc.render.setups["Studio"].clone(); + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut saved.job { + options.denoise = false; + options.volume = Some(HomogeneousVolume { + min_mm: [-10.0; 3], + max_mm: [10.0; 3], + extinction_per_mm: 0.03, + scattering_albedo: [0.25, 0.5, 0.75], + anisotropy: 0.2, + }); + } + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":saved.job}})).unwrap(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + setups::load(&mut h.app); + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("Combined Atmosphere/Sun/Sky Start test requires raytrace-cpu"); + return; + } + h.app.render_workspace.view.live_paused = true; + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + inspector::select_editor(&mut h.app, inspector::Editor::Output); + h.frames(3); + let camera = h.app.cam; + let source = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = image_params(&h.app).unwrap(); + let check = h.app.session.execute("render.preflight", &request).unwrap(); + assert_eq!(check["request"]["raytrace"]["volume"], json!(h.app.render_workspace.view.studio.volume)); + assert_eq!(check["request"]["raytrace"]["sun"], json!(h.app.render_workspace.view.studio.sun)); + assert_eq!(check["request"]["raytrace"]["sky"]["rotation_rad"], 0.731); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let terminal = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(terminal.progress.phase, Phase::Completed, "{:?}", terminal.error); + let frame = handle.frame().unwrap().unwrap(); + let expected = (frame.png().to_vec(), frame.linear_exr().unwrap().to_vec()); + assert!(!expected.0.is_empty() && !expected.1.is_empty()); + assert!(Arc::ptr_eq(&source, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + h.app.session.set_render_job_host(Some(host)).unwrap(); + reset_document(&mut h.app); + h.app.render_workspace.view.live_paused = true; + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera, "cold Render entry restores the one saved physical camera without an override"); + assert_eq!(image_params(&h.app).unwrap(), request); + inspector::select_editor(&mut h.app, inspector::Editor::Output); + h.frames(3); + h.step(&json!({"click":{"handle":"render:stage:render.start"}})).unwrap(); + let handle = h.app.session.render_job_handle(h.app.render_workspace.view.job.unwrap()).unwrap(); + let terminal = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(terminal.progress.phase, Phase::Completed, "{:?}", terminal.error); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!((frame.png().to_vec(), frame.linear_exr().unwrap().to_vec()), expected); + assert_eq!(h.app.session.doc.features, source.features); + assert_eq!(h.app.session.doc.materials, source.materials); + assert_eq!(h.app.session.doc.render.setups["Studio"], source.render.setups["Studio"]); +} + +#[test] +fn celestial_and_volume_conversion_does_not_reactivate_a_dormant_sun_in_a_disabled_gpu_rig() { + use solidcraft_engine::doc::render_settings::RenderJob; + for volume in [false, true] { + let mut h = celestial_editor_fixture(true); + h.app.render_workspace.view.studio.denoise = false; + if volume { + h.app.render_workspace.view.studio.volume = Some(Default::default()); + } + assert!(h.app.render_workspace.view.studio.sun_enabled); + let dormant = h.app.render_workspace.view.studio.sun; + h.app.render_workspace.view.studio.lighting_enabled = false; + let gpu = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::GpuPath { options, .. }) = &gpu.job else { panic!("GPU expected") }; + assert!(options.lighting.is_none(), "the valid GPU draft emits no Sun from a disabled rig"); + assert!(light::rows(&h.app).unwrap().is_empty()); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let mut prospective = h.app.render_workspace.view.clone(); + prospective.raytrace.path = Some(Default::default()); + prospective.raytrace.progressive = Some(Default::default()); + prospective.raytrace.shadows = true; + light::celestial_method(&h.app, &mut prospective, ImageMethod::CpuRaytrace).unwrap(); + assert!(!prospective.studio.sun_enabled); + assert!(prospective.raytrace.sun.is_none()); + assert_eq!(prospective.studio.sun, dormant, "inactive authored numerical controls remain available"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + switch_celestial_method(&mut h.app, ImageMethod::CpuRaytrace, true).unwrap(); + let cpu = setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options, .. }) = &cpu.job else { panic!("CPU expected") }; + assert!(options.sun.is_none()); + assert_eq!(options.volume.is_some(), volume); + assert!(light::rows(&h.app).unwrap().is_empty()); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert!(params["raytrace"].get("sun").is_none(), "runtime lowering must not resurrect the disabled source either"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_preparation_fixture( + disconnect_retirement: bool, +) -> (Harness, solidcraft_engine::render::job::CpuHost, std::sync::mpsc::SyncSender<()>, std::sync::mpsc::Receiver, std::sync::mpsc::Receiver<()>) +{ + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":10,"width":20,"height":3})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host.clone()); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.live_paused = true; + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.render_workspace.view.draft.width = 3; + h.app.render_workspace.view.draft.height = 2; + h.frames(3); + h.app.run("render.scene", json!({})).unwrap(); + h.app.apply_off_thread = Some(std::time::Duration::ZERO); + h.app.preferences.agent_off_thread = false; + let (gate, receiver) = std::sync::mpsc::sync_channel(1); + h.app.apply_gate = Some(Arc::new(std::sync::Mutex::new(receiver))); + let (ready, ready_receiver) = std::sync::mpsc::sync_channel(1); + let (retired, retired_receiver) = std::sync::mpsc::sync_channel(1); + prepare::test_configure(&mut h.app, ready, retired, disconnect_retirement); + assert!(prepare::enabled(&h.app), "native rendering cannot depend on the agent geometry preference"); + (h, host, gate, ready_receiver, retired_receiver) +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_preparation_wait(h: &mut Harness) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while prepare::busy(&h.app) { + prepare::tick(&mut h.app, &h.ctx); + assert!(std::time::Instant::now() < deadline, "preparation did not retire: {}", prepare::inspect(&h.app)); + std::thread::yield_now(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_preparation_start_worker(h: &mut Harness, ready: &std::sync::mpsc::Receiver) { + prepare::tick(&mut h.app, &h.ctx); + assert!(ready.recv_timeout(std::time::Duration::from_secs(30)).unwrap(), "the real capsule must be proved before the deterministic delay"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_check_defers_original_control_reply_until_worker_releases_real_capture() { + use crate::control::ControlRequest; + use solidcraft_engine::schema::ParamCheck; + let (mut h, host, gate, ready, retired) = native_preparation_fixture(false); + let request = image_params(&h.app).unwrap(); + let expected = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + h.app.session.param_check = ParamCheck::Off; + let (control, reply) = ControlRequest::new("engine.execute", json!({"command":"render.preflight","params":request,"param_check":"warn"})); + h.app.run_control(&h.ctx, control); + native_preparation_start_worker(&mut h, &ready); + assert!(host.admitted_bytes() > 0, "delayed proof owns actual billed capture resources"); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty), "no fake pending success"); + let (inspect_request, inspect_reply) = ControlRequest::new("ui.inspect", json!({})); + h.app.run_control(&h.ctx, inspect_request); + assert_eq!(inspect_reply.try_recv().unwrap()["ok"], true, "other native controls remain responsive"); + assert_eq!(prepare::inspect(&h.app)["kind"], "render.preflight"); + assert_eq!(prepare::inspect(&h.app)["preparing"], true); + assert!(h.app.render_workspace.view.job.is_none()); + gate.send(()).unwrap(); + native_preparation_wait(&mut h); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let reply = reply.try_recv().unwrap(); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["param_check"], "warn"); + assert_eq!(reply["result"], expected, "same existing strict preflight contract, no new pending shape"); + assert_eq!(h.app.session.param_check, ParamCheck::Off); + assert!(h.app.render_workspace.view.inspector.checked.is_some()); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_render_commits_only_real_registry_identity_and_retirement_does_not_cancel_it() { + use solidcraft_engine::render::job::Phase; + let (mut h, host, gate, ready, retired) = native_preparation_fixture(false); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + native_preparation_start_worker(&mut h, &ready); + assert!(h.app.render_workspace.view.job.is_none(), "scratch capture cannot mint a job"); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert!(host.admitted_bytes() > 0); + gate.send(()).unwrap(); + native_preparation_wait(&mut h); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let job = h.app.render_workspace.view.job.expect("explicit UI Start follows the committed real-session job"); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.status().unwrap().job, job); + assert!(h.app.render_workspace.view.result); + assert!(h.app.render_workspace.view.follow_job); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some(h.app.render_workspace.view.name.as_str())); + for _ in 0..10_000 { + if handle.status().unwrap().progress.phase.terminal() { + break; + } + host.pump(4096).unwrap(); + } + assert_eq!(handle.status().unwrap().progress.phase, Phase::Completed, "retiring Prepared must not cancel the transferred Start token"); + assert!(handle.frame().unwrap().is_some()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + drop(handle); + drop(h); + assert_eq!(host.admitted_bytes(), 0, "normal app teardown releases real retained ownership"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_preparation_rejects_changed_sources_and_keeps_capture_until_worker_ack() { + use crate::control::ControlRequest; + enum Change { + Camera, + Draft, + Visibility, + Host, + Document, + } + for (changed, change) in [ + ("camera", Change::Camera), + ("draft", Change::Draft), + ("visibility", Change::Visibility), + ("host", Change::Host), + ("document", Change::Document), + ] { + let (mut h, host, gate, ready, retired) = native_preparation_fixture(false); + let request = image_params(&h.app).unwrap(); + let (control, reply) = ControlRequest::new("engine.execute", json!({"command":"render.start","params":request})); + h.app.run_control(&h.ctx, control); + native_preparation_start_worker(&mut h, &ready); + let captured = host.admitted_bytes(); + assert!(captured > 0); + match change { + Change::Camera => h.app.cam.yaw += 0.3, + Change::Draft => h.app.render_workspace.view.draft.width = 4, + Change::Visibility => h.app.session.visibility.hidden_bodies.push("Body1".into()), + Change::Host => h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(), + Change::Document => { + h.app.session = Session::default(); + reset_document(&mut h.app); + } + } + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + prepare::tick(&mut h.app, &h.ctx); + assert!(prepare::busy(&h.app), "{changed}: cancellation is not release"); + assert_eq!(host.admitted_bytes(), captured, "{changed}: source changes do not fake freed capture credit"); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + gate.send(()).unwrap(); + native_preparation_wait(&mut h); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let reply = reply.try_recv().unwrap(); + assert_eq!(reply["ok"], false, "{changed}: {reply}"); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_preparation_actual_cancel_keeps_billed_owner_until_worker_cleanup() { + let (mut h, host, gate, ready, retired) = native_preparation_fixture(false); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + native_preparation_start_worker(&mut h, &ready); + let bytes = host.admitted_bytes(); + h.frames(2); + assert!(crate::scenario::rect_of("render:preparation-cancel").is_some()); + h.step(&json!({"click":{"handle":"render:preparation-cancel"}})).unwrap(); + assert_eq!(prepare::inspect(&h.app)["cancelled"], h.app.tr("render.preparation_cancelled")); + assert!(prepare::busy(&h.app)); + assert_eq!(host.admitted_bytes(), bytes); + assert!(ribbon::action_ready(&h.app, "render.start").is_err()); + gate.send(()).unwrap(); + native_preparation_wait(&mut h); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert!(ribbon::action_ready(&h.app, "render.start").is_ok()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_preparation_disconnected_retirement_holds_unavailable_owner_across_document_reset() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, _retired) = native_preparation_fixture(true); + let request = image_params(&h.app).unwrap(); + let (control, reply) = ControlRequest::new("engine.execute", json!({"command":"render.preflight","params":request})); + h.app.run_control(&h.ctx, control); + native_preparation_start_worker(&mut h, &ready); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + gate.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + prepare::tick(&mut h.app, &h.ctx); + if !prepare::inspect(&h.app)["unavailable"].is_null() { + break; + } + assert!(std::time::Instant::now() < deadline); + std::thread::yield_now(); + } + assert_eq!(reply.try_recv().unwrap()["ok"], false); + assert!(prepare::busy(&h.app)); + assert_eq!(host.admitted_bytes(), bytes, "disconnected cleanup keeps real credit owned"); + assert!(prepare::begin_ui(&mut h.app, solidcraft_engine::render_preparation::Kind::Check, json!({})).is_err()); + h.app.session = Session::default(); + reset_document(&mut h.app); + prepare::tick(&mut h.app, &h.ctx); + assert!(prepare::busy(&h.app)); + assert_eq!(host.admitted_bytes(), bytes, "tab/document replacement cannot destroy unavailable ownership on the window"); + drop(h); + assert_eq!(host.admitted_bytes(), 0, "true app teardown runs ordinary destructors"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_preparation_window_drop_returns_undelivered_capture_to_its_same_worker() { + let (mut h, host, gate, ready, retired) = native_preparation_fixture(false); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + native_preparation_start_worker(&mut h, &ready); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + drop(h); + assert_eq!(host.admitted_bytes(), bytes, "the delayed worker still owns its capture after window teardown"); + gate.send(()).unwrap(); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0, "closed ready receiver destroys the returned capsule on its original worker"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_preparation_keeps_request_vfs_scope_on_proof_and_window_commit() { + use crate::control::ControlRequest; + use std::sync::Mutex; + let (mut h, host, gate, ready, retired) = native_preparation_fixture(false); + let seen = Arc::new(Mutex::new(Vec::new())); + let recorded = seen.clone(); + let allowed = h.dir.join("allowed-read.hdr").to_string_lossy().into_owned(); + let rejected = h.dir.parent().unwrap().join("outside-preparation-scope.hdr").to_string_lossy().into_owned(); + h.app.session.set_command_check(Some(Arc::new(move |id, _, _| { + if id == "render.preflight" { + let scope = solidcraft_engine::io::vfs::current_scope().expect("original native scope must follow both phases"); + assert!(scope.check(&allowed).is_ok()); + assert!(scope.check(&rejected).is_err()); + recorded.lock().unwrap().push(std::thread::current().id()); + } + Ok(()) + }))); + let request = image_params(&h.app).unwrap(); + let (control, reply) = ControlRequest::new("engine.execute", json!({"command":"render.preflight","params":request,"allow_paths":[h.dir]})); + let window = std::thread::current().id(); + h.app.run_control(&h.ctx, control); + native_preparation_start_worker(&mut h, &ready); + gate.send(()).unwrap(); + native_preparation_wait(&mut h); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(reply.try_recv().unwrap()["ok"], true); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "host policy runs once on preparation and once on real-session commit"); + assert_ne!(seen[0], window); + assert_eq!(seen[1], window); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_control_does_not_synchronously_hide_render_preparation_inside_engine_batch() { + use crate::control::ControlRequest; + let (mut h, host, _gate, _ready, _retired) = native_preparation_fixture(false); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for method in ["engine.batch", "engine.script"] { + let (control, reply) = ControlRequest::new( + method, + json!({"commands":[{"command":"solid.box","params":{"length":1}},{"command":"render.preflight"}],"param_check":"strict"}), + ); + h.app.run_control(&h.ctx, control); + let reply = reply.try_recv().unwrap(); + assert_eq!(reply["ok"], false, "{method}: {reply}"); + assert_eq!(reply["param_check"], "strict"); + assert!(reply["error"].as_str().unwrap().contains("individual engine.execute")); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(!prepare::busy(&h.app)); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_preparation_failed_input_delivery_retains_source_until_true_teardown() { + let (mut h, host, _gate, _ready, _retired) = native_preparation_fixture(false); + let document = Arc::downgrade(&h.app.session.doc); + let model = Arc::downgrade(&h.app.session.model.state()); + prepare::test_disconnect_input(&mut h.app); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + prepare::tick(&mut h.app, &h.ctx); + prepare::tick(&mut h.app, &h.ctx); + assert!(!prepare::inspect(&h.app)["unavailable"].is_null()); + assert!(prepare::busy(&h.app)); + assert_eq!(host.admitted_bytes(), 0, "proof never ran, so no renderer lease was invented"); + h.app.session = Session::default(); + reset_document(&mut h.app); + prepare::tick(&mut h.app, &h.ctx); + assert!(document.upgrade().is_some(), "returned heavy input remains in the bounded unavailable owner"); + assert!(model.upgrade().is_some()); + assert!(prepare::begin_ui(&mut h.app, solidcraft_engine::render_preparation::Kind::Check, json!({})).is_err()); + drop(h); + assert!(document.upgrade().is_none(), "true app teardown destroys the unavailable input normally"); + assert!(model.upgrade().is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn headless_render_checks_retain_the_existing_strict_synchronous_api() { + let (mut h, host, _gate, ready, _retired) = native_preparation_fixture(false); + h.app.apply_off_thread = None; + assert!(!prepare::enabled(&h.app)); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert!(h.app.render_workspace.view.inspector.checked.is_some()); + assert!(!prepare::busy(&h.app)); + assert_eq!(ready.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + assert_eq!(host.admitted_bytes(), 0); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_batch_fixture( + disconnect: bool, +) -> ( + Harness, + solidcraft_engine::render::job::CpuHost, + std::sync::mpsc::SyncSender<()>, + std::sync::mpsc::Receiver, + std::sync::mpsc::Receiver<()>, + [Camera; 2], +) { + let (mut h, host, gate, ready, retired) = native_preparation_fixture(disconnect); + let first = h.app.cam; + let second = Camera { yaw: first.yaw + 0.4, ..first }; + for (name, camera, width, height) in [("A worker shot", first, 5, 4), ("B worker shot", second, 9, 8)] { + h.app + .run("render.settings.set", json!({"name":name,"set":{"camera":camera,"width":width,"height":height,"job":{"method":"raster"}}})) + .unwrap(); + } + h.app.render_workspace.view.draft.width = 3; + h.app.render_workspace.view.draft.height = 2; + h.app.render_workspace.view.draft.background = [7, 19, 31]; + (h, host, gate, ready, retired, [first, second]) +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_batch_wait(h: &mut Harness, predicate: impl Fn(&SolveApp) -> bool) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + prepare::tick(&mut h.app, &h.ctx); + if predicate(&h.app) { + return; + } + assert!(std::time::Instant::now() < deadline, "batch did not reach expected state: {}", prepare::inspect_batches(&h.app)); + std::thread::yield_now(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_batch_ready(h: &mut Harness, ready: &std::sync::mpsc::Receiver) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + prepare::tick(&mut h.app, &h.ctx); + match ready.try_recv() { + Ok(value) => { + assert!(value); + return; + } + Err(std::sync::mpsc::TryRecvError::Empty) => {} + Err(e) => panic!("proof hook disconnected: {e}"), + } + assert!(std::time::Instant::now() < deadline, "batch worker never prepared an owned result: {}", prepare::inspect_batches(&h.app)); + std::thread::yield_now(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_batch_reply(h: &mut Harness, reply: &std::sync::mpsc::Receiver) -> serde_json::Value { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + prepare::tick(&mut h.app, &h.ctx); + if let Ok(value) = reply.try_recv() { + return value; + } + assert!( + std::time::Instant::now() < deadline, + "original batch sender did not receive its actual completion: {}", + prepare::inspect_batches(&h.app) + ); + std::thread::yield_now(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_batch_complete(host: &solidcraft_engine::render::job::CpuHost, job: &solidcraft_engine::render::job::JobHandle) { + for _ in 0..10_000 { + if job.status().unwrap().progress.phase.terminal() { + break; + } + host.pump(4096).unwrap(); + } + assert_eq!(job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Completed); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_defers_first_reply_then_uses_one_common_request_and_each_exact_saved_camera() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, cameras) = native_batch_fixture(false); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = image_params(&h.app).unwrap(); + let (control, reply) = + ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":request},"param_check":"strict"})); + h.app.run_control(&h.ctx, control); + native_batch_ready(&mut h, &ready); + assert!(host.admitted_bytes() > 0); + assert!(h.app.session.render_queue_state().job.is_none(), "no scratch or serial-zero identity may stand in for a prepared shot"); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + gate.send(()).unwrap(); + let answer = native_batch_reply(&mut h, &reply); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(answer, json!({"ok":true,"result":{"queued":2},"param_check":"strict"})); + let first = h.app.session.render_queue_state().job.unwrap(); + let first_handle = h.app.session.render_job_handle(first).unwrap(); + let first_status = first_handle.status().unwrap(); + assert_eq!(first_status.request.camera, cameras[0]); + assert_eq!((first_status.request.width, first_status.request.height, first_status.request.background), (3, 2, [7, 19, 31])); + assert_eq!(h.app.render_workspace.view.job, Some(first)); + native_batch_complete(&host, &first_handle); + native_batch_ready(&mut h, &ready); + assert_eq!(h.app.session.render_queue_state().job, Some(first), "next proof retains the last real identity instead of inventing a preparing job"); + assert!(prepare::inspect_batches(&h.app)["worker"]["preparing"].as_bool().unwrap()); + gate.send(()).unwrap(); + native_batch_wait(&mut h, |app| { + app.session.render_queue_state().job.is_some_and(|job| job != first) && prepare::inspect_batches(app)["worker"].is_null() + }); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let second = h.app.session.render_queue_state().job.unwrap(); + let second_handle = h.app.session.render_job_handle(second).unwrap(); + let second_status = second_handle.status().unwrap(); + assert_eq!(second_status.request.camera, cameras[1]); + assert_eq!( + (second_status.request.width, second_status.request.height, second_status.request.background), + (3, 2, [7, 19, 31]), + "saved per-shot dimensions never replace the captured common request" + ); + native_batch_complete(&host, &second_handle); + h.app.session.advance_render_batch().unwrap(); + assert_eq!((h.app.session.render_queue_state().waiting, h.app.session.render_queue_state().running), (0, 0)); + assert!(prepare::inspect_batches(&h.app)["owners"].as_array().unwrap().is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Disconnected), "the original sender is answered exactly once"); + drop(first_handle); + drop(second_handle); + drop(h); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_scene_all_shots_pointer_prepares_without_submitting_during_paint() { + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + h.frames(3); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + assert!(prepare::inspect_batches(&h.app)["owners"].as_array().unwrap().is_empty()); + assert!(h.app.session.render_queue_state().job.is_none()); + h.step(&json!({"click":{"handle":"render:scene:all-shots"}})).unwrap(); + native_batch_ready(&mut h, &ready); + assert!(h.app.session.render_queue_state().job.is_none()); + assert!(host.admitted_bytes() > 0); + ribbon::perform_job(&mut h.app, "render.cancel").unwrap(); + gate.send(()).unwrap(); + native_batch_wait(&mut h, |app| prepare::inspect_batches(app)["owners"].as_array().unwrap().is_empty()); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + assert!(h.app.session.render_queue_state().job.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_control_cancel_before_first_job_is_truthful_and_waits_for_cleanup() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let request = image_params(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let (control, reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":request}})); + h.app.run_control(&h.ctx, control); + native_batch_ready(&mut h, &ready); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + let (cancel, cancel_reply) = ControlRequest::new("engine.execute", json!({"command":"render.cancel","params":{},"param_check":"strict"})); + h.app.run_control(&h.ctx, cancel); + let cancelled = cancel_reply.try_recv().unwrap(); + assert_eq!(cancelled["ok"], true); + assert_eq!(cancelled["param_check"], "strict"); + assert_eq!(cancelled["result"]["preparing"], true); + assert_eq!(cancelled["result"]["cancel_requested"], true); + assert!(cancelled["result"].get("job").is_none()); + assert!(h.app.session.render_queue_state().job.is_none()); + assert_eq!(host.admitted_bytes(), bytes, "cancel acknowledgement is not resource release"); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + gate.send(()).unwrap(); + let answer = native_batch_reply(&mut h, &reply); + assert_eq!(answer["ok"], false); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_finishes_in_exact_inactive_owner_and_close_cancels_its_claim_without_adoption() { + use crate::control::ControlRequest; + for close in [false, true] { + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let owner = h.app.session.uid; + let (control, reply) = + ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":image_params(&h.app).unwrap()}})); + h.app.run_control(&h.ctx, control); + native_batch_ready(&mut h, &ready); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + let other = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + if close { + crate::documents::close(&mut h.app, 0, true); + } + gate.send(()).unwrap(); + let answer = native_batch_reply(&mut h, &reply); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(answer["ok"], !close, "{answer}"); + assert!(h.app.render_workspace.view.job.is_none(), "inactive completion cannot adopt its source into the visible document"); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + if !close { + let session = crate::documents::render_owner(&h.app, owner).unwrap(); + let job = session.render_queue_state().job.unwrap(); + let handle = session.render_job_handle(job).unwrap(); + assert!(handle.status().unwrap().job.session != 0); + native_batch_complete(&host, &handle); + crate::documents::close(&mut h.app, 0, true); + native_batch_wait(&mut h, |app| prepare::inspect_batches(app)["owners"].as_array().unwrap().is_empty()); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + drop(handle); + } + drop(h); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_plan_credit_releases_only_after_background_plan_retirement() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let (control, reply) = + ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":image_params(&h.app).unwrap()}})); + h.app.run_control(&h.ctx, control); + native_batch_ready(&mut h, &ready); + gate.send(()).unwrap(); + assert_eq!(native_batch_reply(&mut h, &reply)["ok"], true); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let job = h.app.session.render_queue_state().job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + native_batch_complete(&host, &handle); + let plan = prepare::inspect_batches(&h.app)["owners"][0]["retained_plan_bytes"].as_u64().unwrap(); + let bytes = host.admitted_bytes(); + assert!(plan > 0 && bytes >= plan); + h.app.run("render.cancel", json!({"job":job})).unwrap(); + assert_eq!(host.admitted_bytes(), bytes, "metadata cancellation cannot drop funded plan backing on the window"); + native_batch_wait(&mut h, |app| prepare::inspect_batches(app)["owners"].as_array().unwrap().is_empty()); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), bytes - plan, "only the independently funded shared plan retires; real retained final remains owned"); + assert!(handle.frame().unwrap().is_some()); + drop(handle); + drop(h); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_and_individual_check_share_one_preparation_lane_without_deadlock() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let request = image_params(&h.app).unwrap(); + let (batch, batch_reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":request}})); + h.app.run_control(&h.ctx, batch); + native_batch_ready(&mut h, &ready); + let (check, check_reply) = ControlRequest::new("engine.execute", json!({"command":"render.preflight","params":request})); + h.app.run_control(&h.ctx, check); + for _ in 0..8 { + prepare::tick(&mut h.app, &h.ctx); + } + assert_eq!(ready.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty), "the second proof cannot start while the batch worker owns the lane"); + assert_eq!(prepare::inspect(&h.app)["waiting_for_worker"], true); + gate.send(()).unwrap(); + assert_eq!(native_batch_reply(&mut h, &batch_reply)["ok"], true); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + native_batch_ready(&mut h, &ready); + assert_eq!(check_reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + gate.send(()).unwrap(); + let checked = native_batch_reply(&mut h, &check_reply); + assert_eq!(checked["ok"], true); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let job = h.app.session.render_queue_state().job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!( + handle.status().unwrap().progress.phase, + solidcraft_engine::render::job::Phase::Queued, + "a Check cannot mint or replace the actual queued batch job" + ); + h.app.run("render.cancel", json!({"job":job})).unwrap(); + native_batch_wait(&mut h, |app| prepare::inspect_batches(app)["owners"].as_array().unwrap().is_empty()); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + drop(handle); + drop(h); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_batch_probe(h: &mut Harness, ready: &std::sync::mpsc::Receiver) -> bool { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + prepare::tick(&mut h.app, &h.ctx); + if let Ok(proved) = ready.try_recv() { + return proved; + } + assert!( + std::time::Instant::now() < deadline, + "preparation probe did not return: {} / {}", + prepare::inspect(&h.app), + prepare::inspect_batches(&h.app) + ); + std::thread::yield_now(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_replacement_keeps_first_priority_and_cancels_old_epoch_only_after_successful_proof() { + use crate::control::ControlRequest; + for valid in [false, true] { + let (mut h, host, gate, ready, retired, cameras) = native_batch_fixture(false); + let request = image_params(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let (batch, batch_reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":request}})); + h.app.run_control(&h.ctx, batch); + let mut replacement = request.clone(); + replacement["replace"] = json!(true); + if !valid { + replacement["settings"]["width"] = json!(0); + } + let (start, start_reply) = ControlRequest::new("engine.execute", json!({"command":"render.start","params":replacement,"param_check":"off"})); + h.app.run_control(&h.ctx, start); + native_batch_ready(&mut h, &ready); + assert_eq!(prepare::inspect_batches(&h.app)["worker"]["preparing"], true, "the original first batch front retains first-action priority"); + assert_eq!(start_reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + gate.send(()).unwrap(); + assert_eq!(native_batch_reply(&mut h, &batch_reply)["result"], json!({"queued":2})); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let original = h.app.session.render_queue_state().job.unwrap(); + let original_handle = h.app.session.render_job_handle(original).unwrap(); + assert_eq!( + native_batch_probe(&mut h, &ready), + valid, + "replacement failure must come from actual worker validation, not a hidden synchronous branch" + ); + assert_eq!( + original_handle.status().unwrap().progress.phase, + solidcraft_engine::render::job::Phase::Queued, + "replacement admission/proof cannot cancel the original job" + ); + assert_eq!(h.app.session.render_queue_state().waiting, 1); + assert_eq!(ready.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty), "later batch fronts stay paused during replacement proof"); + gate.send(()).unwrap(); + let result = native_batch_reply(&mut h, &start_reply); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(result["ok"], valid, "{result}"); + if valid { + let job: solidcraft_engine::render::job::JobId = serde_json::from_value(result["result"]["job"].clone()).unwrap(); + assert_ne!(job, original); + assert!(h.app.session.render_queue_state().job.is_none()); + let handle = h.app.session.render_job_handle(job).unwrap(); + native_batch_complete(&host, &handle); + assert_eq!(original_handle.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Cancelled); + native_batch_wait(&mut h, |app| prepare::inspect_batches(app)["owners"].as_array().unwrap().is_empty()); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + drop(handle); + } else { + assert_eq!(h.app.session.render_queue_state().job, Some(original)); + assert_eq!(h.app.session.render_queue_state().waiting, 1, "failed replacement preserves the original common plan and first actual job"); + assert_eq!(original_handle.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + native_batch_complete(&host, &original_handle); + native_batch_ready(&mut h, &ready); + gate.send(()).unwrap(); + native_batch_wait(&mut h, |app| { + app.session.render_queue_state().job.is_some_and(|job| job != original) && prepare::inspect_batches(app)["worker"].is_null() + }); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + let job = h.app.session.render_queue_state().job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.status().unwrap().request.camera, cameras[1], "the original second saved camera resumes unchanged"); + native_batch_complete(&host, &handle); + h.app.session.advance_render_batch().unwrap(); + drop(handle); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + drop(original_handle); + drop(h); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_document_close_drains_first_proof_and_raw_replacement_without_minting_either() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let request = image_params(&h.app).unwrap(); + let (batch, batch_reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":request}})); + h.app.run_control(&h.ctx, batch); + native_batch_ready(&mut h, &ready); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + let mut replacement = request; + replacement["replace"] = json!(true); + let (start, start_reply) = ControlRequest::new("engine.execute", json!({"command":"render.start","params":replacement})); + h.app.run_control(&h.ctx, start); + assert_eq!(ready.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + crate::documents::close(&mut h.app, 0, true); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + prepare::tick(&mut h.app, &h.ctx); + assert_eq!(start_reply.try_recv().unwrap()["ok"], false, "the bounded raw replacement has no capture/credit to pretend it submitted"); + assert_eq!(batch_reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + assert_eq!(host.admitted_bytes(), bytes, "document close is cancellation intent, not proof of worker cleanup"); + gate.send(()).unwrap(); + assert_eq!(native_batch_reply(&mut h, &batch_reply)["ok"], false); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + assert!(prepare::inspect_batches(&h.app)["owners"].as_array().unwrap().is_empty()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_disconnected_retirement_holds_credit_and_never_cleanup_cancels_a_committed_job() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, _retired, _) = native_batch_fixture(true); + let owner = h.app.session.uid; + let (batch, reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":image_params(&h.app).unwrap()}})); + h.app.run_control(&h.ctx, batch); + native_batch_ready(&mut h, &ready); + gate.send(()).unwrap(); + let response = native_batch_reply(&mut h, &reply); + assert_eq!(response["ok"], true, "a committed real first job retains its truthful identity despite retirement failure"); + assert_eq!(response["result"], json!({"queued":2})); + assert!(!prepare::inspect_batches(&h.app)["worker"]["unavailable"].is_null()); + let job = h.app.session.render_queue_state().job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + native_batch_complete(&host, &handle); + let held = host.admitted_bytes(); + assert!(held > 0); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_ne!(h.app.session.uid, owner); + let (check, checked) = ControlRequest::new("engine.execute", json!({"command":"render.preflight","params":{}})); + h.app.run_control(&h.ctx, check); + assert_eq!(checked.try_recv().unwrap()["ok"], false, "unavailable global lane cannot start another proof in a different document"); + assert!(prepare::begin_batch_ui(&mut h.app, json!({})).is_err()); + prepare::tick(&mut h.app, &h.ctx); + assert_eq!(host.admitted_bytes(), held, "tab replacement cannot fake a released plan or source"); + assert_eq!(handle.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Completed); + drop(handle); + drop(h); + assert_eq!(host.admitted_bytes(), 0, "only true app teardown runs the unavailable owners' destructors"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_no_job_cancel_preserves_schema_scope_and_embedding_host_refusals() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let (batch, reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":{"request":image_params(&h.app).unwrap()}})); + h.app.run_control(&h.ctx, batch); + native_batch_ready(&mut h, &ready); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + for control in [ + json!({"command":"render.cancel","params":{},"param_check":"unknown"}), + json!({"command":"render.cancel","params":{},"allow_paths":"not-an-array"}), + json!({"command":"render.cancel","params":{"unknown_cancel_field":true},"param_check":"strict"}), + ] { + let (cancel, cancelled) = ControlRequest::new("engine.execute", control); + h.app.run_control(&h.ctx, cancel); + assert_eq!(cancelled.try_recv().unwrap()["ok"], false); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + assert_eq!(host.admitted_bytes(), bytes); + } + h.app + .session + .set_command_check(Some(Arc::new(|id, _, _| if id == "render.cancel" { Err("embedding host refuses Cancel".into()) } else { Ok(()) }))); + let (cancel, cancelled) = ControlRequest::new("engine.execute", json!({"command":"render.cancel","params":{}})); + h.app.run_control(&h.ctx, cancel); + assert!(cancelled.try_recv().unwrap()["error"].as_str().unwrap().contains("embedding host refuses Cancel")); + assert!(prepare::inspect_batches(&h.app)["owners"][0]["cancelled"].is_null()); + assert_eq!(host.admitted_bytes(), bytes, "refused control cannot touch the live claim or pretend it retired"); + h.app.session.set_command_check(None); + ribbon::perform_job(&mut h.app, "render.cancel").unwrap(); + gate.send(()).unwrap(); + assert_eq!(native_batch_reply(&mut h, &reply)["ok"], false); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_batch_fixed_owner_slots_include_closed_documents_until_retirement() { + use crate::control::ControlRequest; + let (mut h, host, gate, ready, retired, _) = native_batch_fixture(false); + let request = json!({"request":{"settings":{"width":3,"height":2,"job":{"method":"raster"}}}}); + let (first, first_reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":request})); + h.app.run_control(&h.ctx, first); + native_batch_ready(&mut h, &ready); + let mut senders = vec![first_reply]; + for _ in 1..crate::documents::MAX_OPEN { + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + h.app.run("render.settings.set", json!({"name":"A","set":{"width":3,"height":2,"job":{"method":"raster"}}})).unwrap(); + let (batch, reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":request})); + h.app.run_control(&h.ctx, batch); + assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)); + senders.push(reply); + } + assert_eq!(prepare::inspect_batches(&h.app)["owners"].as_array().unwrap().len(), 32); + let bytes = host.admitted_bytes(); + assert!(bytes > 0); + crate::documents::close(&mut h.app, 1, true); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + h.app.run("render.settings.set", json!({"name":"A","set":{"width":3,"height":2,"job":{"method":"raster"}}})).unwrap(); + let (extra, extra_reply) = ControlRequest::new("engine.execute", json!({"command":"render.batch","params":request})); + h.app.run_control(&h.ctx, extra); + let refused = extra_reply.try_recv().unwrap(); + assert_eq!(refused["ok"], false); + assert!(refused["error"].as_str().unwrap().contains(h.app.tr("render.batch_owner_limit"))); + assert_eq!( + prepare::inspect_batches(&h.app)["owners"].as_array().unwrap().len(), + 32, + "a closed owner is not a freed slot before coordinator cleanup" + ); + assert_eq!(host.admitted_bytes(), bytes, "raw owner slots cannot manufacture further renderer grants"); + drop(h); + gate.send(()).unwrap(); + retired.recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(host.admitted_bytes(), 0); + assert!( + senders.iter().all(|reply| reply.try_recv() == Err(std::sync::mpsc::TryRecvError::Disconnected)), + "true window teardown disconnects the outstanding original senders without inventing jobs" + ); +} + +#[test] +fn light_world_vector_axes_fit_the_real_narrow_inspector_without_clipping_or_paint_edits() { + for side in ["left", "right"] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1100,"height":3000})); + h.app.preferences.render_inspector_side = side.into(); + h.app.preferences.render_browser_side = if side == "left" { "right" } else { "left" }.into(); + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{}}}})).unwrap(); + setups::load(&mut h.app); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":"spot"}))).unwrap(); + light::edit( + &mut h.app, + "render.lights.set", + Some("spot:0"), + Some(json!({ + "position_mm":[-999999999.125,999999999.125,120.125],"emitted_axis":[1.0,2.0,-2.0] + })), + ) + .unwrap(); + h.app.run("view.render_select", json!({"kind":"light","id":"spot:0"})).unwrap(); + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let request = image_request(&h.app).unwrap(); + for _ in 0..2 { + h.frames(4); + for (key, label) in [("position_mm", "render.lighting_world_position"), ("emitted_axis", "render.spot_axis")] { + for (index, axis) in ["X", "Y", "Z"].iter().enumerate() { + let field = crate::scenario::rect_of(&format!("render:light:{key}:{index}")).unwrap(); + let row = crate::scenario::rect_of(&format!("dialog:control:{} {axis}", h.app.tr(label))).unwrap(); + assert!(h.ctx.content_rect().contains_rect(field), "the actual coordinate control fits the window: {side}/{key}/{axis}"); + assert!(row.contains_rect(field), "the actual response fits its painted control-column clip: {side}/{key}/{axis}"); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert_eq!(image_request(&h.app).unwrap(), request); + } + assert_eq!(gpu_lighting_request(&request)["punctual_lights"][0]["position_mm"], json!([-999999999.125, 999999999.125, 120.125])); + assert_eq!(gpu_lighting_request(&request)["punctual_lights"][0]["cone"]["emitted_axis"], json!([1.0, 2.0, -2.0])); + } +} + +fn constant_environment_frame(h: &mut Harness, events: Vec) -> String { + crate::scenario::clear_handles(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), events, ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + output.textures_delta.clear(); + text +} + +fn constant_environment_click_indirect(h: &mut Harness) { + constant_environment_frame(h, vec![]); + let rect = crate::scenario::rect_of("render:environment:enable-indirect").expect("the actual constant-source adoption button"); + assert!(rect.is_positive() && rect.left() >= 0.0 && rect.right() <= 308.0, "the action must fit the narrow inspector: {rect:?}"); + let point = rect.center(); + for pressed in [true, false] { + constant_environment_frame( + h, + vec![ + egui::Event::PointerMoved(point), + egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } +} + +#[test] +fn cpu_constant_environment_guidance_explains_legacy_reflection_and_transmission_without_paint_writes() { + use solidcraft_engine::render::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; + for reflection in [false, true] { + let mut h = cpu_volume_editor_fixture(false, None); + h.app.session.set_render_job_host(None).unwrap(); + if reflection { + h.app.render_workspace.view.raytrace.reflections = Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: "Volume subject".into(), mode: ReflectionMode::Mirror }], + ..Default::default() + }); + } + let document = h.app.session.doc.clone(); + let before = setups::draft(&h.app).unwrap(); + let options = h.app.render_workspace.view.raytrace.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for _ in 0..3 { + let text = constant_environment_frame(&mut h, vec![]); + assert!(text.contains(h.app.tr("render.cpu_constant_direct_help"))); + assert!(crate::scenario::rect_of("render:environment:enable-indirect").is_some()); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(setups::draft(&h.app).unwrap(), before); + assert_eq!(h.app.render_workspace.view.raytrace, options, "explaining selected reflection sources must never erase them"); + assert_eq!(h.app.cam, camera); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + assert!(h.app.session.render_job_host().is_none(), "painting the action must not require or install a host"); + } +} + +#[test] +fn cpu_constant_environment_pointer_indirect_adoption_is_complete_camera_neutral_one_undo_and_cold_portable() { + use solidcraft_engine::doc::render_settings::RenderJob; + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + for progressive in [None, Some(CpuProgressiveOptions { samples_per_pixel: 7, seed: 91 })] { + let mut h = cpu_volume_editor_fixture(false, Some(0.0)); + h.app.session.set_render_job_host(None).unwrap(); + let mut source = h.app.session.doc.render.setups["Studio"].clone(); + if let Some(RenderJob::CpuRaytrace { options, transparent_background }) = &mut source.job { + *transparent_background = true; + options.budget = CpuBudget::Studio; + options.progressive = progressive; + if progressive.is_some() { + options.primary_samples = 1; + } + options.lights = None; // Retain the actual implicit three-light owner. + } + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":source.job}})).unwrap(); + setups::load(&mut h.app); + let before = h.app.session.doc.render.setups["Studio"].clone(); + h.app.cam.yaw += 0.2; + let camera = h.app.cam; + setups::refresh_dirty(&mut h.app); + light::loaded(&mut h.app); + let rows = light::rows(&h.app).unwrap(); + assert_eq!(rows.len(), 3); + assert!(rows.iter().all(|row| row.implicit), "the authored None list owns the neutral studio sources"); + assert_eq!(rows.iter().map(|row| row.id.as_str()).collect::>(), ["directional:0", "directional:1", "directional:2"]); + assert_eq!(rows.iter().map(|row| row.intensity).collect::>(), [3.0, 1.0, 1.5]); + let Some(RenderJob::CpuRaytrace { options, .. }) = &before.job else { panic!("CPU source lost") }; + assert!(options.lights.is_none() && options.preset.is_none()); + let id = rows[0].id.clone(); + h.app.run("render.lights.mute", json!({"id":id,"mute":true})).unwrap(); + h.app.run("render.lights.solo", json!({"id":id,"solo":true})).unwrap(); + h.app.render_workspace.view.selection = RenderSelection::Light(id.clone()); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + assert!(rows.iter().all(|row| !visibility.visible(&row.id)), "the solo source is muted; the other sources are not solo"); + // The request copy must materialize all three exact sources at zero. + // Leaving lights=None would reactivate the implicit studio fallback. + let expected_lights = json!([ + {"direction":[0.6,0.0,0.8],"color":[1.0,1.0,1.0],"intensity":0.0}, + {"direction":[-0.8,0.0,0.6],"color":[1.0,1.0,1.0],"intensity":0.0}, + {"direction":[0.0,-0.6,0.8],"color":[1.0,1.0,1.0],"intensity":0.0} + ]); + let filtered_before = image_request(&h.app).unwrap(); + assert_eq!(filtered_before["settings"]["job"]["options"]["lights"], expected_lights); + let filtered_setup: solidcraft_engine::doc::render_settings::RenderSetup = + serde_json::from_value(filtered_before["settings"].clone()).unwrap(); + let filtered_sources = solidcraft_engine::render_lights::inspect(&filtered_setup).unwrap(); + assert_eq!(filtered_sources.len(), 3); + assert!(filtered_sources.iter().all(|source| !source.implicit && source.intensity == 0.0)); + let irradiance: [f64; 3] = + std::array::from_fn(|channel| filtered_sources.iter().map(|source| source.colour[channel] * source.intensity).sum()); + assert_eq!(irradiance, [0.0; 3], "every authored directional source contributes exactly zero energy"); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + constant_environment_frame(&mut h, vec![]); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "opening the source must remain read-only"); + constant_environment_click_indirect(&mut h); + let mut expected = before.clone(); + if let Some(RenderJob::CpuRaytrace { options, .. }) = &mut expected.job { + options.path = Some(Default::default()); + options.progressive = Some(progressive.unwrap_or_default()); + options.primary_samples = 1; + options.shadows = true; + } + let after = h.app.session.doc.render.setups["Studio"].clone(); + assert_eq!(after, expected, "the exact saved job must preserve volume, light owner, output, profile, source and all other choices"); + assert_eq!(after.camera, before.camera, "the action cannot silently update the saved shot"); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + assert_eq!(h.app.session.redo.len(), 0); + assert_eq!(light::rows(&h.app).unwrap(), rows); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light(id.clone())); + assert!(h.app.render_workspace.view.dirty, "unrelated live navigation remains a draft"); + assert_eq!(h.app.render_workspace.view.raytrace.path.unwrap().max_depth, 8); + if progressive.is_none() { + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 16); + } + let request = raw_image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"], serde_json::to_value(&after.job).unwrap()); + let filtered = image_request(&h.app).unwrap(); + assert_eq!(filtered["settings"]["job"]["options"]["lights"], expected_lights, "adoption preserves the exact zero-energy captured sources"); + assert_eq!(filtered["settings"]["job"]["options"]["lights"], filtered_before["settings"]["job"]["options"]["lights"]); + assert!(request["settings"]["job"]["options"]["lights"].is_null(), "raw authored intent retains the implicit owner, not its filtered copy"); + h.app.run("edit.undo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], before); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["lights"], expected_lights); + h.app.run("edit.redo", json!({})).unwrap(); + setups::sync_revision(&mut h.app); + assert_eq!(h.app.session.doc.render.setups["Studio"], after); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["lights"], expected_lights); + assert!(h.app.session.render_job_host().is_none(), "the offline adoption action cannot mint a host"); + assert!(h.app.render_workspace.view.job.is_none()); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + // Document reset re-registers the app's existing host, not a new host + // from saved settings. Pin that owner independently of the fresh Session. + let cached_host = h.app.render_workspace.image_host.clone(); + let same_cached_host = |actual: Option<&solidcraft_engine::render::job::CpuHost>| match (cached_host.as_ref(), actual) { + (Some(expected), Some(actual)) => expected.same_host(actual), + (None, None) => true, + _ => false, + }; + h.app.session = Session::new(reopened); + assert!(h.app.session.render_job_host().is_none(), "the fresh Session starts without an installed host"); + let cold_document = h.app.session.doc.clone(); + let cold_model = h.app.session.model.state(); + let cold_camera = h.app.cam; + let cold_history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + reset_document(&mut h.app); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap().job, after.job); + assert_eq!(h.app.render_workspace.view.cpu.environment, cpu::Environment::Constant); + assert!(same_cached_host(h.app.session.render_job_host()), "cold reset/load must reuse only the app's exact existing host"); + assert!(same_cached_host(h.app.render_workspace.image_host.as_ref())); + assert!(h.app.render_workspace.view.job.is_none()); + let text = constant_environment_frame(&mut h, vec![]); + assert!(!text.contains(h.app.tr("render.cpu_constant_direct_help"))); + assert!(crate::scenario::rect_of("render:environment:enable-indirect").is_none()); + assert!(same_cached_host(h.app.session.render_job_host()), "painting cannot replace or create a host"); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(Arc::ptr_eq(&h.app.session.doc, &cold_document)); + assert!(Arc::ptr_eq(&h.app.session.model.state(), &cold_model)); + assert_eq!(h.app.cam, cold_camera); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), cold_history); + } +} + +#[test] +fn cpu_constant_environment_indirect_refusals_preserve_legacy_overrides_full_size_and_both_cameras_atomically() { + use solidcraft_engine::render::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; + enum Incompatible { + Reflection, + Budget, + LegacyRotation, + LegacyIntensity, + } + for (incompatible, case) in [ + ("reflection", Incompatible::Reflection), + ("budget", Incompatible::Budget), + ("legacy_rotation", Incompatible::LegacyRotation), + ("legacy_intensity", Incompatible::LegacyIntensity), + ] { + let mut h = cpu_volume_editor_fixture(false, None); + h.app.session.set_render_job_host(None).unwrap(); + match case { + Incompatible::Reflection => { + h.app.render_workspace.view.raytrace.reflections = Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: "Volume subject".into(), mode: ReflectionMode::Mirror }], + ..Default::default() + }); + } + Incompatible::Budget => { + h.app.render_workspace.view.draft.width = 2048; + h.app.render_workspace.view.draft.height = 2048; + } + Incompatible::LegacyRotation => h.app.render_workspace.view.draft.environment_rotation = 0.25, + Incompatible::LegacyIntensity => h.app.render_workspace.view.draft.environment_intensity = 2.0, + } + h.app.cam.yaw += 0.3; + let before = setups::draft(&h.app).unwrap(); + let options = h.app.render_workspace.view.raytrace.clone(); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + constant_environment_click_indirect(&mut h); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "{incompatible}: refusal must not create a command"); + assert_eq!(setups::draft(&h.app).unwrap(), before, "{incompatible}: full authored fields stay intact"); + assert_eq!(h.app.render_workspace.view.raytrace, options, "{incompatible}: no selected override or fixed-sampling choice is cleared"); + assert_eq!(h.app.cam, camera); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + assert!(h.app.render_workspace.view.raytrace.path.is_none()); + let error = environment::enable_indirect_lighting(&mut h.app).unwrap_err(); + if incompatible.starts_with("legacy_") { + assert_eq!(error, h.app.tr("render.setup_legacy_environment")); + } else if incompatible == "reflection" { + assert_eq!(error, h.app.tr("render.setup_runtime_unsupported")); + } else { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + assert!(CpuBudget::Compact.validate_image(2048, 2048, None).is_ok(), "the authored fixed image was valid before adoption"); + let sampling = CpuProgressiveOptions::default(); + assert_eq!(sampling.samples_per_pixel, 16); + assert!(u64::from(2048_u32).pow(2) * u64::from(sampling.samples_per_pixel) > CpuBudget::Compact.limits().max_camera_samples); + assert!(CpuBudget::Compact.validate_image(2048, 2048, Some(sampling)).is_err()); + // Compare the prospective translated size reason, never assume it + // names the current profile rather than the larger offered one. + let previous = h.app.render_workspace.view.clone(); + h.app.render_workspace.view.raytrace.progressive = Some(sampling); + let expected = cpu::validate_progressive_image(&h.app).unwrap_err(); + h.app.render_workspace.view = previous; + assert_eq!(error, expected, "full authored size/profile must be checked before the action can save"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn cpu_constant_environment_guidance_does_not_change_other_methods_sources_or_existing_indirect_mode() { + #[derive(Clone, Copy)] + enum Source { + None, + Hdr, + Sky, + Path, + Gpu, + Raster, + } + for (case, source) in + [("none", Source::None), ("hdr", Source::Hdr), ("sky", Source::Sky), ("path", Source::Path), ("gpu", Source::Gpu), ("raster", Source::Raster)] + { + let mut h = cpu_volume_editor_fixture(matches!(source, Source::Path | Source::Sky), None); + match source { + Source::None => h.app.render_workspace.view.cpu.environment = cpu::Environment::None, + Source::Hdr => { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "/must-not-be-read/lighting.hdr".into() }; + } + Source::Sky => h.app.render_workspace.view.cpu.environment = cpu::Environment::Sky, + Source::Gpu => h.app.render_workspace.view.method = ImageMethod::GpuRaytrace, + Source::Raster => h.app.render_workspace.view.method = ImageMethod::Raster, + Source::Path => {} + } + let document = h.app.session.doc.clone(); + let options = h.app.render_workspace.view.raytrace.clone(); + let camera = h.app.cam; + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let text = constant_environment_frame(&mut h, vec![]); + assert!(!text.contains(h.app.tr("render.cpu_constant_direct_help")), "{case}"); + assert!(crate::scenario::rect_of("render:environment:enable-indirect").is_none(), "{case}"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "{case}: merely opening this source is read-only"); + assert_eq!(h.app.render_workspace.view.raytrace, options); + assert_eq!(h.app.cam, camera); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +fn displayed_result_pass(h: &mut Harness, mut configure: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { + let app = &mut h.app; + h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), ..Default::default() }, + |ui| { + displayed::begin(app); + configure(ui); + show_result(app, ui); + displayed::finish(app, ui.ctx()); + }, + ) +} + +#[test] +fn render_displayed_receipt_requires_a_visible_final_submission_not_a_cached_image() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.live_paused = true; + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + cache_render_images(&mut h.app, &h.ctx); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + let cached = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().clone(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null(), "decoding a texture does not submit it"); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + h.frames(3); + let receipt = inspect_state(&h.app)["displayed_receipt"].clone(); + assert_eq!(receipt["job"], json!(job)); + assert_eq!(receipt["scene_generation"], frame.info.scene_generation); + assert_eq!((receipt["width"].as_u64(), receipt["height"].as_u64()), (Some(16), Some(16))); + assert_eq!(receipt["kind"], "final"); + assert!(receipt["frame_sequence"].is_null() && receipt["samples_per_pixel"].is_null() && receipt["adaptive"].is_null()); + assert!(receipt["egui_frame_nr"].is_u64() && receipt["egui_pass_nr"].is_u64()); + assert_eq!(receipt["egui_frame_nr"].as_u64().unwrap() + 1, h.ctx.cumulative_frame_nr()); + assert_eq!(receipt["egui_pass_nr"].as_u64().unwrap() + 1, h.ctx.cumulative_pass_nr()); + assert!( + h.shapes + .iter() + .any(|shape| matches!(&shape.shape, egui::Shape::Mesh(mesh) if mesh.texture_id == cached.id() && shape.clip_rect.is_positive())), + "the receipt must accompany a real image shape in the completed app UI pass" + ); + // Automation drains in logic before the next UI pass. Neither inspect nor logic + // may mint a fresh frame/pass receipt from the still-present texture. + for _ in 0..3 { + assert_eq!(inspect_state(&h.app)["displayed_receipt"], receipt); + } + h.app.logic(&h.ctx); + assert_eq!(inspect_state(&h.app)["displayed_receipt"], receipt); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert_eq!(h.app.cam, camera); + h.app.render_workspace.image.as_mut().unwrap().1 = Err("retained decode/upload error".into()); + displayed_result_pass(&mut h, |_| {}).textures_delta.clear(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null(), "an error label is not an image submission"); + h.app.render_workspace.image.as_mut().unwrap().1 = Ok(cached); + displayed_result_pass(&mut h, |_| {}).textures_delta.clear(); + assert!(!inspect_state(&h.app)["displayed_receipt"].is_null()); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null(), "the mode command clears the prior pass before another paint"); + assert!(h.app.render_workspace.image.is_some(), "the diagnostic does not discard or change the retained texture"); +} + +#[test] +fn render_displayed_receipt_excludes_hidden_clipped_transparent_and_discarded_passes() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.live_paused = true; + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + displayed_result_pass(&mut h, |_| {}).textures_delta.clear(); + assert!(!inspect_state(&h.app)["displayed_receipt"].is_null()); + displayed_result_pass(&mut h, |ui| ui.set_invisible()).textures_delta.clear(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + displayed_result_pass(&mut h, |ui| ui.set_opacity(0.0)).textures_delta.clear(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + displayed_result_pass(&mut h, |ui| ui.set_clip_rect(egui::Rect::NOTHING)).textures_delta.clear(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + displayed_result_pass(&mut h, |_| {}).textures_delta.clear(); + let previous = inspect_state(&h.app)["displayed_receipt"].clone(); + assert!(!previous.is_null()); + let mut passes = 0; + let app = &mut h.app; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), ..Default::default() }, + |ui| { + displayed::begin(app); + if passes == 0 { + show_result(app, ui); + ui.ctx().request_discard("receipt test: layout discards after the actual image call"); + assert!(ui.ctx().will_discard()); + displayed::finish(app, ui.ctx()); + assert_eq!(inspect_state(app)["displayed_receipt"], previous, "a discarded candidate cannot replace the completed pass"); + } else { + displayed::finish(app, ui.ctx()); + assert!(inspect_state(app)["displayed_receipt"].is_null(), "the final accepted pass submitted no image"); + } + passes += 1; + }, + ); + output.textures_delta.clear(); + assert_eq!(passes, 2, "exercise egui's real discard/replay path"); +} + +#[test] +fn render_displayed_receipt_clears_for_comparison_document_and_workspace_transitions() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.live_paused = true; + let first = completed_preview(&mut h, [20, 40, 60]); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + h.app.run("render.result.select", json!({"index":1})).unwrap(); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.frames(3); + assert_eq!(inspect_state(&h.app)["displayed_receipt"]["job"], json!(second)); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + h.frames(2); + assert!(comparison_active(&h.app)); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null(), "two composited sources must not masquerade as one submitted image"); + h.app.run("render.compare", json!({"off":true})).unwrap(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null(), "ending comparison cannot resurrect an old receipt"); + h.frames(2); + assert!(!inspect_state(&h.app)["displayed_receipt"].is_null()); + enter(&mut h.app, false).unwrap(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + enter(&mut h.app, true).unwrap(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + h.app.render_workspace.view.result = true; + h.frames(2); + assert!(!inspect_state(&h.app)["displayed_receipt"].is_null()); + invalidate_images(&mut h.app); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + h.frames(2); + assert!(!inspect_state(&h.app)["displayed_receipt"].is_null()); + reset_document(&mut h.app); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null()); + assert!(h.app.session.render_job_handle(first).unwrap().frame().unwrap().is_some(), "receipt resets do not evict renderer results"); +} + +#[test] +fn render_displayed_receipt_tracks_actual_cooperative_preview_then_final_without_pumping_it() { + use solidcraft_engine::render::job::{JobId, Phase}; + for adaptive in [None, Some(json!({"pilot_samples":16,"min_samples":16,"relative_error":0.05,"absolute_error":0.002,"coverage_error":0.01}))] { + let maximum = if adaptive.is_some() { 16 } else { 3 }; + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.live_paused = true; + if image_host(&h.app, ImageMethod::CpuRaytrace).is_err() { + eprintln!("CPU checkpoint receipt test requires raytrace-cpu"); + return; + } + let host = h.app.session.render_job_host().unwrap().clone(); + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":2,"height":2,"job":{"method":"cpu_raytrace","options":{"primary_samples":1,"progressive":{"samples_per_pixel":maximum,"seed":81},"adaptive":adaptive}}}})).unwrap(); + let job: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + for _ in 0..100_000 { + host.pump(1).unwrap(); + if handle.preview().unwrap().is_some() { + break; + } + } + let checkpoint = handle.preview().unwrap().expect("one real complete-pass CPU checkpoint"); + assert_ne!(handle.status().unwrap().progress.phase, Phase::Completed); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.follow_job = true; + let before = handle.status().unwrap().progress; + displayed_result_pass(&mut h, |_| {}).textures_delta.clear(); + let receipt = inspect_state(&h.app)["displayed_receipt"].clone(); + assert_eq!(receipt["kind"], "preview"); + assert_eq!(receipt["job"], json!(checkpoint.info.frame.job)); + assert_eq!(receipt["scene_generation"], checkpoint.info.frame.scene_generation); + assert_eq!(receipt["frame_sequence"], checkpoint.info.frame_sequence); + assert_eq!(receipt["samples_per_pixel"], checkpoint.info.samples_per_pixel); + assert_eq!(receipt["adaptive"], json!(checkpoint.info.adaptive)); + assert_eq!( + receipt["adaptive"].is_null(), + adaptive.is_none(), + "adaptive absolute iterations carry their captured phase instead of claiming uniform SPP" + ); + let after = handle.status().unwrap().progress; + assert_eq!( + (before.done, before.total, before.phase), + (after.done, after.total, after.phase), + "painting and inspecting the receipt cannot pump the producer" + ); + for _ in 0..1000 { + host.pump(16384).unwrap(); + if handle.status().unwrap().progress.phase == Phase::Completed { + break; + } + } + assert_eq!(handle.status().unwrap().progress.phase, Phase::Completed); + displayed_result_pass(&mut h, |_| {}).textures_delta.clear(); + let final_receipt = inspect_state(&h.app)["displayed_receipt"].clone(); + assert_eq!(final_receipt["job"], json!(job)); + assert_eq!(final_receipt["kind"], "final"); + assert!(final_receipt["frame_sequence"].is_null() && final_receipt["samples_per_pixel"].is_null()); + assert!(handle.frame().unwrap().is_some()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_displayed_receipt_uses_the_immutable_live_texture_source_not_the_current_selected_job() { + let Some(mut h) = live_cpu_fixture() else { return }; + h.app.viewport.rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(8.0, 8.0))); + live::advance(&mut h.app, &h.ctx, 1.0); + let captured = wait_live_complete(&mut h, 1.3); + let selected = h.app.render_workspace.view.job; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0))), ..Default::default() }, + |ui| { + displayed::begin(&mut h.app); + live::paint(&mut h.app, ui, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 100.0))); + displayed::finish(&mut h.app, ui.ctx()); + }, + ); + output.textures_delta.clear(); + let receipt = inspect_state(&h.app)["displayed_receipt"].clone(); + assert_eq!(receipt["job"], captured["job"]); + assert_ne!(receipt["job"], json!(selected)); + assert_eq!(receipt["scene_generation"], h.app.session.revision); + assert_eq!(receipt["kind"], "live_final"); + assert_eq!(receipt["samples_per_pixel"], captured["samples"]); + assert_eq!(receipt["frame_sequence"], captured["sequence"]); + assert_eq!(h.app.render_workspace.view.job, selected, "scratch pixels cannot change final-result ownership"); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0))), ..Default::default() }, + |ui| { + displayed::begin(&mut h.app); + let subpixel = egui::Rect::from_min_size(egui::pos2(10.1, 10.1), egui::vec2(0.1, 0.1)); + live::paint(&mut h.app, ui, subpixel); + displayed::finish(&mut h.app, ui.ctx()); + }, + ); + output.textures_delta.clear(); + assert!(inspect_state(&h.app)["displayed_receipt"].is_null(), "a live image rounded to zero physical area is not a visible submission"); +} + +fn stable_glass_draft_fixture(method: ImageMethod, with_maps: bool) -> Harness { + let mut h = Harness::new(); + assert_eq!(h.app.preferences.render_inspector_width, crate::prefs::Prefs::default().render_inspector_width); + h.call("ui.resize", json!({"width":1440,"height":3000})); + for (index, name) in ["Glass A", "Glass B", "Map", "Coat"].into_iter().enumerate() { + h.app.run("solid.box", json!({"body_name":name,"length":5,"width":5,"height":5,"corner":[index * 15,0,0],"operation":"new"})).unwrap(); + } + let camera = solidcraft_engine::render::Camera { fov: 0.6, distance: 80.0, ..Default::default() }; + let lens = json!({"aperture_radius_mm":0.02,"focus_distance_mm":80.0}); + let job = if method == ImageMethod::CpuRaytrace { + json!({"method":"cpu_raytrace","options":{"path":{"max_depth":4}, + "progressive":{"samples_per_pixel":4,"seed":17},"lens":lens,"output":{"linear_exr":true}}}) + } else { + json!({"method":"gpu_path","options":{"samples":4,"max_depth":4,"seed":17,"lens":lens,"linear_exr":true, + "lighting":{"environment":[0.15,0.2,0.25],"sun":{"direction":[1,2,3],"angular_radius_rad":0.02,"radiance":[2.0,3.0,4.0]}}}}) + }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":8,"height":8,"camera":camera,"job":job}})).unwrap(); + let targets = materials::read_targets(&mut h.app).unwrap(); + let target = |name: &str| targets.iter().find(|target| target.name == name).unwrap(); + let a = target("Glass A"); + h.app + .run( + "render.optics.bind", + json!({"name":"Studio","body_index":a.ordinal,"body_name":a.name,"expected_revision":h.app.session.revision, + "optics":{"ior":1.43,"boundary":"closed_mesh","absorption_per_mm":[0.01,0.02,0.03]}}), + ) + .unwrap(); + let coat = target("Coat"); + h.app + .run( + "render.coat.bind", + json!({"name":"Studio","body_index":coat.ordinal,"body_name":coat.name,"expected_revision":h.app.session.revision, + "coat":{"weight":0.35,"roughness":0.18,"ior":1.4}}), + ) + .unwrap(); + if with_maps { + let map = target("Map"); + h.app + .run( + "render.library.surface.bind", + json!({"name":"Studio","surface":{"id":"SURF-001","body_index":map.ordinal,"body_name":map.name,"scale":1.0}}), + ) + .unwrap(); + } + h.app.cam = camera; + enter(&mut h.app, true).unwrap(); + setups::load(&mut h.app); + h.app.render_workspace.view.live_paused = true; + h.app.session.set_render_job_host(None).unwrap(); + h +} + +fn stable_glass_draft_add(h: &mut Harness, name: &str) { + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == name).unwrap(); + assert!(target.stable_target.is_some()); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); +} + +fn stable_glass_draft_viewport(h: &Harness) -> egui::Rect { + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let header = crate::scenario::rect_of("render:inspector:header").unwrap(); + let footer = crate::scenario::rect_of("dialog:editor_footer").unwrap(); + assert!(inspector.contains(header.center()) && inspector.contains(footer.center())); + let viewport = egui::Rect::from_min_max( + egui::pos2(inspector.left(), header.bottom() + Tokens::get().space_8), + egui::pos2(inspector.right(), (inspector.bottom() - Tokens::get().space_8).min(footer.top())), + ) + .intersect(h.ctx.content_rect()); + assert!(viewport.is_positive()); + viewport +} + +fn stable_glass_draft_reveal(h: &mut Harness, handle: &str) -> usize { + for scrolls in 0..32 { + let rect = crate::scenario::rect_of(handle).unwrap(); + let viewport = stable_glass_draft_viewport(h); + assert!(rect.is_positive() && rect.left() >= viewport.left() && rect.right() <= viewport.right(), "{handle}: {rect:?}, {viewport:?}"); + if viewport.contains_rect(rect) { + return scrolls; + } + // Scroll the actual visible inspector body, never an off-clip target. + let point = egui::pos2(viewport.left() + viewport.width() * 0.25, viewport.center().y); + h.call("ui.scroll", json!({"x":point.x,"y":point.y,"delta":if rect.top() < viewport.top() {120} else {-120}})); + for _ in 0..120 { + if !h.ctx.input(|input| input.is_scrolling()) { + break; + } + h.frame(); + } + assert!(!h.ctx.input(|input| input.is_scrolling()), "inspector wheel must settle before using a fresh handle"); + } + panic!("{handle}: could not reveal the complete control in the inspector"); +} + +fn stable_glass_draft_click(h: &mut Harness, handle: &str) -> usize { + let scrolls = stable_glass_draft_reveal(h, handle); + let rect = crate::scenario::rect_of(handle).unwrap(); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + assert!(rect.is_positive() && inspector.contains_rect(rect) && stable_glass_draft_viewport(h).contains_rect(rect), "{handle}: {rect:?}"); + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.frames(2); + scrolls +} + +#[test] +fn stable_glass_pointer_draft_composes_saved_glass_maps_coat_and_lens_until_one_explicit_save() { + use solidcraft_engine::doc::render_optics::{OpticalMaterial, SavedOptics}; + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let factory_width = crate::prefs::Prefs::default().render_inspector_width; + let mut h = stable_glass_draft_fixture(method, true); + // Keep the unmodified305pt factory preference and use ordinary wheel navigation. + h.call("ui.resize", json!({"width":1440,"height":760})); + assert_eq!(h.ctx.content_rect().size(), egui::vec2(1440.0, 760.0), "the pointer journey must use the requested ordinary viewport"); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Glass B".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.app.cam.yaw += 0.125; + h.frames(3); + let document = 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 selection = h.app.session.selection.clone(); + let saved = document.render.setups["Studio"].clone(); + assert_ne!(camera, saved.camera, "the optical save must preserve an independently saved camera"); + assert_eq!((saved.optics.len(), saved.surfaces.len(), saved.coats.len()), (1, 1, 1)); + let mut scrolls = stable_glass_draft_click(&mut h, &format!("dialog:section:{}", crate::i18n::tr("render.appearance_editor.glass"))); + scrolls += stable_glass_draft_click(&mut h, "render:glass:enable"); + let absorption = h.app.tr("render.appearance_editor.absorption").to_owned(); + for axis in 0..3 { + scrolls += stable_glass_draft_reveal(&mut h, &format!("dialog:vector:{absorption}:{axis}")); + let field = crate::scenario::rect_of(&format!("dialog:vector:{absorption}:{axis}")).unwrap(); + let column = crate::scenario::rect_of(&format!("dialog:control:{absorption} {}", ["R", "G", "B"][axis])).unwrap(); + assert!(column.contains_rect(field), "absorption{axis}: {field:?}, {column:?}"); + } + let binding = h.app.render_workspace.view.materials.bindings.iter().find(|binding| binding.target.name == "Glass B").unwrap(); + assert!(binding.glass_enabled && !binding.has_runtime_intent()); + let target = binding.target.stable_target.clone().unwrap(); + let mut expected = saved.clone(); + expected.camera = camera; + expected.optics.set(SavedOptics { target, optics: OpticalMaterial::default() }, false).unwrap(); + let request = image_request(&h.app).unwrap(); + assert_eq!(request, json!({"settings":expected})); + let mut repeated = request.clone(); + materials::params(&h.app, &mut repeated).unwrap(); + assert_eq!(repeated, request, "already prospective stable rows are idempotent"); + assert!( + setups::snapshot(&h.app).unwrap_err().contains(h.app.tr("render.setup_runtime_unsupported")), + "generic Save cannot silently commit Glass drafts" + ); + h.frames(4); + assert_eq!(h.app.preferences.render_inspector_width, factory_width, "painting and scrolling cannot widen the inspector"); + assert_eq!(image_request(&h.app).unwrap(), request); + assert!(Arc::ptr_eq(&document, &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.session.selection, selection); + assert_eq!(h.app.cam, camera); + assert!(h.app.render_workspace.view.job.is_none()); + scrolls += stable_glass_draft_click(&mut h, &format!("dialog:section:{}", crate::i18n::tr("render.appearance_editor.saved"))); + scrolls += stable_glass_draft_reveal(&mut h, "render:optics-save"); + let save_label = h.app.tr("render.appearance_editor.save").to_owned(); + let save_enabled = { + let tree = h.output.accesskit_update.as_ref().unwrap(); + let mut buttons = + tree.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some(save_label.as_str())); + let enabled = !buttons.next().expect("the actual optics Save button must be accessible").1.is_disabled(); + assert!(buttons.next().is_none(), "the reviewed optics Save action must be unambiguous"); + enabled + }; + assert!(save_enabled, "optics Save is disabled before the real click; status={:?}", h.app.status); + scrolls += stable_glass_draft_click(&mut h, "render:optics-save"); + assert!(scrolls > 0, "the ordinary-height inspector journey must use actual wheel input"); + expected.camera = saved.camera; + let committed = h.app.session.doc.clone(); + assert_eq!( + committed.render.setups["Studio"], expected, + "actual Save enabled={save_enabled}, status={:?}, last command={:?}", + h.app.status, h.app.last_command + ); + assert_eq!(h.app.preferences.render_inspector_width, factory_width, "explicit Save retains the factory inspector width"); + assert_eq!(h.app.session.undo.len(), history.1 + 1); + assert_eq!(committed.features, document.features); + assert_eq!(committed.materials, document.materials); + assert_eq!(committed.appearances, document.appearances); + assert!(Arc::ptr_eq(&model, &h.app.session.model.state())); + assert_eq!(h.app.cam, camera); + assert_eq!(solidcraft_engine::doc::Document::from_json(&committed.to_json()).unwrap(), *committed); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.cam, camera); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, committed); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn stable_glass_drafts_survive_checked_file_hdr_and_both_request_builder_orders() { + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = stable_glass_draft_fixture(method, false); + stable_glass_draft_add(&mut h, "Glass B"); + let typed = image_request(&h.app).unwrap(); + let target = if method == ImageMethod::CpuRaytrace { hdr::Target::Cpu } else { hdr::Target::Gpu }; + let path = h.dir.join("stable-glass-parity.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + if method == ImageMethod::CpuRaytrace { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + } else { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + } + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + assert!(matches!(hdr::input(&h.app, target), hdr::Input::FileCaptured { .. })); + let document = 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(); + assert_eq!(request["settings"]["optics"], typed["settings"]["optics"]); + assert_eq!(request["settings"]["coats"], typed["settings"]["coats"]); + assert_eq!(request["settings"]["camera"], typed["settings"]["camera"]); + assert_eq!(request["settings"]["optics"].as_array().unwrap().len(), 2); + assert!( + request.pointer("/raytrace/dielectrics").is_none_or(|rows| rows.as_array().is_some_and(Vec::is_empty)), + "stable Glass never becomes a duplicate ordinal override" + ); + if method == ImageMethod::CpuRaytrace { + assert_eq!(request["raytrace"]["lens"], typed["settings"]["job"]["options"]["lens"]); + assert_eq!(request["raytrace"]["path"], typed["settings"]["job"]["options"]["path"]); + } else { + assert_eq!(request["lens"], typed["settings"]["job"]["options"]["lens"]); + assert_eq!(request["max_depth"], typed["settings"]["job"]["options"]["max_depth"]); + assert_eq!(request["lighting"], typed["settings"]["job"]["options"]["lighting"]); + assert_eq!((request["samples"].as_u64(), request["seed"].as_u64()), (Some(4), Some(17))); + } + let mut twice = request.clone(); + materials::params(&h.app, &mut twice).unwrap(); + assert_eq!(twice, request); + assert!(Arc::ptr_eq(&document, &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!(h.app.render_workspace.view.job.is_none()); + if method == ImageMethod::GpuRaytrace { + // This executes the real engine capture/Check route against a metadata + // protocol executor. It never opens a device or qualifies GPU pixels. + use serde_json::Value; + use solidcraft_engine::render::{RenderFeature, job}; + struct Capture(Arc>>); + impl job::ImageExecutor for Capture { + fn supports_linear_exr(&self) -> bool { + true + } + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("gpu-path").unwrap(); + descriptor.profiles[0].features = + vec![RenderFeature::Hdri, RenderFeature::Pbr, RenderFeature::Refraction, RenderFeature::Progressive]; + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &job::ImageRequest, options: job::JobOptions) -> job::Result { + let admission = job::admit_geometry(scene, request, job::MAX_GPU_PATH_TRIANGLES)?; + // Copy bounded scalar metadata, not source meshes/HDR Arcs. + let bodies: Vec<_> = scene + .meshes + .iter() + .enumerate() + .map(|(index, body)| { + json!({ + "index":index,"name":body.name,"ior":body.surface.map(|surface|surface.dielectric_ior()), + "absorption":body.transmission.map(|medium|{let c=medium.extinction();[c.x,c.y,c.z]}), + "has_coat":body.surface.is_some_and(|surface|surface.clear_coat().is_some()) + }) + }) + .collect(); + *self.0.lock().unwrap() = Some(json!({"bodies":bodies,"camera":request.camera, + "environment":request.environment.as_ref().map(|source|source.info()),"options":options})); + Ok(admission) + } + fn begin( + &self, + _: ProductScene, + _: job::ImageRequest, + _: job::JobOptions, + _: job::CancelToken, + ) -> job::Result> { + Err(job::JobError::new(job::ErrorCode::HostUnavailable, "protocol capture test must not begin image work")) + } + } + let captured = Arc::new(std::sync::Mutex::new(None)); + let host = job::ImageHost::with_executor(Arc::new(Capture(captured.clone()))).unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert!(checked.get("job").is_none()); + assert_eq!(checked["resolved"]["executor"], "gpu-path"); + let captured = captured.lock().unwrap().take().unwrap(); + for (name, ior, absorption) in [("Glass A", 1.43, [0.01, 0.02, 0.03]), ("Glass B", 1.5, [0.0; 3])] { + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == name).unwrap(); + let body = captured["bodies"].as_array().unwrap().iter().find(|body| body["name"] == name).unwrap(); + assert_eq!(body["index"], json!(target.ordinal)); + assert_eq!(body["ior"], json!(ior)); + assert_eq!(body["absorption"], json!(absorption)); + } + assert!(captured["bodies"].as_array().unwrap().iter().any(|body| body["name"] == "Coat" && body["has_coat"] == true)); + assert_eq!(captured["camera"], json!(camera)); + assert_eq!(captured["environment"], checked["environment"]); + assert_eq!(captured["environment"]["source_sha256"], json!(hdr::input(&h.app, target).resource().unwrap())); + let expected_options = job::JobOptions { + samples: h.app.render_workspace.view.samples, + max_depth: h.app.render_workspace.view.max_depth, + seed: h.app.render_workspace.view.seed, + lens: Some(h.app.render_workspace.view.studio.lens), + lighting: serde_json::from_value(request["lighting"].clone()).unwrap(), + linear_exr: true, + ..Default::default() + }; + assert_eq!(captured["options"], json!(expected_options), "all GPU lighting, lens and numerical options reach capture"); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &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); + } + } +} + +#[test] +fn stable_glass_draft_stays_dirty_across_refresh_navigation_and_cancelled_shot_switch() { + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = stable_glass_draft_fixture(method, false); + h.app.run("render.settings.set", json!({"name":"Other","set":{"width":8,"height":8,"job":{"method":"raster"}}})).unwrap(); + h.app.render_workspace.view.name = "Studio".into(); + setups::load(&mut h.app); + stable_glass_draft_add(&mut h, "Glass B"); + assert!(!setups::requires_runtime_request(&h.app)); + assert!(setups::has_runtime_inputs(&h.app), "portable optics are still unsaved local intent"); + h.app.render_workspace.view.dirty = false; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + let request = image_request(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let camera = h.app.cam; + enter(&mut h.app, false).unwrap(); + h.app.cam.yaw += 0.3; + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.cam, camera, "Render navigation is not replaced by saved-camera hydration"); + assert_eq!(image_request(&h.app).unwrap(), request); + assert!(h.app.render_workspace.view.dirty); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + switch_shot(&mut h.app, "Other".into()); + assert!(inspector::confirmation_open(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(image_request(&h.app).unwrap(), request); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + assert_eq!(image_request(&h.app).unwrap(), request); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn stable_glass_draft_refusals_keep_saved_targets_unknown_identity_and_maps_hdr_intent() { + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + // Hostile local state cannot masquerade as an edit of an existing saved row. + let mut h = stable_glass_draft_fixture(method, false); + stable_glass_draft_add(&mut h, "Glass A"); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.cam); + assert!(image_request(&h.app).unwrap_err().contains(h.app.tr("render.material_revalidate_needed"))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.cam), before); + + let mut h = stable_glass_draft_fixture(method, false); + stable_glass_draft_add(&mut h, "Glass B"); + h.app.render_workspace.view.materials.bindings[0].target.stable_target = None; + assert!(h.app.render_workspace.view.materials.bindings[0].has_runtime_intent()); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.cam); + if method == ImageMethod::CpuRaytrace { + assert!(image_request(&h.app).unwrap_err().contains(h.app.tr("render.material_cpu_saved_runtime_conflict"))); + } else { + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["optics"], json!(document.render.setups["Studio"].optics)); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Glass B"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.cam), before); + + let mut h = stable_glass_draft_fixture(method, true); + stable_glass_draft_add(&mut h, "Glass B"); + let target = if method == ImageMethod::CpuRaytrace { hdr::Target::Cpu } else { hdr::Target::Gpu }; + let path = h.dir.join("saved-maps-glass.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + if method == ImageMethod::CpuRaytrace { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + } else { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + } + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.cam); + assert!(image_request(&h.app).unwrap_err().contains(h.app.tr("render.saved_maps_runtime_conflict"))); + assert_eq!(h.app.render_workspace.view.draft.surfaces, document.render.setups["Studio"].surfaces); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.cam), before); + + let mut h = stable_glass_draft_fixture(method, false); + stable_glass_draft_add(&mut h, "Glass B"); + // Bypass UI post-hooks to model an unacknowledged embedding/source replacement. + h.app.session.execute("render.settings.set", &json!({"name":"Unrelated","set":{"width":13}})).unwrap(); + let document = h.app.session.doc.clone(); + assert!(image_request(&h.app).unwrap_err().contains(h.app.tr("render.material_revalidate_needed"))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + } +} + +#[test] +fn stable_glass_draft_capture_keeps_the_existing_cpu_eight_and_gpu_thirty_two_limits() { + for (method, limit) in [(ImageMethod::CpuRaytrace, 8), (ImageMethod::GpuRaytrace, 32)] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"Optics","length":1,"width":1,"height":1})).unwrap(); + h.app.run("solid.pattern.rectangular", json!({"bodies":["Optics"],"dir1":[1,0,0],"count1":limit+1,"spacing1":3})).unwrap(); + let targets = materials::read_targets(&mut h.app).unwrap(); + assert_eq!(targets.len(), limit + 1); + h.app.cam.fov = 0.6; + let job = if method == ImageMethod::CpuRaytrace { + json!({"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":4,"seed":17},"path":{"max_depth":4}}}) + } else { + json!({"method":"gpu_path","options":{"samples":4,"max_depth":4,"seed":17}}) + }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":8,"height":8,"camera":h.app.cam,"job":job}})).unwrap(); + setups::load(&mut h.app); + for target in targets.iter().take(limit) { + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + } + h.app.render_workspace.view.materials.enabled = true; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["optics"].as_array().unwrap().len(), limit); + let mut binding = materials::Binding::new(targets[limit].clone(), &h.app); + binding.glass_enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + assert!(image_request(&h.app).is_err(), "{method:?}: over-limit targets must refuse rather than disappear"); + 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); + } +} + #[test] fn render_results_batch_continues_in_background_tabs_and_keeps_each_shot_result_with_its_document() { let mut h = render_results_batch_fixture(); diff --git a/crates/ui-egui/src/render_workspace_transport.rs b/crates/ui-egui/src/render_workspace_transport.rs index 8e624eee0..3fef525ee 100644 --- a/crates/ui-egui/src/render_workspace_transport.rs +++ b/crates/ui-egui/src/render_workspace_transport.rs @@ -1,4 +1,4 @@ -//! Shared numerical editors for bounded GPU transport extensions. +//! Shared numerical editors for bounded camera sampling and GPU transport extensions. use crate::{SolveApp, ui_kit}; /// Pilot allocation and conditional transmission sampling share portable intent. @@ -13,7 +13,16 @@ pub(super) fn adaptive_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let response = ui_kit::checkbox(ui, app.tr("render.adaptive_enable"), &mut enabled); crate::scenario::publish_target("render:adaptive-enable", response.rect); if response.changed() { - app.render_workspace.view.studio.adaptive = enabled.then(Default::default); + app.render_workspace.view.studio.adaptive = enabled.then(|| { + let mut options = solidcraft_engine::render::job::adaptive::AdaptiveSampling::default(); + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + // Explicitly enabling the option does not silently raise the saved + // production cap, change the image size or choose a larger profile. + options.pilot_samples = 16; + options.min_samples = 16; + } + options + }); } let mut options = app.render_workspace.view.studio.adaptive.unwrap_or_default(); if !enabled { @@ -47,6 +56,10 @@ 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) { + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + cpu_glass_controls(app, ui); + return; + } let before = (app.render_workspace.view.studio.nested_media, app.render_workspace.view.studio.transmission_samples); let mut strata = match before.1 { 2 => 1, @@ -69,3 +82,37 @@ pub(super) fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui) { app.render_workspace.view.dirty |= before != (app.render_workspace.view.studio.nested_media, app.render_workspace.view.studio.transmission_samples); } + +/// 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) { + ui_kit::text(ui, app.tr("render.material_cpu_optics_limits"), ui_kit::Text::Note("render.cpu_glass_limits")); + if app.render_workspace.view.raytrace.progressive.is_none() { + let reason = super::cpu::progressive_adoption_reason(app); + let button = ui_kit::button(ui, app.tr("render.cpu_progressive_adopt"), ui_kit::Button::Enabled(reason.is_none())); + crate::scenario::publish_target("render:cpu-glass-adopt-progressive", button.rect); + if button.clicked() + && let Err(error) = super::cpu::adopt_progressive(app) + { + app.set_status(error, true); + } + if let Some(reason) = reason { + ui_kit::text(ui, &reason, ui_kit::Text::Note("render.cpu_glass_adoption_reason")); + } + } + if let Some(path) = app.render_workspace.view.raytrace.path { + ui_kit::row(ui, app.tr("render.cpu_path_depth"), |ui| ui_kit::text(ui, &path.max_depth.to_string(), ui_kit::Text::Inline)); + } else { + let reason = super::cpu::path_reason(app); + let button = ui_kit::button(ui, app.tr("render.cpu_glass_enable_path"), ui_kit::Button::Enabled(reason.is_none())); + crate::scenario::publish_target("render:cpu-glass-enable-path", button.rect); + if button.clicked() { + app.render_workspace.view.raytrace.path = Some(Default::default()); + app.render_workspace.view.dirty = true; + } + if let Some(reason) = reason { + ui_kit::text(ui, &reason, ui_kit::Text::Note("render.cpu_glass_path_reason")); + } + } + ui_kit::text(ui, app.tr("render.cpu_path_help"), ui_kit::Text::Note("render.cpu_glass_path_help")); +} diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index d75c1bf76..8272e0241 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -927,6 +927,52 @@ pub(crate) fn dropdown_menu(ui: &mut Ui, id: impl egui::AsIdSalt, current: &str, dropdown_menu_with_close_behavior(ui, id, current, egui::PopupCloseBehavior::CloseOnClick, add) } +/// A width-bounded toolbar picker. Long selected values and popup rows truncate; +/// callers can retain their complete labels in hover text. +pub(crate) fn bounded_dropdown_menu(ui: &mut Ui, id: impl egui::AsIdSalt, current: &str, width: f32, add: impl FnOnce(&mut Ui)) -> Response { + crate::prefs_search::note_current(ui, current); + if crate::prefs_search::querying(ui) + && (!ui.is_visible() || (crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[current]))) + { + return crate::prefs_search::hidden_response(ui); + } + let width = dimension(width); + let response = ui + .allocate_ui_with_layout(vec2(width, row_height()), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(width); + let widget = ui.make_persistent_id(egui::IdSalt::new(&id)); + let combo = egui::ComboBox::from_id_salt(id) + .width(width) + .height(Tokens::get().space_24 * 14.0) + .selected_text(current) + .truncate() + .icon(dropdown_arrow); + let popup = super::container::show_combo(ui, widget, combo, |ui| { + ui.set_max_width(width); + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + add(ui); + }); + let response = popup.response; + if popup.inner.is_some() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + response.request_focus(); + } + response + }) + .inner; + publish(ui, &response, egui::Role::ComboBox); + // The shared kit publication supplies chrome and row metadata, but omits + // the selected value. Restore both for the final focus/click announcement; + // visual truncation must not truncate the accessible captured-source name. + response.widget_info(|| { + let row_label = label(ui); + let name = if row_label.trim().is_empty() { current } else { crate::i18n::tr_label(row_label) }; + let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), name); + info.current_text_value = Some(current.to_owned()); + info + }); + response +} + /// Dropdown with explicit dismissal behavior. For editable content use `CloseOnClickOutside` /// and close the popup when a choice is accepted. pub(crate) fn dropdown_menu_with_close_behavior( @@ -986,6 +1032,16 @@ fn dropdown_menu_width( paint_dropdown_icon(ui, response.rect, icon); } publish(ui, &response, egui::Role::ComboBox); + // Kit chrome publishes the row label after egui's selected-text metadata. + // Keep that label when present, and the visible action/value for a bare + // dropdown, without losing its full current value in the final announcement. + response.widget_info(|| { + let row_label = label(ui); + let name = if row_label.trim().is_empty() { current } else { crate::i18n::tr_label(row_label) }; + let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), name); + info.current_text_value = Some(current.to_owned()); + info + }); response } @@ -1638,7 +1694,38 @@ pub(crate) fn number_field( speed: f64, suffix: &str, ) -> Response { - let response = ui.add(egui::DragValue::new(value).range(range).speed(speed).suffix(suffix).custom_parser(crate::prefs::parse_number)); + bounded_number_field(ui, value, range, speed, suffix, true) +} + +/// A bounded editor that preserves an existing out-of-range value until the person edits it. +/// Useful when a selected resource profile changes the admissible range: revealing the field +/// must not silently lower saved intent. Typing and dragging still respect the current limits. +pub(crate) fn number_field_preserving( + ui: &mut Ui, + value: &mut T, + range: std::ops::RangeInclusive, + speed: f64, + suffix: &str, +) -> Response { + bounded_number_field(ui, value, range, speed, suffix, false) +} + +fn bounded_number_field( + ui: &mut Ui, + value: &mut T, + range: std::ops::RangeInclusive, + speed: f64, + suffix: &str, + clamp_existing: bool, +) -> Response { + let response = ui.add( + egui::DragValue::new(value) + .range(range) + .clamp_existing_to_range(clamp_existing) + .speed(speed) + .suffix(suffix) + .custom_parser(crate::prefs::parse_number), + ); if response.has_focus() { crate::prefs_search::note_key_sink(ui.ctx()); } diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs index 4bf116981..07f32cf1e 100644 --- a/crates/ui-egui/src/ui_kit/fields_tests.rs +++ b/crates/ui-egui/src/ui_kit/fields_tests.rs @@ -940,7 +940,7 @@ fn navigation_dropdown_popups_own_escape_and_return_focus_without_canceling_the_ let previous = crate::theme::is_dark(); for dark in [false, true] { crate::theme::set_dark(dark); - for kind in ["plain", "compact", "editable"] { + for kind in ["plain", "compact", "bounded", "editable"] { let ctx = crate::fonts::test_context(); let action = Cell::new(Action::None); let trigger = Cell::new(None); @@ -972,6 +972,7 @@ fn navigation_dropdown_popups_own_escape_and_return_focus_without_canceling_the_ let response = match kind { "plain" => dropdown(ui, "styles", &mut choice, &options), "compact" => compact_dropdown_menu(ui, "styles", options[selected.get()], choices), + "bounded" => bounded_dropdown_menu(ui, "styles", options[selected.get()], 120.0, choices), _ => dropdown_menu_with_close_behavior( ui, "styles", @@ -1294,6 +1295,116 @@ fn esc_closes_the_text_menu_alone() { assert!(owner_saw_esc.get(), "with the menu closed, Esc reaches the owner again"); } +#[test] +fn bounded_dropdown_focus_announces_full_selected_source_with_a_nonempty_accessible_label() { + use std::cell::Cell; + fn visible_text(shape: &egui::Shape, clip: egui::Rect, value: &str) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.text() == value && clip.contains(text.pos), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| visible_text(shape, clip, value)), + _ => false, + } + } + let long_source = "CPU retained image with a complete captured shot name that exceeds the bounded toolbar width"; + for variant in ["bounded", "regular", "compact", "outside"] { + let current = if variant == "bounded" { long_source } else { "Add Light" }; + for labelled in [false, true] { + let ctx = crate::fonts::test_context(); + ctx.enable_accesskit(); + let id = Cell::new(None); + let focus = Cell::new(false); + let rect = Cell::new(egui::Rect::NOTHING); + let chosen = Cell::new(false); + let mut draw = |ui: &mut Ui| { + let picker = |ui: &mut Ui| { + if focus.get() { + // Give the real widget focus during this frame, before its + // native and kit metadata are emitted. No synthetic event. + ui.memory_mut(|memory| memory.request_focus(id.get().expect("the first frame captures the picker ID"))); + } + let choices = |ui: &mut Ui| { + if list_picker(ui, "source", current, true).clicked() { + chosen.set(true); + ui.close(); + } + }; + let response = match variant { + "bounded" => bounded_dropdown_menu(ui, "accessible_bounded_source", current, 120.0, choices), + "regular" => dropdown_menu(ui, "accessible_regular_source", current, choices), + "compact" => compact_dropdown_menu(ui, "accessible_compact_source", current, choices), + _ => dropdown_menu_with_close_behavior( + ui, + "accessible_outside_source", + current, + egui::PopupCloseBehavior::CloseOnClickOutside, + choices, + ), + }; + id.set(Some(response.id)); + rect.set(response.rect); + }; + if labelled { + row(ui, "Retained source", picker); + } else { + picker(ui); + } + }; + menu_frame(&ctx, vec![], &mut draw); + let initial_rect = rect.get(); + focus.set(true); + let output = menu_frame(&ctx, vec![], &mut draw); + assert!(ctx.memory(|memory| memory.has_focus(id.get().unwrap()))); + let event = output.platform_output.events.last().expect("focusing the actual picker must announce its value"); + assert!(matches!(event, egui::output::OutputEvent::FocusGained(_)), "the final announcement must describe actual focus: {event:?}"); + let info = event.widget_info(); + assert_eq!(info.role, egui::Role::ComboBox); + assert!(info.enabled); + let expected = if labelled { crate::i18n::tr_label("Retained source") } else { current }; + assert_eq!(info.label.as_deref(), Some(expected)); + assert!(!info.label.as_deref().unwrap().trim().is_empty()); + assert_eq!( + info.current_text_value.as_deref(), + Some(current), + "the visual ellipsis cannot replace the full selected source in focus metadata" + ); + let update = output.platform_output.accesskit_update.as_ref().expect("the native accessibility tree must describe the focused picker"); + let pickers: Vec<_> = update.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::ComboBox).collect(); + assert_eq!(pickers.len(), 1, "the real picker has one native accessibility node"); + let node = &pickers[0].1; + assert_eq!(node.label(), Some(expected)); + assert_eq!(node.value(), Some(current), "the native screen reader receives the complete selected source"); + assert!(!node.is_disabled()); + if variant != "bounded" { + assert!( + output.shapes.iter().any(|shape| visible_text(&shape.shape, shape.clip_rect, current)), + "the accessible bare/row picker value is also the actual visible control text" + ); + } + assert_eq!(rect.get(), initial_rect, "accessibility focus leaves the actual dropdown layout unchanged"); + assert!(!chosen.get(), "focus cannot select an action"); + if !labelled { + // egui's simple TTS description reads ComboBox labels; its native + // AccessKit tree above also carries the separate selected value. + assert!(output.platform_output.events_description().contains(current)); + } + // The same real control remains clickable and its choice closes under + // either dismissal policy. No test-synthesized accessibility event. + focus.set(false); + menu_frame(&ctx, pointer(rect.get().center(), true), &mut draw); + menu_frame(&ctx, pointer(rect.get().center(), false), &mut draw); + menu_frame(&ctx, vec![], &mut draw); + assert!(egui::ComboBox::is_open(&ctx, id.get().unwrap()), "{variant}: actual dropdown opens"); + let choice = scenario::handle_at("dialog:list:source").expect("the actual popup choice is visible"); + menu_frame(&ctx, pointer(choice, true), &mut draw); + menu_frame(&ctx, pointer(choice, false), &mut draw); + menu_frame(&ctx, vec![], &mut draw); + assert!(chosen.get(), "{variant}: actual pointer activates the chosen action"); + assert!(!egui::ComboBox::is_open(&ctx, id.get().unwrap()), "{variant}: accepted action closes its popup"); + assert_eq!(rect.get(), initial_rect, "choice activation keeps the actual control geometry"); + } + } +} + #[test] fn a_track_number_adds_up_and_a_sign_adds_to_the_value_now() { let typed = super::relative_number; diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 5ec93f8c8..03c4b4f9d 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -1457,6 +1457,9 @@ const ELEMENTS: &[Element] = &[ element!("number_field", |ui, _| { number_field(ui, &mut 3_u32, 1..=200, 1.0, ""); }), + element!("number_field_preserving", |ui, _| { + number_field_preserving(ui, &mut 256_u32, 1..=64, 1.0, ""); + }), element!("number_fields", |ui, _| { row(ui, "Target", |ui| { number_fields(ui, &mut [-18.0, 125.5, -18.0], -1e9..=1e9, 0.1, ""); @@ -1470,6 +1473,25 @@ const ELEMENTS: &[Element] = &[ list_picker(ui, "preset", "Preset", true); }); }), + element!("bounded_dropdown_menu", |ui, state| { + let choices = [ + "CPU lens acceptance with a long captured shot name for the retained image", + "GPU lens acceptance with a second long captured shot name for the result", + ]; + let selected = state.selected.min(choices.len() - 1); + let width = ui.available_width().min(Tokens::get().form_card_width * 0.75); + let response = bounded_dropdown_menu(ui, "gallery_bounded_menu", choices[selected], width, |ui| { + for (index, label) in choices.iter().enumerate() { + let response = list_picker(ui, &format!("bounded:{index}"), label, selected == index); + if response.clicked() { + state.selected = index; + ui.close(); + } + response.on_hover_text(*label); + } + }); + response.on_hover_text(choices[selected]); + }), element!("dropdown_menu_with_close_behavior", |ui, s| { dropdown_menu_with_close_behavior(ui, "gallery_editable_menu", "Preset", egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { text_field(ui, &mut s.value, "Filter…"); diff --git a/crates/ui-egui/src/ui_kit/stages.rs b/crates/ui-egui/src/ui_kit/stages.rs index 0b5fb9039..465d66411 100644 --- a/crates/ui-egui/src/ui_kit/stages.rs +++ b/crates/ui-egui/src/ui_kit/stages.rs @@ -89,12 +89,14 @@ impl StageBar { super::text::paint_text(ui, rect.shrink2(vec2(t.space_4, 0.0)), &label, font, t.text_dim, true); } - /// Quiet information chip within the tools row, using the shared surface and ink tokens. - pub(crate) fn note(ui: &mut Ui, label: &str) -> egui::Response { + /// Quiet information chip with a bounded, single-line label and shared surface/ink tokens. The caller supplies + /// the full-text tooltip when the surrounding row must keep its actions reachable. + pub(crate) fn note_bounded(ui: &mut Ui, label: &str, max_width: f32) -> egui::Response { let t = Tokens::get(); let width = ui.painter().layout_no_wrap(label.into(), egui::FontId::proportional(t.font_label), t.text_dim).size().x; - let (rect, response) = - ui.allocate_exact_size(vec2(width + t.space_14 + t.space_6 + t.space_8 * 2.0, t.control_height - t.space_2), Sense::hover()); + let width = width + t.space_14 + t.space_6 + t.space_8 * 2.0; + let width = width.min(max_width.max(t.control_height)); + let (rect, response) = ui.allocate_exact_size(vec2(width, t.control_height - t.space_2), Sense::hover()); ui.painter().rect_filled(rect, t.control_radius, t.dialog_footer); let icon = Rect::from_center_size(pos2(rect.left() + t.space_8 + t.space_14 / 2.0, rect.center().y), vec2(t.space_14, t.space_14)); crate::icons::paint_ink(ui.painter(), icon, "help", t.text_dim); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index e5436cd3e..92c183f71 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -535,6 +535,9 @@ pub(crate) fn scene_pick_slack(app: &SolveApp) -> f64 { } pub fn projection(app: &SolveApp, rect: Rect) -> Proj { + // Product paint, control-channel world coordinates, navigation and picking share + // one camera frame. The helper leaves explicit subframes and Design unchanged. + let rect = crate::render_workspace::camera_rect(app, rect); let mut cam = app.cam; // Render owns an explicit product camera, including its saved/custom FOV. if !crate::render_workspace::active(app) { @@ -2727,6 +2730,11 @@ pub(crate) fn pick_through(app: &SolveApp, proj: &Proj, pos: Pos2) -> Vec { } fn pick_with_sketch_points(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool) -> Vec { + // Gray canvas can navigate but cannot supply an invisible surface for selection, + // cursor orbit or surface zoom beyond the rendered image's captured camera frame. + if crate::render_workspace::active(app) && !app.preferences.render_legacy_image_defaults && !proj.rect.contains(pos) { + return Vec::new(); + } let mut hits = pick_hits(app, proj, pos, other_sketch_points, false, true, false); // A Single hole's face place snaps to the face's centre and its round edges' centres. crate::hole_place::snap_hits(app, proj, pos, &mut hits); @@ -2787,6 +2795,10 @@ impl Near { } fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, all: bool, include_midpoints: bool, through: bool) -> Vec { + // Select Other and tool picks share the same visible-image boundary as ordinary picks. + if crate::render_workspace::active(app) && !app.preferences.render_legacy_image_defaults && !proj.rect.contains(pos) { + return Vec::new(); + } let s = &app.session; let st = crate::open_meshing::shown_world(app); let bounds = body_bounds(app, &st); @@ -4001,9 +4013,21 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { app.session.visibility.hidden_folders.hash(&mut h); // How strongly print faces are tinted (Preferences › General › Slicer). app.preferences.print_face_highlight.to_bits().hash(&mut h); + image_target_outlines(app).hash(&mut h); h.finish() } +/// Product pixels must stay visible while their appearance target is selected. +fn image_target_outlines(app: &SolveApp) -> bool { + crate::render_workspace::active(app) && !app.preferences.render_legacy_image_defaults && crate::render_workspace::live::has_picture(app) +} + +/// Display-only triangle-mesh polylines are not modeling edges. Targets without +/// drawable pickable boundaries keep their existing face/body fill feedback. +fn has_pickable_outline(mesh: &solidcraft_engine::geom::Mesh) -> bool { + mesh.edges.iter().enumerate().any(|(index, edge)| edge.len() >= 2 && mesh.edge_pickable(index)) +} + pub(crate) fn highlight_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); highlight_geometry_key(app).hash(&mut h); @@ -4246,6 +4270,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { let gpu_lit = |b: &solidcraft_engine::doc::ModelBody| !dragged.contains(b.name.as_str()); // Faces lit over the model use the triangles the model shows them with. let product = crate::render_workspace::active(app); + let outlines = image_target_outlines(app); // Bodies a Move dialog moves are lit where they stand (as they are picked). While its triad // is dragged they aren't lit at all, so the highlight is built again once, when it lets go, // rather than every frame. @@ -4447,19 +4472,34 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { // Lit, not flat: an imported mesh (STL, OBJ) is one face, and a flat fill would // paint the whole part as a single silhouette. if let Some(b) = by_name.get(body).filter(|_| app.body_visible(body) && !replaced(body)) { - face_tris(&mut feedback, &shown(b), *index, c4(t.sel_face), true); - hidden_face_outline(&mut feedback, &drawn(b), *index, t.sel_edge); + let m = shown(b); + if outlines && has_pickable_outline(&m) { + for (ei, e) in m.edges.iter().enumerate() { + if m.edge_pickable(ei) && m.edge_faces.get(ei).is_some_and(|faces| faces.iter().any(|f| *f as usize == *index)) { + edge_lines(&mut feedback, e, selected_edge, 2.0, &[]); + } + } + } else { + face_tris(&mut feedback, &m, *index, c4(t.sel_face), true); + hidden_face_outline(&mut feedback, &drawn(b), *index, t.sel_edge); + } } } Sel::Body { name } => { if let Some(b) = by_name.get(name) && app.body_visible(name) { - let lit = WholeBody { selected: true, colour: c4(t.body_selected) }; - if !(gpu_lit(b) && light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut selected_instances)) { - let m = shown(b); - let count = b.body.face_count(); - mesh_tris(&mut feedback, &m, c4(t.body_selected), true, |f| (f as usize) < count); + if let Some(m) = outlines.then(|| shown(b)).filter(|mesh| has_pickable_outline(mesh)) { + for (_, e) in m.edges.iter().enumerate().filter(|(ei, _)| m.edge_pickable(*ei)) { + edge_lines(&mut feedback, e, selected_edge, 2.0, &[]); + } + } else { + let lit = WholeBody { selected: true, colour: c4(t.body_selected) }; + if !(gpu_lit(b) && light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut selected_instances)) { + let m = shown(b); + let count = b.body.face_count(); + mesh_tris(&mut feedback, &m, c4(t.body_selected), true, |f| (f as usize) < count); + } } } } @@ -4579,12 +4619,13 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { if faces.is_empty() { continue; } - let m = drawn_mesh(app, b); + let m = if outlines { shown(b) } else { drawn_mesh(app, b) }; + let use_outlines = outlines && has_pickable_outline(&m); let base = body_color(&s.doc, b).unwrap_or(t.body); let k = t.hover_face_lift; let hover_col = [base.r().saturating_add(k), base.g().saturating_add(k), base.b().saturating_add(k), 255]; let selected_body = selected_whole.contains(b.name.as_str()); - if !selected_body { + if !selected_body && !use_outlines { // A whole body the model draws from a plan is lit by redrawing the plan's own // evaluated triangles, not by building every triangle again (see `highlight_plan`). let lit = WholeBody { selected: false, colour: hover_col }; @@ -4617,11 +4658,13 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { if let Some(b) = st.body(body) { let k = t.hover_face_lift; let c = body_rgb(app, body); - let m = drawn(b); + let m = if outlines { shown(b) } else { drawn(b) }; let patch = m.surface_patch(*index); - let lit = shown(b); - for &f in &patch { - face_tris(&mut feedback, &lit, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true); + if !(outlines && has_pickable_outline(&m)) { + let lit = shown(b); + for &f in &patch { + face_tris(&mut feedback, &lit, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true); + } } for (e, _) in m.edge_faces.iter().enumerate().filter(|(_, fs)| fs.iter().any(|f| patch.contains(&(*f as usize)))) { if let Some(p) = m.edges.get(e) @@ -7201,7 +7244,7 @@ pub(crate) fn refresh_layout(app: &mut SolveApp, ctx: &egui::Context) { // OK and Cancel in the view's corner (#6709) take the top right; the axis view goes below. let corner = crate::view_confirm::size(app); let style = app.preferences.navigator_style; - app.viewport.layout = Some(if crate::render_workspace::active(app) { + let layout = if crate::render_workspace::active(app) { let navigation = if app.ui.show_navigation_bar { crate::navigation_bar_view::measured(app, ctx, content).rect } else { Rect::NOTHING }; if app.preferences.render_inspector_side == "left" { crate::viewport_layout::Layout::product_left(rect, content, &docks, ctx.pixels_per_point(), style, corner, navigation) @@ -7212,7 +7255,15 @@ pub(crate) fn refresh_layout(app: &mut SolveApp, ctx: &egui::Context) { let content = if app.ui.layout == crate::shell::LayoutMode::Docked { rect } else { content }; let navigation = if app.ui.show_navigation_bar { crate::navigation_bar_view::measured(app, ctx, content).rect } else { Rect::NOTHING }; crate::viewport_layout::Layout::with_content(rect, content, &docks, ctx.pixels_per_point(), style, corner, navigation) - }); + }; + // Cache the exact product camera projection as well as its Fit room. + // Controls retain their outer content/axis/navigation rectangles. + let layout = if crate::render_workspace::active(app) && !app.preferences.render_legacy_image_defaults { + crate::render_workspace::picture_layout(app, &layout) + } else { + layout + }; + app.viewport.layout = Some(layout); } } @@ -7241,7 +7292,7 @@ fn axis_center(app: &SolveApp, rect: Rect) -> Pos2 { pub(crate) const AXIS_CENTER_LIFT: f32 = 4.0; pub(crate) fn axis_rect(app: &SolveApp, rect: Rect) -> Rect { - app.viewport.layout.as_ref().filter(|l| l.viewport == rect).map(|l| l.axis_view).unwrap_or_else(|| { + app.viewport.layout.as_ref().filter(|l| l.viewport == crate::render_workspace::camera_rect(app, rect)).map(|l| l.axis_view).unwrap_or_else(|| { let size = axis_view_size(app.preferences.navigator_style); Rect::from_min_size(pos2(rect.right() - size, rect.top()), vec2(size, size)) }) diff --git a/crates/ui-egui/src/viewport_layout.rs b/crates/ui-egui/src/viewport_layout.rs index bfe877be1..0bce3f39f 100644 --- a/crates/ui-egui/src/viewport_layout.rs +++ b/crates/ui-egui/src/viewport_layout.rs @@ -5,7 +5,7 @@ use solidcraft_engine::geom::Aabb3; use solidcraft_engine::geom::prelude::*; use solidcraft_engine::render::Camera; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct Layout { pub viewport: Rect, pub drawable: Rect, diff --git a/crates/ui-egui/src/viewport_layout_tests.rs b/crates/ui-egui/src/viewport_layout_tests.rs index 0f44ab7ea..e34507e4f 100644 --- a/crates/ui-egui/src/viewport_layout_tests.rs +++ b/crates/ui-egui/src/viewport_layout_tests.rs @@ -152,11 +152,23 @@ fn navigator_render_keeps_classic_probe_and_host_authored_lens_and_picture() { assert_ne!(h.app.view_fov(), fov); let layout = h.app.viewport.layout.as_ref().unwrap(); let picture = crate::render_workspace::picture_layout(&h.app, layout); - assert!(picture.viewport.width() < layout.viewport.width(), "the portrait frame must exercise a distinct projection"); + let outer = h.app.viewport.rect.unwrap(); + assert!(picture.viewport.width() < outer.width(), "the portrait frame must exercise a distinct projection"); for up in [solidcraft_engine::render::UpAxis::Z, solidcraft_engine::render::UpAxis::Y] { assert_navigator_shared_zoom(&h.app, Camera { up, fov, ..Default::default() }); } } + if measured { + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(4); + assert!(!crate::render_workspace::shot::overlay_visible(&h.app)); + let layout = h.app.viewport.layout.as_ref().unwrap(); + let usable = crate::shell::host_usable(&h.app).unwrap(); + let picture = crate::render_workspace::host_picture_layout(&h.app, layout, &usable).unwrap(); + let painted = crate::scenario::rect_of("render:product:frame").unwrap(); + assert!(painted.width() < h.app.viewport.rect.unwrap().width()); + assert_eq!(picture.viewport, painted, "host Fit and Centre must use the painted portrait even without guides"); + } } } diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md index fb4948cd8..7d2637d0b 100644 --- a/docs/book/src/reference/glossary.md +++ b/docs/book/src/reference/glossary.md @@ -303,6 +303,14 @@ component changes every copy. The browser names occurrences with a number, such - **Elsewhere:** occurrence, instance, component instance. - **For translators:** not a *pattern instance*. +### opaque path lighting + +Indirect diffuse and specular illumination computed by tracing finite light paths between opaque surfaces. Shown as **Indirect lighting (opaque surfaces)** in Sampling. + +- **In SolidCraft:** optional CPU `job.options.path` / runtime `raytrace.path`, enabled explicitly in Sampling. +- **Don't use:** ambient occlusion, glass, full optical parity. +- **For translators:** this describes light transport; it is unrelated to a modelling path or physical material density. + ### part number A design property that holds the identifier an organisation gives a design. @@ -312,6 +320,13 @@ A design property that holds the identifier an organisation gives a design. - **Don't use:** part number for a standard part's size. - **For translators:** see *Words with more than one meaning*, "part". +### path depth + +The maximum number of shaded surfaces in a rendering path, starting with the first visible surface. A depth of 1 uses direct lighting only; higher values allow more light bounces. This does not count CAD mesh vertices. + +- **In SolidCraft:** CPU `path.max_depth` is 1–16; longer paths are truncated. +- **For translators:** a count, not a geometric depth in millimetres or timeline depth. + ### pattern instance One copy that a pattern makes of its features, bodies or sketch entities. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 68a5712bf..9eb26c4b8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -983,6 +983,25 @@ Other `ui.prefs` parameters: Entering Render requires finishing the current modelling operation; returning restores the Design camera. See [the integrated Render workspace](render-workspace.md). +`ui.inspect.render.live` reads automatic image feedback without launching or pumping +work. It includes enabled/paused, pending/running, capture generation, isolated job, +completed passes, target, sequence, current/stale image and error. These job +identities belong to the live scratch session and cannot be exported or selected as +completed results through the original document session. `view.render_live {paused: +true|false}` pauses/resumes feedback through the registered command; its headless +form validates and echoes the request without changing a document. + +GPU adaptive checkpoints include optional `preview.adaptive` metadata in +`render.status` and `ui.inspect.render.live.adaptive`: `stage` is `pilot` or +`production`, `completed` and `target` count that phase's iterations, and +`pilot_samples`, `minimum_production_samples`, `maximum_production_samples` retain +the captured allocation bounds. The compatibility field `samples_per_pixel` is an +absolute completed pilot-plus-production iteration when this metadata is present; +it represents uniform SPP only when `adaptive` is absent. The checkpoint target is +the validated pilot count plus maximum production count. Pilot images never enter +the final image or raw master, and production iteration counts are not uniform +per-pixel sample counts. + ### Sketch alignment guides `ui.prefs {sketch_tracking_guides: true}` enables temporary horizontal and vertical dotted diff --git a/docs/render-aging.md b/docs/render-aging.md index 7a9108232..5765a1f98 100644 --- a/docs/render-aging.md +++ b/docs/render-aging.md @@ -8,7 +8,7 @@ The read-only `render.scene` reply exposes `stable_target` beside each captured The editor saves that identity, not `ordinal` or an unqualified visible name. Check and Start resolve it against the current scene; a hidden, removed or replaced occurrence requires explicit rebinding. Another body's insertion/reordering does not -retarget a layer. The runtime-only GPU job still receives its captured index/name pair. +retarget a layer. The runtime-only CPU or GPU job receives its captured index/name pair. The procedural field origin remains world-anchored; this does not add object-local weathering motion or change physical geometry, material cards or mass. @@ -18,3 +18,44 @@ explicitly refused with a rebinding message. Keep the original file and rebind i compatible development build; never strip the target or silently make it global. `format/pending/render-stable-aging-targets.rs` records the new saved concept without editing published numbers or migrations. + + +## CPU evaluation contract + +A CPU raytrace job can preserve the same optional `options.aging` stack and stable +saved targets. Empty or absent stacks retain the preceding saved JSON and CPU PNG +arithmetic. An inactive stack retains its bounded parameters without adding a +material continuation or consuming extra transport work. Check and Start refuse +missing/replaced/hidden targets explicitly. This is optical authorship: engineering +material cards, geometry, visibility, emission and mass are unchanged. + +An active stack is evaluated once for each hit before the shared opaque closure. +Direct lighting, opaque path response/PDF/sampling and first-hit denoising guides +use that same result. The worker reuses one fallibly reserved, prepaid material +slot for the guide prepass and then transport. Each layer is a charged resumable +continuation; cancellation or cumulative-work exhaustion cannot advance that +layer or commit an incomplete camera pass. No extra image plane or RNG stream is +introduced. The raw EXR captures the aged transport before denoising/presentation. + +Layer order, original pre-aging metallic class, exact body targeting, upward bias +from the original outward geometric normal, RGB/roughness/metallic changes and +clear-coat weight attenuation follow the existing ordered layer contract. Coat +roughness and IOR, shading/geometric normals, emission and topology are preserved. +World millimetres are evaluated in f64 after subtracting the explicit authored +origin; the camera never defines the CPU field. Noise repeats every 4096 cells, +while directional Scratch bands use their separate `floor(0.8*q)` identity. + +Certified dielectric boundaries and passive stage geometry are not aged. An +explicit certified-glass target is refused. CPU aging cannot replace independently +authored anisotropic roughness axes; that combination retains its values and is +refused explicitly. The legacy selected rough-reflection HDR path also refuses +layers that would introduce a diffuse lobe it cannot carry; keeping metallic aging +or explicitly selecting opaque path transport avoids silently discarding energy. +Other existing transport/geometry/coat/HDR restrictions remain in force. This +consumer does not add CPU texture-map support or broaden dielectric transport. + +`format/pending/cpu-aging.rs` records the additional CPU saved concept. The staging +artifact is source preparation only: its newly added tests, target layouts, native +CPU jobs, UI controls and saved reopen journeys are UNCOMPILED/UNRUN until the +integration branch's serial qualification executes them. GPU Scratch camera-rebase +precision/phase work is tracked separately and is not a CPU-parity validation claim. diff --git a/docs/render-backends.md b/docs/render-backends.md index d6fdb5c76..0087933b4 100644 --- a/docs/render-backends.md +++ b/docs/render-backends.md @@ -75,13 +75,15 @@ user-selectable engine families. An installed CPU host advertises `cpu-product` first. A real native CPU worker with `raytrace-cpu` compiled in also advertises `cpu-raytrace`; cooperative hosts and builds without that feature do not. A stopped native host retains an unavailable descriptor. -The second method supports preview PNG with PBR, HDRI and the bounded CPU refraction -contract: certified thin sheets or axis-aligned closed boxes. This is not arbitrary -closed-solid glass, EXR or final-mode rendering. Its separate -[CPU progressive option](render-cpu-progressive.md) accumulates bounded camera -samples and publishes provisional complete passes of the existing transport; -it does not add global illumination. Geometry, material combinations and resource -admission still validate the actual request. +The second method supports PNG with PBR, HDRI and explicit CPU optical contracts. +Without Path, dielectrics remain certified sheets or strict axis-aligned boxes. +Explicit [CPU Path](render-cpu-path.md) adds indirect lighting and its certified +general-Glass domain. [Progressive sampling](render-cpu-progressive.md) publishes +complete provisional passes; compatible output options retain a final raw EXR. +The profile's Preview mode is metadata, not a claim of final image quality. +Geometry, material combinations and resource admission still validate each request. +See [the detailed parity matrix](render-parity.md); a generic Refraction feature +flag never proves that every boundary or combination is supported. The `cpu-raytrace` ID is reserved for this native method, including while it is absent; applications cannot register another image or viewport host under that name. diff --git a/docs/render-built-in-library.md b/docs/render-built-in-library.md index 8df81b094..3ce735417 100644 --- a/docs/render-built-in-library.md +++ b/docs/render-built-in-library.md @@ -1,14 +1,18 @@ # Built-in authored render library -**Integration-batch source, not yet a validated application release.** The application-facing adapters below are prepared in the personal render branch. Their compilation, regression execution and visual acceptance must be recorded on the frozen batch. Source-resource conformance from PR #6 is separate evidence. +The adapters below are in published source `00edaf6a`/tree `38a7f0af` and included +in CI7's document/engine/workspace suites. Full CI7 is red; no complete material +showcase or release acceptance is claimed. Native evidence uses an opaque Sample +Plate, not every library recipe. See [renderer parity](render-parity.md#qualification). +Original source-resource conformance remains separate evidence. ## Inventory and availability The Render panel now has a library section using the existing dropdown, list-picker, disclosure, number-field and theme-token components. Search is paginated; target search returns bounded name/ordinal pages rather than mesh payloads. The same operations are available through engine commands, CLI and MCP. -| Source | Prepared application projection | Explicit exclusions | +| Source | Application projection | Explicit exclusions | |---|---|---| -| 48 authored PBR surfaces | Uniform opaque assignment, or GPU planar color/normal/roughness/metallic maps | Height/displacement, manufacturing geometry and true anisotropic BRDF | +| 48 authored PBR surfaces | Uniform opaque assignment, or CPU/GPU built-in planar color/normal/roughness/metallic maps | Height/displacement, manufacturing geometry and true anisotropic BRDF | | 48 SELENE appearance recipes | Original uniform opaque baseline | The advanced-target properties listed in each recipe | | 24 HDR environment fields | Hash-verified, embedded CPU/GPU environment in a saved setup | Finite room geometry, parallax, contact floor and measured photometry | | Numeric rectangular/sun rigs | Exact emitter conversion at an explicit subject scale and center | Passive cards require an explicitly acknowledged emitters-only variant; calibration-blocked and externally owned sun rigs refuse | @@ -22,12 +26,17 @@ Original authoring manifests remain unchanged, including their `runtime_ready: f - `render.library.describe`: exact `kind` and `id`; returns the original entry and explicit variants/omissions. - `render.library.targets`: bounded body-name query and page; returns current ordinals, names, revision and captured scene bounds. - `render.library.appearance.apply`: `id`, `variant: "uniform_opaque"`, and 1..256 exact `bodies`. Uses ordinary appearance assignment, one undo, with explicit approximation acknowledgement. -- `render.library.surface.prepare`: `id`, exact `body_index` and `body_name`, optional origin, plane and repeat scale. Returns a GPU texture binding; does not assign a material or alter the document. The default origin is the target bounds center. Existing body IOR is retained. +- `render.library.surface.prepare`: `id`, exact `body_index` and `body_name`, optional origin, plane and repeat scale. Returns the built-in texture binding for an admitted CPU/GPU consumer; does not itself save a material or alter the document. The default origin is the target bounds center. Existing body IOR is retained. - `render.library.environment.apply`: `id`, setup `name`, optional typed setup `set` patch, authored rotation/intensity and explicit `replace_environment`. Embeds the original HDR and saves the setup atomically. Requires a CPU/GPU job but no installed device or source file. - `render.library.studio.prepare`: `id`, explicit `variant`, `center_mm` and `subject_extent_mm`. Returns numerical GPU lighting plus limitations and a geometry-clearance review requirement. - `render.library.studio.apply`: a prepared rig request, setup name/patch and `replace_lighting_and_environment: true`. Saves the selected emitter projection in one undo. Existing environment and lights are replaced only with that explicit confirmation. -The library browser only enables executable actions for their supported categories and selected executor. A stale target requires a fresh selection; an authored surface cannot silently replace a glass binding. GPU surface bindings remain temporary request state, as with existing optical bindings. Built-in image sources no longer depend on filesystem paths, but their body bindings are not yet document-portable. +The browser enables actions only for supported categories and the selected method. +A stale target requires revalidation; a surface cannot silently replace Glass. +Built-in surfaces use stable saved body targets for CPU/GPU and retain their +encoded resources for offline reopening. Glass and opaque coats have their own +saved bindings. External file mappings keep the existing GPU temporary-input +route; the separate portable external-PNG importer is not delivered here. ## Reproducible embedded sources @@ -62,3 +71,32 @@ A saved HDR with an authored solar disk cannot also retain an analytic sun. Appl ## Prepared verification Regression sources cover catalog counts/pagination, blocked concepts, exact hashes and channel roles, absent-file HDR persistence, orientation conversion, explicit appearance approximation, unchanged engineering metadata, body identity, scalar channels, positive normal basis, actual shared source storage, GPU buffer deduplication and GPU scalar output against a linear reference. Execution results are recorded separately after the batch is frozen. + +## Reviewed CPU studios and rigs + +Native studio reviews accept the explicitly selected CPU or GPU method. The CPU +projection preserves sampling, adaptive allocation, profile, camera, lens, optical +bindings, maps, aging, volume and output choices. It installs the same embedded +HDR identity/rotation/intensity, passive stage and explicit exposure. Existing CPU +HDR sample count is retained, or starts at 16 when none was authored. Native +three-light compositions keep their existing 1/16 radiance gain; it is not added to +direct rig imports. + +Direct CPU rigs keep exact authored achromatic area radiance and world-mm full +edges. They never retain the implicit three studio lights. The unchanged CPU area +intensity ceiling 64 means 16 of the 19 currently executable direct rigs refuse; +RIG-007, RIG-020 (Sun) and RIG-022 (black) fit this numerical projection. World, +clearance, feature and resource checks still apply. A refusal never clamps a light, +splits it, changes method or removes authored settings. + +A CPU Sun review without indirect lighting offers an explicit adoption action. +It adds path depth 8, progressive 16/seed 0 only if absent, one camera sample per +pass and traced shadows. Existing progressive/adaptive/profile intent is kept; +the complete prospective setup must validate before adoption plus rig replacement +publishes as one undo. Preparing, cancelling or painting a review does not save, +start a job or save unrelated viewport navigation. + +The CPU authoring engine, pointer and cold-capture renderer regressions are in the +published source tested by CI7. That scoped execution does not establish native +image quality for every rig; the recorded native scene is the opaque Sample Plate. +See [the qualification record](render-parity.md#historical-published-qualification). diff --git a/docs/render-clear-coat.md b/docs/render-clear-coat.md index 4d7c60fae..1b159466e 100644 --- a/docs/render-clear-coat.md +++ b/docs/render-clear-coat.md @@ -1,6 +1,41 @@ -# Runtime clear coat +# Clear coat for CPU and GPU images -Progressive image jobs accept an independent dielectric GGX coat over an opaque +The Appearance editor’s Clear coat section uses the same saved opaque coat for +CPU ray tracing and GPU path tracing. Select a whole body, enable the coat, edit +Weight, Roughness and IOR, then choose **Save coat to shot**. Edits are previewed +through a stable-target request overlay; painting the editor never saves them. +**Discard coat edit** restores the saved state. Replacing different saved numbers +requires the explicit Replace control. Removing a saved coat has a confirmation +and one Undo step. + +A saved setup carries `coats: [{target, coat: {weight, roughness, ior}}]` beside +its existing surface and optical bindings. `render.coat.bind` takes the exact +`render.scene` body ordinal/name and `expected_revision`, then stores the existing +stable definition/feature/component/occurrence identity. Check and Start resolve +that identity again. A hidden or replaced body is refused; a later body with the +same name or ordinal never inherits the coat. `render.coat.unbind` removes one +exact saved target without requiring a renderer. Empty lists are omitted, so old +setups retain their serialized shape. + +Both methods support the existing 64-target override bound, weight 0..1, +roughness 0.045..1 and relative IOR 1..3. All saved numbers are checked even at zero +weight. Saved coats require an opaque target and cannot share a Glass target, +including at weight zero. CPU selected reflection and anisotropy overrides also +cannot share a coated target. These unsupported combinations refuse without +clearing authored values. CPU direct shading and its explicit progressive Path +transport consume the same coat; raster remains schematic and refuses bindings. + +Saved maps may share an opaque coat target. They alter the substrate and shading +normal while retaining the coat parameters. Existing aging changes the substrate +and reduces coat weight by its physical layer mask; it keeps coat roughness/IOR +and never rewrites the saved coat. The guided denoiser operates on complete image +updates while the raw EXR remains unfiltered. Coat Save/Discard/Remove and saved +Undo/Redo preserve independent local map drafts. A conflicting external edit +keeps a pending local coat edit visible until it is discarded or reviewed again. + +## Existing GPU runtime override API + +GPU progressive image jobs accept an independent dielectric GGX coat over an opaque metallic/roughness substrate. A dark, moderately rough plastic base with a smooth coat can show narrow softbox reflections while retaining a dark body. Chrome uses the existing metallic surface; it does not need a coat. @@ -15,7 +50,9 @@ Weight is finite in [0,1], perceptual roughness in [0.045,1], and relative IOR i [1,3]. Unknown fields and repeated indices are errors. Weight zero is a no-op. Coats cannot be combined with runtime transmission on the same body. Overrides apply to the body and its faces in the job snapshot, never to the saved document, -preview, undo history or appearance format. They require progressive rendering. +engineering materials or source appearance. They require GPU progressive rendering. +The existing raw API retains its zero-weight no-op behavior; the saved binding +route above additionally requires an opaque target even at zero weight. The implementation adds single-scattering GGX/Smith coat reflection with its own Schlick Fresnel term. For cosine `c`, define the conservative directional bound diff --git a/docs/render-cpu-advanced-integration.md b/docs/render-cpu-advanced-integration.md index 6f668d746..d61e7979c 100644 --- a/docs/render-cpu-advanced-integration.md +++ b/docs/render-cpu-advanced-integration.md @@ -16,9 +16,16 @@ with 0xlillith's prior work. This integration adds no third-party assets, code, rendering library or dependency. The source identity is provenance, not proof that its old tests passed on this new combination. -## Connected capabilities +## Historical recovery capabilities -| Area | Actual consumer in this revision | Limits | +The following table records the original recovery tree above, not the complete +published renderer. Current Path Glass, coats, saved maps, adaptive sampling and +qualification are listed in [renderer parity](render-parity.md). In particular, +the current legacy box certificate accepts valid tiled box faces; it does not +require exactly 12 triangles. Historical test/provenance claims below stay scoped +to their recorded source. + +| Area | Original recovery consumer | Original recovery limits | | --- | --- | --- | | GGX visible-normal sampling (VNDF) | CPU `ImageTask` rough reflections and the certified anisotropic adapter | The original single-scattering Schlick/GGX/separable-Smith model; no layered coat transport, transmission proposal or diffuse GI. | | Fixed primary AA | Existing CPU image job and visible 1/4/16 sample controls | Reuse only for completed, nonselected primary hits within one fixed spatial sample. Not a progressive sample prefix. | @@ -39,8 +46,10 @@ runtime API inputs, outside portable setup persistence. Existing CPU primary AA, exposure, shadow and studio preset controls remain in place. The GPU material editor owns a different runtime schema selected explicitly with top-level `progressive: true`. CPU progressive sampling instead uses `raytrace.progressive` -and rejects area lights, dielectric and anisotropic overrides in its initial -bounded contract; the fixed CPU route retains those capabilities. +and supports the existing rectangular/continuous LED light integral with a fresh +film-aware sample identity. The subsequent progressive continuation also accepts +the existing certified thin-sheet/axis-aligned-box dielectric and planar anisotropy +subsets, preserving all geometry, HDR, clear-coat and optical-overlap checks. See [VNDF](render-vndf-prototype.md), [primary AA](render-primary-aa.md), [emission](render-surface-emission.md), [surface effects](render-surface-patterns.md) @@ -88,7 +97,7 @@ coat and dielectric path remains unchanged. Captured GPU `transmission` data is not reinterpreted as CPU dielectric options. CPU admission still certifies immutable captured body identities, retains opaque -alpha requirements, checks finite inputs and bounded capacities, and rejects +body/face alpha requirements, checks finite inputs and bounded capacities, and rejects unsupported intersections between optical, emission and surface selections. Geometry, document history, physical mass properties and saved materials are not modified by these runtime inputs. @@ -103,9 +112,18 @@ recovered tests are retained, with new integration regressions for preservation of clear coat, refusal of unmatched coat transport and exclusion of registered executors from CPU film reservations. -The integrator must compile and execute the exact combined revision, including -CPU feature on/off and the current `ImageTask` layout bound. Render/engine/UI -contracts, cancellation and lease tests, hostile inputs, wasm and project CI -remain gates. Real equal-camera CPU output and exported PNGs are still needed to -assess the visible results. Historical results from earlier source snapshots do -not qualify this revision. +Subsequent integration has executed CPU renderer, saved-document and engine +regressions, default-feature host metadata/digest checks, and an earlier-snapshot +Render workspace suite with CPU enabled and a real GPU required. That earlier +workspace result does not qualify the new combined CPU additions. The workspace +suite includes an actual CPU Render action and export of that job's retained +native master; see [CPU output presentation](render-cpu-output.md#focused-validation) +for the exercised scope. The source-only qualification above describes the +original recovery handoff. + +Each final combined revision still needs its repository-wide and platform checks, +including wasm, plus native equal-camera image acceptance. Historical results +from earlier source snapshots do not qualify later changes. + + +The optional [CPU opaque path lighting](render-cpu-path.md) consumer is part of the combined source and has executed renderer regressions. It adds bounded progressive diffuse/specular GI only when `path` is authored; existing restrictions and bytes above describe the absent-path route. Mixed glass/anisotropy/volume parity and combined document/engine/UI/native qualification remain incomplete. diff --git a/docs/render-cpu-celestial.md b/docs/render-cpu-celestial.md new file mode 100644 index 000000000..a3e69990d --- /dev/null +++ b/docs/render-cpu-celestial.md @@ -0,0 +1,76 @@ +# CPU finite Sun and gradient Sky + +This source change adds the shared finite Sun and gradient Sky intent to CPU ray +tracing with explicit Indirect lighting (`options.path`). It is an opt-in transport +extension; selecting a light never enables GI or replaces another environment. +Raster remains schematic. The implementation and its renderer, saved/runtime and +pointer-UI tests are included in published `00edaf6a`/tree `38a7f0af` and executed +by CI7. Full CI7 remains red, and dedicated native Sun/Sky or Glass image-quality +acceptance remains pending; see [qualification](render-parity.md#qualification). + +`CpuJob.sun` uses the existing Sun direction, angular radius in radians +(0.001…π/2), and relative linear-sRGB radiance (0…100,000,000 per channel). +It is distinct from a hard directional source: a hard source retains +`angular_radius_rad: None`, and the zero-radius/default route keeps its existing +producer/RNG/work behavior. The optional Sun shares the eight-directional limit; +point/spot and rectangle limits are unchanged. + +`CpuJob.sky` uses the existing portable `SkyEnvironment::Sky` fields: linear +zenith/horizon/ground RGB, world-Z axis, rotation within ±1,000,000 radians and +intensity 0…100. Its radiance is the same unchanged f32 gradient at the GPU's 256 +row centres. Longitude rotation is retained but this axisymmetric gradient is +invariant under it. CPU evaluates a selected row directly; it does not generate +an HDR image, quantize to RGBE or allocate an environment plane. CPU uses uniform +solid-angle proposals; GPU uses its existing alias-table proposals. This is the +same radiance target, not a claim of equal convergence or CPU/GPU pixel identity. + +Constant, Sky and HDR illumination are exclusive sources. Finite Sun is additive +with any one of them. HDR retains its existing declared-primary policy, intensity +limit 64 and direct sample count; Sky takes one NEE proposal per shaded bounce. +The built-in HDR library requires explicit replacement consent and refuses an +analytic Sun when the selected HDR already owns its solar disk. Generic HDR bytes +have no inferred solar ownership. Display backplates remain separate from light. + +CPU Path samples the finite Sun uniformly over its cap. Environment and Sun NEE +and escaped BSDF contributions each use their own power weight against the same +material PDF, with the actual competitor count and depth endpoint. Delta Glass +escape receives full emitter weight after the existing physical Beer segments. +Nearest geometry/area-emitter endpoints, thin-shadow continuation and certified +nested origins retain their existing contracts. Infinite NEE connections through +closed Glass are still outside the existing supported connection domain, as in +the GPU consumer; this does not add caustic or closed-interface NEE support. + +Effects → Maps → Aging still supplies the shared BRDF/PDF and guide material. +Sky/Sun add no guide or snapshot plane. Optional Sun/Sky boxes are billed at actual +`size_of` in the retained request and both owned producer option copies. The +unchanged 4096-byte task slot must contain the enlarged inline option headers; +the static size assertion is retained. The retained Record's optional Sun/Sky +headers and inline Volume header are summed once by the shared fixed metadata +helper on every captured request, including raytrace=None. Regrade pays the same +actual-size sum in its retained request lease, independently of its presentation/ +master lease and without duplicating source texture/HDR costs. Thus default +pixels/work/buffers stay identical, but its admission metadata estimate honestly +includes this sizeof delta; no previous layout is fabricated. Every new Sun stage consumes the existing +cumulative work ledger before mutation, and the next bounded host quantum observes +cancellation. None skips that stage and allocates no celestial heap state. + +The common light editor saves/loads/filters finite Sun on either renderer. CPU +Sky is available from the Environment source picker only with explicit Indirect +lighting. Numeric load, Undo and environment edits preserve the shot camera. +When a Sun/Sky setup switches between CPU and GPU, its exact source values and +common rig are converted prospectively. Incompatible domains refuse atomically. +For GPU→CPU with no CPU Path, a separate reachable method action explicitly plans +Indirect depth, CPU progressive SPP/seed and traced shadows, then validates and +persists one Undo transaction. It retains the chosen CPU profile, adaptive policy, +presentation, lens and saved scene intent; it never raises a cap or clamps depth. +The same transaction includes an authored Atmosphere box, so a combined setup +never uses sequential effect writes or an obsolete GPU-only Volume refusal. +Atmosphere still refuses incompatible Glass/SSS, noise reduction and transmission +strata without clearing their values. + +The published suites cover independent per-ordinal/energy cases, HDR addition, +complete PNG prefixes, raw FLOAT32 masters, lens/adaptive/certified-Glass routes, +map/aging closure, work/cancel and retained capacity, plus saved/common API and +pointer-UI fixtures. Native preview/final/export/reopen evidence for each such +optical combination remains separate. Results from an earlier binary or source +do not qualify a new implementation. diff --git a/docs/render-cpu-general-glass.md b/docs/render-cpu-general-glass.md new file mode 100644 index 000000000..b3771786e --- /dev/null +++ b/docs/render-cpu-general-glass.md @@ -0,0 +1,173 @@ +# CPU general Glass with indirect lighting + +The published implementation is in commit `00edaf6a`, source tree `38a7f0af`. +Full CI7 ran the renderer, document, engine and UI tests; the renderer passed 744 +tests and all 433 Render workspace tests passed. Full CI7 remains red in other +listed tests. The native Sample Plate evidence used opaque geometry, so it does +not qualify a native Glass image. See [capabilities and qualification](render-parity.md). + +The Glass follow-up in this change prepares and retains the complete general-Glass +certificate for Check and Start. The editor merges saved and prospective targets +without saving the draft; checked file HDR capture keeps those stable identities. +See [PR #11087](https://github.com/tangency-labs/solidcraft/pull/11087) for this +follow-up's exact source and qualification; the historical CI7 and opaque native +results above remain separate. + +CPU **Indirect lighting** (`options.path`) can consume up to eight stable saved or +exact captured optical assignments. It requires explicit progressive camera +sampling, one primary attempt and traced shadows. Path depth remains 1–16 and counts +shaded opaque surfaces, optical boundaries and active scattering events. An endpoint beyond this finite +limit contributes no further radiance; the limit is not a convergence guarantee. +There is no default, size, camera, profile or method change. Fixed saved choices +require explicit adoption through Sampling or the CPU Glass transport section. +GPU-only Fresnel strata and the GPU nested-media flag are not CPU controls. + +Without `path`, the original planar sheet and strict axis-aligned box consumer, +deterministic Fresnel branch tree, camera stream, raw pixels and cumulative work +remain unchanged. Existing saved `closed_mesh` intent still lowers to that box +subset in this route. With `path`, `closed_mesh` instead selects the new certificate +and continuation. Explicit `closed_box` keeps its existing strict shape check. +No saved optical number, engineering geometry, physical material or mass changes. + +The new certificate checks the **actual captured f64 triangle positions**. It does +not trust a closed flag, tolerance-weld seams, move vertices or repair triangles. +Signed zero shares an exact coordinate identity. Closed targets require exactly +two oppositely wound faces per edge, one connected shell and one connected circular +link at every exact coordinate vertex. A pinched vertex fails the link check even +when edge incidence and global connectivity pass. Adaptive exact predicates reject +intersection, non-topological contact, coplanar overlap and self-intersection. +Coordinates must be zero or have magnitude at least 2^-128 mm within the existing +1e12 mm world bound; this conservative predicate domain prevents underflow rather +than snapping small coordinates. An exact signed dyadic volume proves outward +orientation using a fixed 12-limb integer accumulator, not rounded volume or an +approximate ray-crossing witness. Imported or computed seams that are not exactly +closed refuse with their authored data intact. + +Separated bounds use the existing fast disjoint test. Overlapping selected closed +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. +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. + +Each perspective primary ray classifies its physical eye or sampled lens pupil +before any opaque hit or analytic emission. Exact half-open crossings initialize +the ordered nested medium stack; Beer absorption starts at that physical origin, +including opaque or emissive first hits inside Glass. Orthographic rays retain +their established before-bounds origin. A conservative bounds fast path avoids +classification work and allocation for unambiguous outside rays. Ambiguous samples +use one reusable prepaid state and a cooperative BVH scan. An actual boundary at +the origin or in the eye/pupil-to-near-clip segment refuses explicitly; endpoints +outside a small object do not bypass the segment check. No camera, ray or boundary +is moved to manufacture an outside origin. +The single path carries an eight-entry medium stack. Every segment uses the +previous physical surface point for Beer absorption, before any numeric launch +adjustment. Geometric winding chooses entry/exit and verifies the certified parent. +Smooth captured optical normals are used only if both reflected and refracted +directions stay in the correct geometric hemispheres; otherwise the original +geometric normal is used. Snell, exact unpolarized Fresnel, total internal +reflection and the radiance IOR ratio are reused from the original f64 optics. +On-boundary continuations exclude only the producing body's exact source plane; +they do not consume a short segment with a finite normal offset. + +Each Fresnel event chooses one counter-sampled delta branch. It creates no ray tree, +extra image plane or extra camera sample. Its domain uses the existing per-pixel, +per-ordinal, per-depth identity, including independent adaptive pilot seeds and the +original production seed. Reflected or refracted paths give directly reached HDR or +rectangle emission full delta weight. Opaque hits retain the complete existing +Effects→Maps→Aging closure before every BRDF/PDF and denoising guide use. Maps remain +unsupported on an optical target; unrelated opaque maps and aging remain active. + +Thin-sheet transmitted shadows have an ordered closest-interface continuation. +They apply RGB parallel-sheet Beer/Fresnel transmission and carry the transmission +branch probability into the original light/BSDF sample-count MIS. If the remaining +finite depth cannot realize the competing BSDF chain, light weight is one. Finite +area connections retain geometry-wins-endpoint ties; point/spot connections retain +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. +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. + +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 +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 +proof slot by `sizeof(CertifiedOptics)`, including its Vec header; its outer Vec +header remains in the existing fixed metadata allowance. The ready cursor's +allocation moves into the image task, with its prior work charged once. Its +source-specific qualification is recorded in +[PR #11087](https://github.com/tangency-labs/solidcraft/pull/11087). Source-plane +cursor state is billed by the actual existing pixel and path slot sizes. No cap or static guard is raised. Contact and containment can +require quadratic work, so a valid large mesh can exhaust its selected profile +without producing a partial certificate or image. The fixed 4096-byte host slot and +all frame/metadata bounds remain compilation gates. The inside-origin increment +adds one conditional exact-capacity state slot, prepaid by its actual size; its +fixed BVH stack visits one node or primitive per charged step and is reused across +camera samples. It adds no image plane, additional ray, random draw or new cap. + +Renderer regressions cover exact contacts, pinched vertices, rotated and arbitrary +closed meshes, outward sign under large-coordinate cancellation, nested physical +Beer lengths, independent per-ordinal Fresnel paths, real HDR and area endpoints, +opaque contact material, thin-shadow/BSDF MIS with 1/4/16/64 source samples, every +PNG prefix, worker quanta, raw EXR identity, adaptive pilot discard, cancellation, +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. + +## 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. +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. + +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. + +Active scattering requires Path and disabled surface denoising, matching the +existing GPU random-walk compatibility domain. Thin sheets and Path=None retain +an explicit refusal, including authored inactive options on the legacy route. +With Path, `Some(rate0)` stays authored and adds no random draw, continuation work +or pixel/PNG/raw change. The pending collision/source-plane metadata is charged +through actual `sizeof(State)`, and captured optical storage uses actual element +sizes; this is not a promise of unchanged metadata admission bytes across builds. +The existing prepaid classifier slot is reused, with a debit before each scan or +transition. With active scattering, opaque bounce and direct-light rays also start +at the physical surface: a charged one-primitive-at-a-time range walk reuses the +existing exact source-plane cursor. This avoids consuming collision/absorption +distance through a normal offset; inactive options keep the old launch path. Nonrepresentable event positions or collapsed source/endpoint-plane +positions refuse instead of being moved by an epsilon. All existing profile, +4096-byte host-task and 1024-byte frame-metadata limits remain unchanged gates. + +Regressions cover independent exponential survival, HG CDF/density mass +and first moment, per-ordinal first-hit eye/lens/nested Beer and slab walks, +contained light/BSDF survival MIS at 1/4/16/64 source samples, inactive identity, +white furnace, every complete prefix, quanta, raw/alpha/finishing/adaptive pilot +separation, cancellation/work exhaustion and saved/runtime/pointer save/reopen. +Their execution is covered by the published renderer suite, not by the opaque +native Sample Plate capture. See +[PR #11087](https://github.com/tangency-labs/solidcraft/pull/11087) for the Glass +follow-up's exact source and executed qualification scopes. diff --git a/docs/render-cpu-output.md b/docs/render-cpu-output.md new file mode 100644 index 000000000..ddb384673 --- /dev/null +++ b/docs/render-cpu-output.md @@ -0,0 +1,125 @@ +# CPU output presentation and native masters + +CPU ray tracing can apply the same presentation operators as GPU path tracing to +its captured transport result. Presentation is independent of the optional CPU +physical lens, guided noise reduction and opaque path lighting; those options +keep their own admission and compatibility checks. CPU adaptive sampling and +conditional Path Glass/subsurface transport also use this output pipeline. Their +compatibility limits remain independent; see [renderer parity](render-parity.md). +Raw EXR is unfiltered film data, including when the displayed PNG is denoised. + +A portable CPU job may include: + +```json +{ + "width": 512, "height": 512, "exposure_ev": 1, + "job": { "method": "cpu_raytrace", "options": { + "progressive": { "samples_per_pixel": 16, "seed": 81 }, + "output": { + "tone_map": "aces_fitted", + "finishing": { "rgb_gain": [1.2, 0.9, 1], + "bloom": { "strength": 0.2, "threshold": 1.5, "radius": 8 }, + "photographic": { "grain": 0.02, "seed": 42 } + }, + "linear_exr": true + } + }} +} +``` + +The runtime equivalent is `raytrace.output`. Output never owns another exposure, +background or transparency value. Setup exposure still lowers once into CPU +raytrace exposure; the captured image request owns the display background and +transparent-background flag. Opaque remains the default; explicit true exports +straight-alpha geometric coverage. Unknown or GPU transport fields inside output +are refused. + +Missing/null output and identity presentation keep the original f64 PNG exactly. +EXR-only retention also preserves that display path. Nonidentity presentation +converts one complete pass to FLOAT32, premultiplied by primary coverage, before +shared Display/Bloom/Photographic stages. Fixed CPU captures raw radiance before +its existing per-pixel display write; progressive CPU converts the complete f64 +film mean. Every provisional pass has the same effects and deterministic seeds +as a standalone final target at that pass count. + +A raw master is created only for final completion, before exposure, tone mapping, +finishing, bloom, photographic effects and the display backdrop. RGB is relative +scene-linear sRGB/D65 and coverage-premultiplied; A is primary coverage. The CPU +producer has its own exact native software metadata profile. Regrading accepts +only the exact retained native CPU/GPU profiles; it does not import arbitrary EXR. + +The shared output envelope remains 8192 pixels per side and 16,777,216 pixels in +total. A larger CPU profile does not raise that separate envelope. Active output +is validated before HDR IO or scene capture, and offline saved setups validate it +as well. Original CPU images without these output stages retain their existing +profile bounds. + +Admission adds one 16-byte-per-pixel conversion, bounded bloom scratch (24 bytes +per pixel), optional photographic scratch (8 bytes per pixel plus 16 KiB), final +EXR capacity and fixed stage/options metadata. The existing RGBA/PNG reservation +is moved into the output stage, not duplicated. Conversion, each bounded output +operation and final digest scans debit the same cumulative CPU work budget. +Cancellation cannot install a late PNG or raw master. + +Raw masters, final PNGs and at most two provisional PNG slots use the existing +host pool. A final has its own lease and cannot borrow a pinned preview slot. +Externally retained final/preview Arcs remain charged until their last owner is +dropped. A cancelled job leaves the previous completed image intact. + +The Render workspace saves and reloads CPU presentation through the shared +Effects, Environment and Output editors. EXR export is enabled only by an actual +selected completed image with a retained master. Enabling retention for a future +job or showing a provisional PNG cannot manufacture an exportable EXR. + +## Focused validation + +Executed renderer regressions cover the original f64 PNG identity, analytic raw +radiance and coverage, every complete progressive prefix, worker quantum +independence, each output stage's cancellation and cumulative work ceiling, and +retained preview/final leases. Earlier saved-document and engine runs exercised +strict round trips, cold output refusal before HDR IO, actual CPU rendering, +raw-master export and regrading; they do not qualify later combined additions. + +An earlier-snapshot Render workspace suite passed with the CPU feature enabled +and a real GPU required. It included the real Render button's saved CPU effects +and exported EXR, presentation Undo/reload, camera preservation, progressive +controls, live selection overlays, cancellation and clean cold-entry shot +switching. That earlier result does not qualify the later combined alpha, +denoising, GI or saved-optics additions, whose document/engine/UI/native workflow +gates remain pending. Executed combined renderer checks do not replace +repository-wide or platform CI. + + +## Transparent PNG coverage + +CPU runtime requests accept the existing top-level `transparent_background` flag. +Saved CPU jobs keep it beside `options`, with false as the default, like the other +image methods. Omission and false retain the original opaque f64 PNG and work +route. The Output checkbox and Environment Clear action use this same flag; +there is no second alpha setting inside `options` or `output`. + +True exports straight RGB and 8-bit alpha from primary geometric coverage for +fixed 1/4/16 AA and progressive camera sampling. The scene radiance is divided by +coverage before exposure/tone/colour adjustments, never multiplied by alpha in +the PNG. Alpha is rounded geometric coverage; fully clear pixels have canonical +zero RGB. Background colour is not composited into a transparent PNG. Body and +face opacity must remain 100%: this is background removal/edge coverage, not +partial material opacity or a general transmissive-glass matte. A primary glass +hit retains its existing geometry footprint. + +The shared colour presentation is available with alpha. Active camera backdrops, +bloom and photographic operators still require opaque output and refuse without +removing authored values. Raw EXR always retains the same premultiplied linear +radiance and coverage, byte for byte, independent of PNG background choice. +No additional image plane, ray, reservation envelope or work limit is introduced. +Only the completed final PNG is exportable; previews remain nonexportable and +cancellation retains the existing publication barrier. Export writes the exact +retained straight-alpha PNG bytes. + +For explicit CPU independent-pilot allocation, raw linear means and coverage use +each pixel's production sample count. Completed-pass presentation borrows the +film's exact count plane for integer PNG alpha rounding; it does not copy a new +image-sized count plane or write pilot radiance to the final raw EXR. Captured +sampling metadata remains in the existing job report rather than a second, +conflicting linear-master schema. This outside integration requires compilation +and numerical/export qualification before advertising the CPU adaptive route. diff --git a/docs/render-cpu-path.md b/docs/render-cpu-path.md new file mode 100644 index 000000000..ccd6e6eb5 --- /dev/null +++ b/docs/render-cpu-path.md @@ -0,0 +1,57 @@ +# CPU indirect lighting + +CPU indirect lighting and [general Glass](render-cpu-general-glass.md) are in +published source `00edaf6a`/tree `38a7f0af`. CI7 passed 744 renderer tests and all 433 +Render workspace tests; the full project gate remains red. Native evidence is an +opaque Sample Plate, so native Glass and image-quality acceptance remain pending. +See [the parity and qualification record](render-parity.md). + +CPU Sampling can explicitly enable **Indirect lighting**. Runtime intent is `raytrace.path: {"max_depth": 8}`; saved CPU intent is `job.options.path` with the same contract. Omission preserves the existing direct/selected-reflection algorithm, pixels and work. It adds no path allocation when omitted; the fixed task metadata remains within the existing allowance, subject to compilation guards. Path depth is 1–16 shaded opaque surfaces or Glass boundaries, starting with the first hit. A depth of 1 uses direct lighting only; higher values allow more light bounces and may take longer. Finite depth truncates longer paths; this is not a certified convergence or speed guarantee. No automatic quality, profile, size, seed, camera, default or method change is made. + +The mode requires progressive camera sampling, `primary_samples: 1` and traced shadows. It evaluates the complete existing isotropic opaque BRDF, including its existing clear-coat approximation, and uses an exactly matched cosine/GGX-NDF/coat mixture. Null proposals retain their probability mass. Secondary hits preserve captured body/face appearance and existing surface effects; visible surface emission can illuminate diffuse neighbors through actual path continuation. Small mesh emitters have no next-event sampling and may remain noisy. + +Directional and point/spot sources retain their delta direct estimates. Rectangles become intersectable one-sided emitters. Rectangular and HDR/constant environment estimates use light/BSDF power weights with the actual direct sample counts, previous-scatter density/position and no nonexistent continuation competitor at the depth endpoint. Geometry wins equal-distance emitter ties. Finite shadow intervals exclude their sampled source; other rectangles occlude both strategies consistently. Uniform-solid-angle HDR sampling preserves the existing explicit sRGB/D65 policy; no importance-distribution quality claim is made. + +A primary miss remains the separate unexposed display background. Complete paths add scene-linear radiance to the existing primary film exactly once. Existing every-pass publication, presentation, raw final EXR, final ownership and exact export routes remain authoritative. A partial path cannot advance film coverage/SPP or publish a completed result. Guided noise reduction and transparent PNG coverage compose with this opaque +transport without entering raw EXR radiance or changing primary coverage. +Composition regressions check an analytic partial-coverage emitter, every +checkpoint, worker quanta and unchanged raw masters; these renderer regressions have executed. + +The [general Glass route](render-cpu-general-glass.md) adds certified closed meshes, +nested media, inside-eye/pupil classification and delta transport when Path is +explicit. Selected reflection overrides and certified anisotropy remain refused +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 +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 +existing settings and returns to the original sheet/box or opaque transports. + +Memory is one exact-capacity fallible path continuation, prepaid in CPU job admission. There is no second film, ray queue, worker, host pool or raised cap. Sampler/source/emitter scans, traversal, shading and the final film commit are separate bounded work continuations sharing the original cumulative budget and cancel token. The unchanged fixed host metadata/task-state bounds remain integration gates. + +Executed renderer regressions cover analytic Lambert density/furnace, full coat PDF consistency, projected-solid-angle rectangle means, real diffuse red bounce and blocker, every-prefix/quanta/raw-master invariants, exact admission delta and cancellation/work exhaustion. Published document, engine and workspace tests also cover saved/runtime capture and Sampling click/Undo/reopen. These test results do not qualify a native Glass image or complete image-quality acceptance. + + +Rectangle support uses the full admitted two-vector basis, including the common +near-orthogonal tolerance and extreme aspect ratios. Geometry wins model/emitter +equal-distance ties in both continuation and direct visibility. Positive-area +overlapping, same-facing coplanar rectangle supports refuse before capture; +the bounded projected-bounds guard is conservative for rotated supports and +retains all authored sources. Adjacent supports and opposite one-sided emitters +remain valid. Stratified HDR/area source inputs alone are made representably +open at floating-point endpoints; the camera counter stream is unchanged. + +The CPU denoising prepass tests each admitted analytic rectangle only when this +path mode is enabled. A strictly closer, front-facing emitter produces a bypass +guide instead of borrowing the diffuse body behind it; geometry keeps exact +distance ties. Each of at most four source scans has its own cumulative work +debit and cancellation check. Its scalar continuation state is prepaid in the +existing exact guide-state size, with no additional image plane. The absent-path +guide algorithm performs no new source scans. Combined numerical and lifecycle +renderer tests for these invariants have executed; native image-quality acceptance remains pending. + +The optional finite Sun and gradient Sky use the shared saved radiance domains, separate emitter MIS and bounded cooperative stages. They require explicit Path transport and preserve default-absent behavior; see [CPU celestial lighting](render-cpu-celestial.md) for the source contract and the shared qualification limits. diff --git a/docs/render-cpu-progressive.md b/docs/render-cpu-progressive.md index a31b70ea0..e757551da 100644 --- a/docs/render-cpu-progressive.md +++ b/docs/render-cpu-progressive.md @@ -1,16 +1,22 @@ # CPU progressive camera sampling -The limits below describe the compatibility **Compact** profile. Explicit Studio and Workstation envelopes are documented in [CPU resource profiles](render-cpu-resource-profiles.md); their implementation batch still requires consolidated validation. +The limits below describe the compatibility **Compact** profile. Explicit Studio and Workstation envelopes are documented in [CPU resource profiles](render-cpu-resource-profiles.md); the published suites and remaining qualification limits are recorded in [renderer parity](render-parity.md). CPU progressive rendering repeatedly traces fresh camera samples into a bounded -linear-light film. Checkpoints are complete image passes, at 1, 2, 4, 8, 16 and -32 samples per pixel when below the requested final sample count. The exact -requested count produces the final PNG, including non-powers of two such as 3 -or 5. A one-sample job has no provisional checkpoint. +linear-light film. Every complete nonfinal image pass produces a checkpoint: +1, 2, 3, 4, and so on. The exact requested count produces the final PNG, +including non-powers of two such as 3 or 5. A one-sample job has no provisional +checkpoint. The UI can coalesce fast updates between physical screen repaints; +the renderer does not skip complete-pass work to follow a powers-of-two cadence. -This mode uses the native `cpu-raytrace` executor and its existing direct-light -and selected-reflection transport. It does not add diffuse global illumination, -caustics, adaptive convergence, a denoiser, or general glass path tracing. +This mode uses the native `cpu-raytrace` executor. With `raytrace.path` absent it +keeps the existing direct-light, selected-reflection and certified sheet/box +optical transport. Explicit [opaque path lighting](render-cpu-path.md) adds bounded +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. ## Request and saved intent @@ -63,22 +69,25 @@ render host is installed. ## Supported combinations and limits -| Control | Initial CPU progressive contract | +| Control | CPU progressive contract | | --- | --- | | Dimensions | Each side 1..4096; at most 1,048,576 pixels | | Samples per pixel | 1..64 | | Total camera samples | At most 16,777,216 (`width × height × samples_per_pixel`) | | Fixed spatial AA | `primary_samples` must be 1 | +| Physical depth of field | Optional `lens` uses the shared aperture radius / axial focus distance; positive aperture needs a bounded perspective camera and conservative pupil/glass admission | | Selected mirror / isotropic rough reflection | Existing bounded depth; `reflections.samples` must be 1 when bodies are selected | | Directional / point / spot sources | Existing CPU light contracts and limits | | Constant / captured HDR environment | Existing CPU contracts; HDR plus rough reflections still requires certified fully metallic selected bodies and effective faces | | Surface emission / isotropic surface effects | Existing CPU appearance contracts; emission is visible radiance | -| Area / LED sources | Explicitly rejected in this initial progressive mode | -| Dielectric / anisotropic face overrides | Explicitly rejected in this initial progressive mode | -| Output | Opaque PNG with the existing display background | +| Area / LED sources | Existing rectangular emitter transport; at most 4 sources sharing 1/4/16/64 area samples per camera sample | +| Dielectric / anisotropic face overrides | Without Path: certified sheets/axis-aligned boxes and the separate planar anisotropic adapter. With Path: general Glass under its certificate; selected anisotropy/reflection overrides refuse. Geometry, coat, HDR and overlap guards remain. | +| Output | Opaque or straight-alpha coverage PNG; optional compatible shared tone/colour finishing and final-only native linear EXR via `output`; bloom/backdrop/photographic effects require opaque output | An incompatible request fails; it does not remove settings or switch methods. -The fixed CPU route retains its existing area, dielectric and anisotropy support. +Progressive sampling alone retains the legacy sheet/box and planar-anisotropy +transport. Explicit Path selects [general Glass](render-cpu-general-glass.md); +these are different transport choices, not an implicit widening of fixed jobs. At 1024 × 1024 the camera-sample cap allows at most 16 samples per pixel; at 512 × 512 it allows 64. Requests are also subject to the existing geometry, 384 MiB CPU job and 512 MiB shared host-pool admission limits. Traversal, @@ -91,7 +100,9 @@ will finish below the cumulative runtime work ceiling. Camera jitter is a deterministic counter sequence keyed by the u32 seed, pixel index and absolute sample ordinal. Reflection and HDR-direct variates use -separate domains of the same counter. Target sample count, worker quantum and +separate domains of the same counter. Rectangular and continuous LED emitters use +a separate film-aware area-sample identity; their admitted area integral completes +before that camera sample enters the film. Target sample count, worker quantum and checkpoint cadence are not keys. Consequently, for an unchanged captured request and scene, a checkpoint at N samples has exactly the same sample prefix and PNG bytes as a job whose final target is N. @@ -111,6 +122,28 @@ The existing general `FilmAccumulator`/borrowed `FilmPngTask` APIs are retained; the owned image job uses the shared `PngEncoding` pipeline without a self-referential borrowed task or a second independent pool. +## Physical thin lens + +Optional `raytrace.lens` and saved CPU `options.lens` use the shared physical +[`ThinLens`](render-thin-lens.md) contract. Positive aperture requires this +progressive mode; an existing fixed-AA shot needs explicit adoption in Sampling. +The independent pupil domain uses seed, pixel and absolute film ordinal, so +changing target samples or worker quantum does not alter a prefix. Each camera +sample still traces one primary ray. Pupil generation adds one charged scalar +continuation and no image buffer; the existing memory and cumulative work caps +remain in force. Omitting the lens or using radius zero preserves the original +fixed/progressive images and work count byte for byte. + +## Presentation and raw masters + +Optional [`output`](render-cpu-output.md) settings reuse the same tone, finishing, +bloom and photographic stages as GPU output. They receive scene-linear, +coverage-premultiplied mean radiance, never decoded PNG pixels. Every checkpoint +uses the same presentation as the final PNG. Only the exact final pass may retain +an EXR; provisional images remain nonexportable. Identity presentation keeps the +original f64 display calculation byte for byte, including when raw retention is +selected. All new stages share the same cumulative CPU work budget and admission. + ## Preview publication and final export `JobStatus.preview`, when present, contains: @@ -147,23 +180,31 @@ job, but cannot replace a previous successfully completed final frame. ## Allocation and retained snapshots Admission reserves the working film, existing RGBA/encoder/final-PNG capacity, -and the maximum encoded capacity plus metadata for every possible nonfinal -checkpoint. This conservative upper bound covers a consumer retaining all -checkpoints at once. Actual film and PNG capacities are checked against their -admitted capacities after fallible allocation. +and at most two maximum-sized encoded checkpoint slots with bounded metadata. +The checkpoint allowance is independent of the requested sample count. Actual +film and PNG capacities are checked against their admitted capacities after +fallible allocation. -A completed checkpoint moves its PNG allocation into the preview object. -`Reservation::split` transfers that allocation's share of the running lease -without increasing or decreasing the pool total. Replacing or clearing the host -preview drops only the host's `Arc`; any external `Arc` keeps its memory billed. -At final completion the task releases its working buffers before the remaining -lease shrinks to the final PNG. Dropping each last external snapshot releases -only that snapshot's reservation. There is no full-film clone per checkpoint. +A completed checkpoint moves its PNG allocation into an immutable preview. +`Reservation::split` transfers a prepaid slot without increasing the pool total. +Dropping its last `Arc` returns the slot to the same running job; keeping an old +snapshot alive keeps that slot billed. Replacing the host's old snapshot needs +no consumer acknowledgement. If both slots are externally pinned, the job +records `preview_retention_skips`, omits that snapshot and continues sampling +and final export. A freed slot allows later complete passes to publish again; +`frame_sequence` counts published snapshots and `samples_per_pixel` identifies +the actual pass, so consumers must not equate the two after a retention skip. + +Completion or cancellation closes the reusable pool and releases unused slots. +Externally retained snapshots keep their own leases until their last owner drops +them. The final PNG retains its separate reservation and never borrows a pinned +preview's slot. There is no full-film clone per checkpoint. ## Regression coverage The source includes regressions for deterministic prefixes and worker quanta, fresh primary rays, non-power-of-two targets, actual HDR/rough-reflection PNGs, +rectangular/LED PNG prefixes against numerical light integrals and area-shadow cancellation, linear averaging before tone mapping, coverage and unexposed backgrounds, bounded/cancelled film mutations, and the single cumulative work budget. @@ -175,3 +216,62 @@ Engine tests cover Check/Start equality, cold rejection before HDR capture, session ownership, exact final export, and retention of the previous completed image after a progressive job is cancelled. Execution evidence belongs to the integrated CI receipts; this source handoff does not claim those gates passed. + + +`transparent_background: true` exports the existing primary coverage as straight +PNG alpha. Fixed AA and every complete progressive prefix use the same conditional +scene colour; clear pixels are zero RGBA and no display background is mixed into +edge colour. Opaque false/default pixels and work remain unchanged. Raw EXR +premultiplied radiance/coverage is independent of this display choice. See +[CPU output presentation](render-cpu-output.md#transparent-png-coverage). + + +The optional [CPU path lighting](render-cpu-path.md) consumer adds bounded +progressive diffuse/specular GI and its conditional general-Glass transport only +when `path` is authored. The restrictions above describe the absent-Path route. +Published source has document/engine/workspace regression coverage; unsupported +Glass/anisotropy/external-volume combinations and native Glass visual acceptance +remain explicit in [the parity matrix](render-parity.md). + +## Optional independent-pilot allocation + +CPU `raytrace.adaptive` (saved `CpuJob.options.adaptive`) uses the shared +`AdaptiveSampling` policy. It requires an explicit progressive production cap of +at least 16 samples. Pilots use an independent seed domain; their RGB and coverage +Welford statistics allocate each pixel a fixed 16..production-cap budget. Pilot +radiance is discarded through a cooperative reset. Production preserves the +ordinary CPU seed and zero-based sample ordinals, and stopped pixels consume no +more transport variates or rays. Every complete pilot and production sweep still +passes through the same two-slot checkpoint publication; the UI can coalesce +physical paints, and externally pinned slots can cause retention skips. + +All existing CPU profile limits include **pilot_samples + samples_per_pixel**; +no cap or profile is raised automatically. At most 256 pilots and 4096 total +pilot/production passes are possible in the largest selected profile. Compact +retains its 64-pass and 16,777,216 camera-sample bounds. A 32-pilot/64-production +request therefore needs an explicit profile that admits 96 total passes. The +cumulative work budget also includes initialization, reset, skipped-pixel cursors, +finishing and publication. Statistical allocation can miss rare paths and does +not certify a noise level or completion time. + +Per-pixel sums, coverage and sample counts remain f64/u16 until complete-pass +resolve. RGB and raw FLOAT32 EXR coverage are divided by each pixel's own +production count; no uniform denominator or PNG alpha quantization enters the +raw master. Shared finishing borrows the film's exact count plane and rounds +straight-alpha PNG bytes from the integer covered/sample ratio. It allocates no +additional count snapshot. The raw EXR remains final-only and unfiltered. +`JobStatus.sampling` records the actual production count range, evaluations and +pixels at the cap; `PreviewInfo.adaptive` distinguishes pilot and production +ordinals. A production sweep ordinal is not a promise of uniform per-pixel work. + +The existing certified optical/aniso route, physical lens, direct lights/HDR, +opaque path lighting and completed-pass denoiser use the same adaptive camera +identity. Their existing geometry, coat, optical/HDR and path-combination guards +remain in force. Omission preserves the ordinary film allocation, random keys, +sample order and debits; actual new inline metadata is billed by size rather +than hidden behind the historical memory estimate. + +The independent-pilot implementation and its numerical, host-ownership, +saved-request and UI regressions are included in the published CI7 source. +See [qualification](render-parity.md#qualification). That execution does not +certify adaptive convergence, every material combination or native Glass quality. diff --git a/docs/render-cpu-resource-profiles.md b/docs/render-cpu-resource-profiles.md index 8a47a008f..753eb9ac0 100644 --- a/docs/render-cpu-resource-profiles.md +++ b/docs/render-cpu-resource-profiles.md @@ -1,6 +1,6 @@ # Explicit CPU resource profiles -**Implementation batch: source prepared; consolidated compilation and large-scene runtime acceptance are pending.** These envelopes are admission limits, not measured performance or a final-quality certification. +**The combined CPU-feature renderer build and profile/admission regressions have executed; current combined workflow and large-scene runtime acceptance remain pending.** These envelopes are admission limits, not measured performance or a final-quality certification. ## Intent @@ -61,11 +61,11 @@ Fallible allocation, actual vector-capacity checks, checked arithmetic, bounded The new pending-format descriptor is `render-cpu-budget`. Old intent has Compact semantics; larger intent is not discarded on reopen. The independent GPU sampling flag remains separate from CPU progressive sampling. Visual material edits still do not change engineering material properties. -This increment does not introduce CPU diffuse global illumination, adaptive sampling, multithreaded transport, arbitrary dielectric geometry, texture displacement or EXR output. The existing optical-combination restrictions remain explicit. Raising an admission ceiling is not a performance optimization or a claim that every large scene is practical yet. +Resource-profile selection alone does not enable CPU diffuse global illumination, adaptive sampling, multithreaded transport, arbitrary dielectric geometry, texture displacement or EXR output. Optional [opaque path lighting](render-cpu-path.md) and [output presentation](render-cpu-output.md) have their own explicit contracts. The existing optical-combination restrictions remain explicit. Raising an admission ceiling is not a performance optimization or a claim that every large scene is practical yet. -## Prepared regression coverage +## Regression coverage -Tests cover explicit 4K/8K admission without allocating a large film, BVH cardinality estimates for larger profiles, old/unknown profile handling, offline saved round trips, preservation of incompatible UI drafts, host-pool isolation, arithmetic overflow and linear film accumulation above 64 samples. Their execution belongs to the consolidated batch gate; formatting or static source checks alone do not constitute a passing test run. +Tests cover explicit 4K/8K admission without allocating a large film, BVH cardinality estimates for larger profiles, old/unknown profile handling, offline saved round trips, preservation of incompatible UI drafts, host-pool isolation, arithmetic overflow and linear film accumulation above 64 samples. Renderer admission and above-64-sample film regressions have executed. Offline document/UI, host and platform qualifications remain separate; admission tests without a large film do not establish large-scene performance. ## Display is separate from output diff --git a/docs/render-cpu-volume.md b/docs/render-cpu-volume.md new file mode 100644 index 000000000..385374d88 --- /dev/null +++ b/docs/render-cpu-volume.md @@ -0,0 +1,104 @@ +# CPU bounded Atmosphere + +This implementation and its renderer, host-ownership, document/engine and pointer +regressions are in published source `00edaf6a`/tree `38a7f0af`, tested by CI7. +Full CI7 remains red. Native Atmosphere/Glass image quality and performance are +not established by the opaque Sample Plate capture. See +[qualification](render-parity.md#qualification). + +CPU Indirect lighting may consume the existing `HomogeneousVolume` contract: one +world-space axis-aligned box, scalar extinction in inverse millimetres, RGB +single-scattering albedo, and HG phase bias using propagation directions. It is the +same bounded fog domain used by GPU Atmosphere, not a weather model, density grid, +heterogeneous medium, spectral solver or emissive volume. + +The portable field is `CpuJob.volume`; the runtime field is +`raytrace.volume`. Both preserve `min_mm`, `max_mm`, `extinction_per_mm`, +`scattering_albedo` and `anisotropy`. Coordinates stay within ±1e9 mm, each extent +is at least 1e-6 mm, extinction is 0–1000/mm, each albedo component is 0–1 and phase +bias is −0.95–0.95. Existing image, geometry, cumulative work, memory, ray-distance, +codec, 4096-byte host task and 1024-byte completion metadata caps remain unchanged. +Those layout assertions compiled in the published CI7 source; the passing scoped +renderer suite does not establish native Atmosphere image quality or performance. + +Positive extinction requires explicit progressive CPU Indirect lighting. It cannot +combine with Glass, selected-medium subsurface scattering or surface Denoise. +Existing selected-reflection/anisotropy Path restrictions remain in force. No +setting is silently cleared, no fixed saved sampling is adopted automatically, and +an unsupported request fails with its authored values retained. CPU has one Path +attempt per film ordinal; GPU-specific Fresnel-stratum controls are not introduced +as CPU transport parameters. Zero extinction stays authored while bypassing all +new worker phases, random dimensions and heap owners. Omitted volume keeps the old +serialized CPU wire. Literal fixed layout/admission byte identity with an older +binary is not claimed. + +## Physical transport and model visibility + +A perspective ray uses its actual eye or sampled pupil as the optical start, so +fog before the model near plane is not lost. Its original model near interval is +retained. For orthographic projection, the optical start is the earlier of that +original model near plane and the fog box's signed line entry; the model interval +moves by the same ray parameter. The pixel line, camera, captured geometry, model +bounds and framing never move. Far optical queries include the box even when it +extends ahead of or beyond the model, or when the scene contains no model at all. +A box extending beyond an actual admitted infinite-ray distance refuses explicitly. + +The single finite path samples an exponential flight within the forward ray/box +segment, before its closest visible model or analytic-emitter endpoint. A collision +applies RGB scattering albedo once, contributes foreground coverage, counts one +Path event and evaluates direct lighting with the HG phase function. Continuation +uses the shared exact HG sampler. Surviving sampled paths carry no-event probability +in their endpoint density without multiplying throughput a second time. Absorption +is represented by the complementary probability and scattering albedo; it is not +an additional double attenuation. + +The existing bounded directional, point/spot, rectangle/LED and constant/HDR +lighting continuations provide next-event samples. Volume vertices use their +physical position and HG response/PDF; opaque vertices retain the completed +Effects→Maps→Aging closure. Visibility is blocked by the same opaque geometry and +other analytic emitters, and its box segment supplies transmittance to both the +NEE contribution and matching phase/BSDF competitor density. Source sample counts +and finite-depth endpoints retain complementary MIS. No new BRDF/PDF/clamp body or +refracting-boundary approximation is added. The composed Sun/Sky stages use the same +medium-aware response/PDF and physical source helper; combined phase/escape and +SSS-delta regressions are included in the executed published renderer suite. + +Active-volume opaque launches use the existing exact producing-plane exclusion. +A cooperative primitive-range walk charges one neighboring primitive per step, +avoiding a surface normal offset that would change the fog length. Interior volume +launches have no surface offset. An actual collision that aliases a source, +endpoint or box boundary refuses rather than moving geometry or clipping radiance. + +## Work, retained ownership and prepared oracles + +One optional context lives in the already prepaid finite Path state. Actual State +size pays pending source/event/range/MIS metadata; there is no ray tree, extra film, +image plane, source image or decoder allocation. The inline runtime volume field +adds a fixed request-header charge on every retained job, even for absent CPU +options. Ordinary capture/preflight share the fixed metadata helper; regrade pays +its own header once in the Record request lease and does not rebill the source +HDR/texture bytes. This lease survives work release and an absent frame until the +last status handle drops. Held frame/presentation metadata retains its existing +separate lifetime. The composed Sun/Sky and inline volume headers are summed once. + +Every new worker operation debits before changing state. Box/free-flight/phase +math is bounded, range discovery visits one primitive per debit, and traversal +uses the existing cooperative cursors. Cancellation or work exhaustion cannot +publish a late sample, checkpoint or master. + +Prepared regressions use independent exponential CDF, analytic slab/box lengths, +HG formula/direction and light-sampling loops for depths 1/2/16. They cover pure +absorption, a real perspective near prefix and pupil, orthographic foreground and +background union, empty-scene coverage, single/multiple scattering, white-furnace +energy, opaque blockers, finite rectangle and real nonconstant HDR sources with +1/4/16/64 samples, survival-density MIS, exact physical source/range debits, every +PNG prefix, raw FLOAT EXR/alpha, finishing, adaptive pilot separation, worker quanta, +cancellation and retained-header release. Typed saved/runtime and cold-container +Start/Undo tests preserve the camera, geometry and engineering materials. The +shared Atmosphere adapter is composed with the celestial editor: one prospective +method transaction preserves Volume, Sun, Sky, the analytic rig, camera and full +authored sampling/output intent. A known volume-only edit retains mute/solo/light +selection only with exact source provenance; unknown source replacement clears it. +Actual pointer, save/Undo/cold and combined native Start/raw-master assertions are +included in the published UI test module and CI7 execution. This is regression +coverage, not native Atmosphere image-quality acceptance or a green full gate. diff --git a/docs/render-cpu-workspace.md b/docs/render-cpu-workspace.md index 352877e19..3554df949 100644 --- a/docs/render-cpu-workspace.md +++ b/docs/render-cpu-workspace.md @@ -1,40 +1,54 @@ # CPU controls in the Render workspace -This incremental panel is built on advanced CPU source tree +The original incremental panel was built on advanced CPU source tree `6e5db1e64376164878918eb68f1e5b311740afcd`. It prepares the same existing `render.preflight` and `render.start` commands. It does not add a renderer, material asset or rendering dependency. The subsequent numeric setup unit persists the portable subset through `RenderSetup.job`; see [workspace settings](render-workspace.md#settings-and-product-camera). -Choose **CPU ray tracing** in Render. Three collapsible sections provide the -following controls; the existing AA 1/4/16, lighting presets, shadows and exposure -remain available in **Single image** sampling mode. +Choose **CPU ray tracing** in Render. The original three sections below describe +its legacy request controls. The normal workspace also exposes the separately +validated CPU lens, guided noise reduction, opaque indirect lighting and saved +certified Glass controls. Existing fixed setups retain their AA 1/4/16, lighting, +shadows and exposure; adopting progressive sampling is an explicit action. ## Progressive CPU sampling -**CPU sampling mode → CPU progressive** accumulates samples of the existing CPU -integrator. Set **samples per pixel** from 1 to 64 and the separate CPU sampling -seed. Selecting the mode explicitly chooses one primary sample per pass; returning -to **Single image** restores the AA selector without discarding lights or HDR controls. -This is camera sampling of the existing integrator, not diffuse global illumination, -adaptive sampling or CPU denoising. +New normal CPU setups show progressive sampling as always-on status with samples +per pixel and seed controls. Existing fixed setups retain their exact intent and +show an explicit **Use progressive sampling** action; opening the page never +converts them. Adoption announces one camera sample per pass and refuses an +incompatible image budget or selected reflection count instead of changing size, +method, lighting or reflections. The previous Single image / Progressive selector +remains available through **Use previous Render image defaults**. +Progressive camera sampling is independent of the optional [opaque path lighting](render-cpu-path.md) +and [guided noise reduction](render-cpu-output.md) contracts. Independent-pilot +CPU adaptive sampling is also implemented. These controls combine only where +their geometry, memory, work and transport admission rules allow; they do not +certify convergence or a completion time. -The initial progressive path accepts isotropic opaque surfaces and the supported -directional, point and spot lighting. Selected reflections require one reflection -sample. Area lights, LEDs, dielectric overrides and anisotropy must use Single image; -switching modes never silently removes these inputs. Check and Start report an -incompatible combination through the same request validation. +Progressive sampling accepts the existing supported opaque/direct-light, selected +reflection, certified dielectric and planar anisotropy transport. Selected opaque +reflections require one attempt per camera sample. Without Path, Glass retains +certified sheets/axis-aligned boxes and anisotropy its planar subset. Explicit +Path supports general Glass but refuses selected reflection/anisotropy overrides. Geometry, HDR, clear-coat and optical overlap restrictions +remain explicit. The shared Glass editor saves the certified dielectric subset +with stable body/occurrence targets; see [saved optics](render-raytrace-dielectrics.md#saved-optical-bindings-and-common-glass-controls). +Selected opaque-reflection and anisotropic-face bindings still use the temporary +runtime identity/confirmation contract below. -Admission allows at most 1,048,576 pixels, dimensions up to 4096, and +The Compact resource profile allows at most 1,048,576 progressive pixels, dimensions +up to 4096, and 16,777,216 pixel × sample evaluations. For example, 1024 × 1024 supports 16 SPP, whereas 64 SPP requires at most 262,144 pixels. Increasing SPP or loading a setup never changes its dimensions automatically. If needed, the panel displays a **Use the largest size at this aspect: W × H** action; only clicking it resizes the draft. Save applies the same numeric limits without requiring a renderer and leaves invalid drafts intact. Traversal, sampling and image encoding also share -the backend's cumulative work budget. +the backend's cumulative work budget. Larger [CPU resource profiles](render-cpu-resource-profiles.md) +remain explicit choices; no profile, size or sample count is raised automatically. -The result canvas shows provisional PNG checkpoints after 1, 2, 4, … samples, +The result canvas shows provisional PNG checkpoints after every complete pass, 1, 2, 3, 4, … samples, before the requested final count. A provisional label includes its SPP and checkpoint sequence; the job identity and captured revision remain unchanged. Checkpoint updates reuse the current pan/zoom. Completion replaces the preview with its final image; @@ -85,13 +99,17 @@ The engine still performs final capture and surface compatibility validation. CPU reflections do not implement a general layered clear-coat transport model. The engine rejects a coated body or face selected for an incompatible reflection -path. This panel does not claim diffuse global illumination, caustics or a general -glass renderer. +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. ## Environment capture -**Constant** environment supplies secondary reflected/transmitted radiance. It -is not direct diffuse lighting and does not replace the image background. +In the legacy selected-reflection transport, **Constant** environment supplies +secondary reflected/transmitted radiance. Optional opaque path lighting also +estimates its direct and continued environment illumination. Neither route +replaces the separately authored image background. **HDR** uses the CPU environment contract: Radiance `.hdr`, 2:1 panorama, at most 2048 × 1024 pixels and 16 MiB of source bytes, with explicit supported sRGB/D65 primaries. EXR and files without those primaries are refused. Selected rough @@ -113,7 +131,7 @@ panel to **HDR saved inside this design**. Further saves use `render.settings.se Reload, setup switching and design reopen never need the original path. The CPU HDR's rotation, intensity and sample count are saved separately from its source ID. Rotation remains in radians internally; drawing the degree editor does not -round-trip or clamp it. A constant environment and HDR are mutually exclusive. +round-trip or clamp it. Constant, gradient Sky and HDR environments are mutually exclusive. Explicit CPU Indirect lighting also supports the shared finite Sun and gradient Sky contracts; see [CPU celestial lighting](render-cpu-celestial.md). CPU still requires explicit sRGB/D65 primaries; it never inherits the GPU's optional assumption for an undeclared source. @@ -139,12 +157,14 @@ attenuation and must not exceed the reference. Both distances range from 0.001 t 1,000,000 mm in this panel. Intensities are relative renderer values, not a claim of lumens, watts or calibrated photometric measurements. -Area lights, their sampling/seed and spot cones remain without dedicated panel -editors, but valid values loaded from a setup are preserved in Save, Check and Start. +The original panel did not provide dedicated area/spot editors. The shared Lights +editor now exposes supported area and directional/point controls; loaded spot +cones and numeric sampling intent remain preserved in Save, Check and Start. Directions retain their original nonzero magnitude; showing a field does not normalize or clamp it. Emission, surface effects, dielectric bindings and anisotropic faces -remain runtime API capabilities that this panel explicitly refuses to edit. A later -material/optics editor can expose those contracts separately. +remain runtime API capabilities beyond the original panel. The current shared +Glass editor exposes only its separately validated saved certified dielectric +subset; it does not make arbitrary optics or temporary bindings portable. ## Integration and acceptance @@ -157,10 +177,62 @@ regressions for sequence caching, final publication racing the status read, cancellation/export retention, explicit resolution adjustment, offline Save/Reload, hidden values and reopening progressive setups with embedded HDR. -The author checked Rust formatting, locale-key coverage, whitespace and exact -patch replay. No Cargo build, test execution, native launch or visual quality -acceptance was performed for this incremental source unit. The integrator must +For the historical incremental source unit, the author checked Rust formatting, +locale-key coverage, whitespace and exact patch replay. No Cargo build, test +execution, native launch or visual quality acceptance was performed for that unit. The integrator must run the combined revision's CI and the native UI/render tests before treating those regressions as passing. CPU controls and the GPU material editor have separate modules and request builders; both must retain their final admission guards when mounted together. + +## Output presentation + +The shared **Effects** editor accepts CPU ray tracing and GPU path tracing. Tone +mapping, creative looks, RGB gains, bloom and photographic image effects remain +presentation controls. CPU opaque path lighting, physical lens sampling and guided +noise reduction have their own explicit controls and compatibility checks. Noise +reduction filters complete progressive/final display passes without changing raw +film or the final unfiltered EXR. **Environment → Gradient** is also available for CPU output. +Physical depth of field is configured separately in **Frame → Lens**, through +the shared [thin-lens contract](render-thin-lens.md). CPU aperture sampling uses +the progressive film and requires a perspective camera; disabled or zero aperture +preserves the previous image exactly. +**Keep linear master** retains a final-only native FLOAT32 EXR. The export choice +uses the selected completed image's actual master, independently of the current +draft method or a new provisional render. + +These values save under `job.options.output`, reopen without a render host, and +use the setup's single exposure/background authority. The first numerical edit +keeps the visible size and numerical baseline. Merely opening the editor never +saves or starts a job. [CPU output presentation](render-cpu-output.md) describes +the existing shared output bounds and raw ownership. + +## Explicit CPU image budgets + +The normal Sampling page shares Draft/Balanced/High with GPU, but projects CPU +cost budgets independently from the same Q-001/Q-002/Q-003 catalogue. CPU uses +960×540/16, 1600×900/32, 2560×1440/64 production samples and seed 21026. The smallest +existing profile admitting the complete pilot+production envelope is selected, +without lowering an already selected larger profile. Nonadaptive baseline +profiles are Compact/Studio/Studio. No memory/work/SPP cap is raised. + +A CPU chip can change exactly width, height, progressive production sample cap, +progressive seed and resource profile in one reversible edit. Camera, lens, +HDR/light input, GI enablement/depth, denoise, optics, maps, aging, alpha, +finishing, raw-master intent and adaptive policy stay as authored. A preserved +adaptive minimum above the new sample cap refuses atomically. Saved fixed-AA +setups retain the explicit Adopt progressive action before these presets; a +quality click never silently normalizes primary AA or reflection attempts. + +These are image-cost presets, not complete optical/convergence quality tiers or +CPU/GPU convergence equivalence. Geometry/memory and cumulative-work admission +still apply to the captured job. Canonical CPU clicks use the same numerical +transaction and current-shot save path; imported GPU quality review remains a +separate acknowledged flow. Merely painting/selecting a page does not apply a +preset or launch a final render. + +The CPU budget/quality transaction and its pointer/save/reopen/Undo and hostile +budget regressions are included in the published source tested by CI7. See +[the qualification record](render-parity.md#qualification). Presets are not a +convergence or image-quality certificate; native Glass visual acceptance remains +pending. diff --git a/docs/render-denoise.md b/docs/render-denoise.md index d50a293fc..c6b5eafca 100644 --- a/docs/render-denoise.md +++ b/docs/render-denoise.md @@ -1,51 +1,83 @@ # Optional spatial denoising -Native progressive GPU image requests accept `"denoise": true`. Omission and -explicit `false` preserve the existing raw image path and allocate no denoising -buffers or pipelines. This runtime flag is not stored in designs or appearances. -The request is rejected on non-progressive or non-GPU executors. +CPU ray-traced requests accept `raytrace.denoise: true`; saved CPU jobs store +`job.options.denoise`. GPU path requests keep their existing `denoise` flag and +saved GPU field. Omission and explicit `false` preserve the corresponding raw +image path and allocate no denoising buffers. CPU filtering uses only the native +Rust renderer: no GPU device, WGSL runtime or software-GPU fallback is involved. +Raster cannot consume raytrace options. Offline editing does not imply that an +image host is installed. -The optional final pass runs after all requested path samples, on linear -premultiplied radiance, before the existing single exposure/tone-map/sRGB output -step. It never changes the raw linear accumulator or the path random-number -stream. Raw radiance and medium diagnostics are checked first, so denoising -cannot conceal a failed glass path. To retain both raw and filtered PNGs, submit -two otherwise identical jobs with the flag false and true respectively. +Every complete published pass uses the selected filter, including nonfinal CPU +and fixed/adaptive GPU feedback. Fast updates can coalesce at screen repaint; +the producer does not omit an effect merely to obtain an intermediate image. +Filtering uses normalized linear coverage-premultiplied radiance before bloom, +exposure, tone mapping, sRGB encoding and photographic finishing. It never +changes the raw film, sample keys or random stream. Radiance and transport +failures are checked before filtering. Final-only raw FLOAT32 EXR comes from the +unfiltered pass, before denoising; no raw companion is retained per preview. The original implementation uses three edge-aware a-trous passes with pixel steps 1, 2 and 4 and the separable five-tap kernel [1,4,6,4,1]. It is inspired by the published method of [Dammertz, Sewtz, Hanika and Lensch, HPG 2010](https://holger.dammertz.org/publications/dammertz10hpg_bibtex.html). -No third-party filtering source or weights are copied. A deterministic pixel-centre -ray supplies textured albedo, shading normal, body identity, world position and -depth. Bilateral weights use albedo difference, normal agreement, distance from -the local tangent planes, axial depth difference, and radiance contrast. Spatial thresholds scale with -the projected pixel footprint. Every pass retains the original alpha; the -online convex average avoids overflowing radiance multiplied by kernel weights. +No third-party filtering source or weights are copied. Deterministic pixel-centre +rays supply effective albedo, shading normal, body identity, position, depth and +projected pixel footprint. CPU guides reuse its actual prepared hit and supported +surface-effect evaluation; positions are made camera-relative in f64 before +conversion to f32. Guides are captured once per immutable CPU job and never +consume an absolute camera-sample ordinal. -First-hit guides cannot describe an image seen through refraction or a sharp +Bilateral weights use albedo difference, normal agreement, distance from the +local tangent planes, axial depth difference and radiance contrast. Spatial +thresholds scale with the projected pixel footprint. Every pass preserves the +original coverage. Online convex averaging avoids multiplying HDR radiance by +large kernel weights. + +First-hit guides cannot describe an image seen through refraction or sharp reflection. Pixels first hitting glass, metals with roughness below 0.25, -near-mirror coats with roughness below 0.05, light emitters, background or -partial coverage bypass the filter. Glossier coats are filtered: on the studio -coffee scenes their broad reflections of the cyclorama and area lights keep -their shape, while the grain from choosing between coat and base layers is -removed. A coat reflecting fine detail can lose some of it. First-hit guides also do not model depth-of-field correspondences: -the centre lens ray is used, so out-of-focus boundaries may retain noise or -acquire spatial bias. Rough glossy effects and soft shadows can lose detail. -This is a biased, optional spatial filter, not a temporal or learned denoiser, -and it cannot guarantee preservation of every lighting or texture feature. +near-mirror coats with roughness below 0.05, light emitters, background or partial +coverage bypass the filter. CPU's explicit Mirror override bypasses it as the +corresponding sharp reflective route, including on a dielectric base colour. +Glossier coats can be filtered; reflections of fine detail may soften. First-hit +guides also do not reconstruct depth-of-field correspondences: the centre lens +ray is used, so out-of-focus boundaries can retain noise or acquire spatial +bias. Rough glossy effects, texture detail and soft shadows can lose detail. +This is a biased, optional spatial filter, not a temporal or learned denoiser. +It cannot guarantee preservation of every lighting or texture feature. -Preflight includes the enabled method, three passes, guide policy, bypass cases -and these limitations. The job options retain the explicit flag. A job admits -80 additional GPU bytes per pixel only when enabled: 48 for guides and 32 for -two colour buffers. The 512 MiB job estimate and each device storage-binding -limit apply. At 1920x1080 the guide buffer is 99,532,800 bytes; larger dimensions -may be rejected before allocation rather than silently reducing resolution. -The guide pass reuses the existing six-storage-buffer path layout; the filter -needs three storage buffers. Cancellation is checked between bounded tiles. +CPU admission prepays 48 bytes per pixel for guides plus two 16-byte colour +buffers. If shared presentation or EXR already admits one linear buffer, the +additional pixel storage is 64 bytes rather than 80. Bounded guide cursor and +output-task storage is also admitted; there is no retained image per pass. +The existing CPU resource profile and shared host pool still apply. The shared +float4 presentation envelope limits filtering to 8192 pixels per side and +16,777,216 pixels total, even when EXR retention is off. No size is reduced and no +profile is raised automatically. Each filter continuation processes at most 256 +pixels with a fixed 25-tap gather per pixel and cancellation checks between +pixels. Work units count these bounded pixel visits, as for existing finishing +kernels: three visits per image pixel per complete published pass. Guide rays +retain the existing incremental BVH node/triangle charges, using the same +cumulative job budget without resetting it between output and transport. -Regression coverage includes an independent f64 gather oracle, constant-image -and coverage identity, checker noise reduction, albedo/normal/depth/body edge -preservation, synthetic GPU/oracle agreement, production centre-ray guides, -default/explicit-false image identity, raw-buffer preservation, admission and -runtime preflight behaviour. GPU checks must be run on the target backends; -source-level and shader validation alone do not establish rendered quality. +GPU admission keeps 80 additional bytes per pixel for three guide vec4s and two +colour buffers. Adaptive intermediate normalization has its separate admitted +input. Current GPU job/storage-binding limits apply before allocation. GPU +guides reuse production intersections and material evaluation; cancellation is +checked between bounded dispatch tiles. CPU and GPU filters share the numerical +policy, not bit-identical transport or a common device pipeline. + +Preflight names the enabled method, passes, guide/bypass policy, work convention +and limitations. Saved settings preserve the explicit flag. Retained-master +regrading has no geometry guides and does not reapply denoising; its metadata +reports `denoise_applied: false`, and the original raw EXR remains unchanged. +Submit otherwise identical unfiltered and filtered jobs to retain both PNGs. + +Executed CPU renderer regressions include an independent direct f64 gather +oracle, HDR/constant/coverage identity, noise reduction, body/albedo/normal/depth +edges, production centre-ray guides and bypasses, translated geometry, lens-guide +identity, false-path byte/work/allocation identity, every filtered prefix, +quantum independence, raw film/EXR preservation, cancellation and full scratch +admission. Document/engine/UI tests for offline persistence, explicit CPU wire +routing, native request metadata and one-undo controls still need qualification +on the combined source. Executed renderer checks do not establish native +image-quality, performance or full-project acceptance. diff --git a/docs/render-environment-sampling.md b/docs/render-environment-sampling.md index bebe99d1c..08fb981f0 100644 --- a/docs/render-environment-sampling.md +++ b/docs/render-environment-sampling.md @@ -51,12 +51,13 @@ and all other primaries refuse illumination; default Radiance RGB is not silentl relabeled sRGB. Supporting other primaries requires a separately validated gamut and white-point conversion. No clipping or invented conversion is used here. -## CPU consumer source and remaining integration +## CPU consumer and remaining qualification -The new branch starts from actual upstream history. The separately qualified RT2 -source is not a commit parent or an executed validation result for this module. -Integration must use its real prerequisite commit or an explicitly recorded -source overlay before its own gates; no copied build outputs. +At the original source handoff, the separately qualified RT2 source was not an +executed validation result for this module. Integration required real prerequisite +history or a recorded source overlay, without copied build outputs. Subsequent +combined CPU renderer checks have executed for environment sampling and the +actual image consumer; current combined workflow/native gates remain separate. 1. Capture the admitted existing HDR source and preserve its original encoded allocation. Include encoded/decoded retained capacities, request clones and state in the @@ -68,7 +69,7 @@ source overlay before its own gates; no copied build outputs. and creates short-lived borrowed views, without a self-referential borrow or a second decoded copy. Decoding validates corrected texels incrementally; internal views check shape and capacity without rescanning every texel for each sample. - Execution and visual acceptance remain pending. + Renderer decode/ownership/cancellation checks have executed; native visual acceptance remains pending. 3. At an opaque hit, each environment direct sample creates one positive-minimum secondary visibility ray from the shared geometric offset. Reuse the existing resumable traversal cursor, charging every sample and traversal unit. Add visible @@ -87,7 +88,9 @@ Original analytic tests generate RGBE bytes at runtime: constant map and PDF, single bright cell solid angle, black map, axes/rotation/seam/poles, cancellation and shared-budget failure, decoder corrections, unsupported primaries, hostile options/directions and an independent white-conductor hemispherical integral. -They have NOT RUN. No external assets, dependencies or persistence fields added. +The renderer analytic/input cases have executed. Engine source-removal and +metadata contracts still need current combined qualification. This sampling +helper itself adds no external assets, dependencies or persistence fields. Mathematical references only; no code or figures copied: [PBRT, Infinite Area Lights](https://pbr-book.org/4ed/Light_Sources/Infinite_Area_Lights) @@ -95,7 +98,7 @@ for radiance and solid-angle estimators (its image mapping is different), and [W3C CSS Color 4, sRGB](https://www.w3.org/TR/css-color-4/#predefined-sRGB) for the sRGB/D65 primary coordinates and the distinction from encoded sRGB. -## Opt-in request (not yet executed) +## Opt-in request `render.preflight` / `render.start` accept an `environment` object alongside `integrator:"raytrace"`, for example: @@ -120,16 +123,19 @@ The standalone HDR checkpoint has no reflection continuation. This isolated combined source connects secondary environment misses and explicitly selected metallic rough reflectors or ideal mirrors; see [the integration contract](render-hdr-reflections-integration.md). Mixed/diffuse -rough HDR combinations and unknown optics fields refuse. No MIS, transmission, -texture, emissive geometry, GPU or saved HDR environment is advertised. Existing -saved environment controls remain refused; runtime controls are explicit above. +rough HDR combinations and unknown optics fields refuse on that legacy route. +This direct/reflection estimator itself adds no MIS or texture consumer. Saved +CPU HDR references use the existing [resource contract](render-hdr-resources.md). +Optional [opaque path lighting](render-cpu-path.md) adds matched light/BSDF MIS and +BSDF-sampled mesh emission; certified dielectric transport remains a separate +CPU route. These do not establish mixed glass/GI or general material-map support. Seven consumer source regressions complement the nine analytic/input regressions: an image-task PNG oracle and deterministic/background checks, decode/visibility cancellation and work exhaustion, native captured-source ownership, four-unit quanta, all traversal-to-shading transitions, engine rendering after source-file removal compared with unlit geometry, and capture-metadata lease release after -PNG eviction. All 16 tests remain NOT RUN. +PNG eviction. Renderer cases have executed; current combined engine contract and native workflow qualification remain separate. Consumer review repairs: environment cursor continuation charges traversal without an additional shading debit; each pixel quantum remains at most four shared work @@ -141,4 +147,4 @@ retained there. Fixed metadata is charged to the Record-owned lease independentl of the PNG, while captured image storage stays under the work lease. Preflight includes retained request metadata in its combined per-job estimate. A regression withdraws the actual HDR file and compares lit geometry against the same unlit job. -All tests remain NOT RUN. +The renderer ownership and bounded-work cases have executed; the engine file-removal regression still needs current combined qualification. diff --git a/docs/render-glass-boundaries.md b/docs/render-glass-boundaries.md index 0ed663d97..14ee874b2 100644 --- a/docs/render-glass-boundaries.md +++ b/docs/render-glass-boundaries.md @@ -7,8 +7,9 @@ only the light it had already gathered; it is never converted into transparent background. Each job counts these paths. A handful at the limits of f32 geometry (a few per billion on the captured 69-body tumbler scene) are logged and tolerated; more than one in a million paths fails the job with the first -failure's pixel, bounce, sample and code. A camera inside glass, open meshes or -overlapping solids fail every affected path and therefore the job. +failure's pixel, bounce, sample and code. Without explicit nested-media mode, a +camera inside glass remains unsupported. Open meshes or overlapping solids +are unsupported in either mode; the opt-in origin certificate is described below. Surfaces may touch closed glass, as a tumbler resting on a table does. The offset launch from such a surface can start inside the glass, so its first @@ -41,13 +42,29 @@ grazing angle. Patch identities add four bytes per triangle and their preparatio storage is included in admission. Nonmanifold or collapsed adjacency is not used to infer a patch. -Projected edge determinants use a compensated difference of products. This -avoids losing exact shared-edge cancellation on tested GPU compilers. The -algorithm follows the arithmetic described by +Projected edge determinants retain the existing compensated expression for +well-separated products, following [Matt Pharr's discussion of Kahan's difference of products](https://pharr.org/matt/blog/2019/11/03/difference-of-floats). +When four or more leading bits cancel, normalized 12-bit high/low factors supply +exactly representable partial products. Materialized scalar subtractions recover +each product residual without requiring a fused `fma`. Compensated summation uses +the existing integer-defined binary32 addition to establish round-to-nearest, +ties-to-even boundaries, then rescales the result by a power of two. Choosing +this arithmetic path leaves the geometric comparisons and distance bounds intact. + +The scalar materialization barrier depends on the positive-zero bits of +`studio_weights.w`. The host always writes that lane as positive zero; only xyz +contain the three source weights. A retained shader-layout/host-serialization test +checks the lane's actual offset and bits for implicit and explicit studio inputs. +The numerical branch adds no owned host or storage buffer. + WGSL [floating-point evaluation rules](https://www.w3.org/TR/WGSL/#floating-point-evaluation) -permit implementation variation, including expansion of `fma`; backend tests -are required, and this is not a proof of exact intersection for all WGSL devices. +permit implementation variation, including expansion of `fma`. The split-product +oracle checks exact product reconstruction and normal determinant bit patterns +against an independent f64 reference. Hardware and software Vulkan runs also keep +the original corner, medium-transition and transport-energy oracles. Floating +subnormal consumers retain WGSL's permitted handling; backend qualification is +still required, rather than claiming exact intersection on every WGSL device. Hit depth also uses an affine base plus local vertex-edge increments. Summing three weighted distances can round a distant sharp-rim entry and exit to the @@ -72,6 +89,55 @@ sloped adjacent face, exact diagonal hits, and a captured impossible hit at a polygon edge. Original editable CAD renders exercise hollow walls and repeated reflection/refraction through the production command and job interfaces. +## Actual-primary-origin certificate + +This implementation and its regressions are part of published `00edaf6a`/tree +`38a7f0af`; the GPU library passed 210 tests in CI7. Full CI7 remains red, and the +opaque native fixture does not qualify a native Glass image. See +[the qualification record](render-parity.md#qualification). In explicit nested-media +mode, each actual primary/pupil origin performs one closed-boundary-only query +before any opaque hit, visible analytic emitter, subsurface flight or escape can +consume the segment. Opaque and thin geometry cannot hide that query. For a +transverse nearest face-interior crossing in a valid certified containment +hierarchy, an exit identifies the current medium, while an entry identifies its +parent; immutable parent references then supply the complete outer-to-inner stack. +Beer starts at the actual shader primary origin. Perspective pupils use the +existing sampled eye disk. GPU orthographic primaries retain their existing +`target + back*(4*distance) + image-plane offset` origin; generic `Camera::eye()` +is not that orthographic origin, and no camera/projection policy changes here. + +The query uses the existing uploaded-f32 intersection arithmetic, dominant-axis +depth order and padded BVH. Its positive-depth search does not discard the +ordinary primary's epsilon interval: an interface inside that existing launch +interval refuses instead of being silently skipped. Detected boundary origins, +nearest edge/vertex or transverse-sign ambiguity, tied nearest depths and stack +overflow also use the existing medium diagnostics and unchanged failure fraction. +No world position, minimum ray distance, tolerance, BRDF, PDF or random draw is +changed. This is not a new exact world-space predicate or universal watertightness +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 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 +allocation, uniform/storage buffer, retained plane or snapshot. One extra BVH +query per sampled primary is bounded by the existing scene and sample caps. +GPU work is scheduled by the existing measured dispatch controller, not a +per-node debit ledger: the added cost participates in actual submission latency, +with cancellation checked between the same bounded dispatches. No cap, diagnostic +threshold or timeout is raised, and no hard wall-time guarantee is added. + +The pre-fix analytic regression preserves exact source RGB, coverage and the +existing Beer tolerance. A separate fixture correction establishes the actual +packed orthographic world origin before qualification: the earlier generic-eye +premise was wrong. The executed regression set retains first-opaque/emitter cases, +parent order, no-hit air, exact/near-launch boundary refusal, silhouettes and +f32 depth ties, physical per-pupil Beer with independent variates, copied +subsurface parameters and strict outside-path identity. These tests executed in +the published GPU suite. That execution does not establish every-backend +watertightness, native Glass visual acceptance or convergence quality. + ## Candidate anchor and local-offset continuation A rounded world-space hit point can lie outside a sharp rib even when all three diff --git a/docs/render-hdr-reflections-integration.md b/docs/render-hdr-reflections-integration.md index d4db891e2..8121cd242 100644 --- a/docs/render-hdr-reflections-integration.md +++ b/docs/render-hdr-reflections-integration.md @@ -5,8 +5,10 @@ follow-ups. The personal rendering branch now ports that work onto the combined CPU/GPU2 snapshot described in [advanced CPU integration](render-cpu-advanced-integration.md). VNDF, spatial AA, surface effects, visible emission and the bounded dielectric path are integrated -source, but their exact-revision execution and visual acceptance remain pending. -Historical checks do not qualify this new combination. +source. The combined CPU renderer has since executed the corresponding +numerical, bounded-work and image-consumer checks; current combined engine/UI +and native visual qualification remain pending. Historical checks do not qualify +those remaining gates. ## Disjoint lighting paths @@ -39,7 +41,7 @@ Explicit mirrors retain their declared ideal-reflection/Fresnel intent. The foundation retained the pinned reflection unit's projected-NDF GGX proposal. The separate [VNDF follow-up](render-vndf-prototype.md) replaces its production proposal and outgoing PDF together, with the same BSDF and null accounting; -its source-only checks do not transfer foundation validation. The integrated +its separate numerical checks do not transfer foundation validation. The integrated planar anisotropic adjunct replaces only the selected face's matched rough sampler and directional direct BRDF. There is no retry, PDF renormalization or diffuse-over- specular-PDF mixture. Both samplers preserve the same HDR miss contract. @@ -91,7 +93,7 @@ metadata as the reflection cursor state grows. It is not another decoder, cache, loader, worker or pool. Actual vector capacity must be one. Completion drops that slot; decoded/scanline capacities and source capacities retain their prior checks. A source regression checks the combined image task fits its 4096-byte host slot; -that test has NOT RUN. +that renderer layout test has executed in the combined CPU-feature build. Preparation, traversal and reflection continuation charge the shared cumulative work budget and observe cancellation. Cursor-to-shading transitions yield before @@ -108,7 +110,7 @@ GGX sample weights and deterministic variates; a broad bright cell rotating in world space; rejection of mixed/diffuse rough responses; retained selector capacities/task layout; and cancellation/work exhaustion during secondary transport. All previous HDR and reflection test sources are retained unchanged. -These tests have NOT RUN, and the prepared PNG comparisons are not screenshots. +These renderer tests have executed; their decoded PNG checks are not native screenshots or visual acceptance. Before publication, integrate real prerequisite history, run the combined default/feature checks, Clippy/wasm and required project gates, then produce and @@ -147,5 +149,6 @@ equal-axis HDR reflection matches isotropic PNG bytes; unsupported direct/mirror combinations refuse; and an actual anisotropic secondary hit into another body yields within one unit (four per public quantum) and observes cancellation. Kernel's core/face tests and v4 continuation regressions are also retained from -pinned source. Every added/adopted test is NOT RUN in this integration. Independent -source review and the combined execution/visual gates remain pending. +pinned source. The corresponding CPU renderer combination tests have executed; +this does not transfer validation to kernel changes or qualify current combined +engine/UI/native visual gates. diff --git a/docs/render-integration.md b/docs/render-integration.md index b69555c6f..4be3ca936 100644 --- a/docs/render-integration.md +++ b/docs/render-integration.md @@ -1,5 +1,37 @@ # Phased render and material integration +## Current product acceptance target (2 November 2026) + +The owner has prioritised the complete Render UI journey in #6201. Historical +feature inventories and source-only checkpoints do not complete this target. + +- **Progressive by default:** entering the rendering workflow should produce + progressive visual feedback without finding an opt-in sampling switch. Publish + every completed pass, display the captured current/target count, invalidate on + visual edits and keep cancellation responsive. A slow screen may coalesce + repaints; counters alone are not evidence that intermediate images work. +- **CPU and GPU usability:** CPU ray tracing and GPU path tracing should both + support the complete artistic and optical feature set. Until each producer, + saved contract and UI route exists and is tested, report its gap explicitly. + Do not remove an admission check to imply parity or silently switch methods. +- **Raster purpose:** offer raster for schematic presentation, with controls + appropriate to that output. Do not present it as the default photorealistic + renderer or offer unsupported optical effects as working controls. +- **Useful defaults:** a new setup should select an available ray-traced route + and an admissible progressive sample budget. Preserve existing saved setups, + output size and explicit choices. Keep the old defaults behind the normal + compatibility preference; do not silently lower quality to make a job start. +- **One trustworthy image journey:** choose an appearance, adjust lighting and + framing, see the changes, render, cancel, export the identified completed image, + save and reopen. Provisional pixels must never replace the final export source. + Keep the merged #6281 selection-driven editors, results and compare paths. + +Acceptance requires real UI interaction and original diagnostic scenes on the +tested source: opaque and textured surfaces, glass/absorption, lights and HDR, +aging, lens/finishing, a narrow window, undo/redo and cold reopen. Evaluate CPU +and GPU separately, including image quality and cancellation. Passing a codec, +one low-sample scene or a source test does not establish complete effect coverage. + The native GPU image path is described in [Progressive product images](render-path.md). Optional [CPU progressive camera sampling](render-cpu-progressive.md) through its existing CPU executor and shared image-job protocol. diff --git a/docs/render-jobs.md b/docs/render-jobs.md index 785fab7cb..57e273795 100644 --- a/docs/render-jobs.md +++ b/docs/render-jobs.md @@ -60,8 +60,22 @@ Cancellation, failure and final publication clear the provisional slot while preserving the previous successful result when no newer final exists. Each externally retained preview keeps its own admitted memory reservation. +`ui.inspect.render.displayed_receipt` identifies the cached image submitted by the +last completed, non-discarded UI pass. It contains the job, scene generation, pixel +size, final/preview kind, optional checkpoint count/sequence and adaptive phase, +and the egui frame/pass numbers. A live image uses its own captured source identity. +Merely decoding or retaining an image does not produce a receipt. A completed UI pass +without an image, or with a hidden, fully clipped, zero-opacity or comparison view, +publishes no receipt. Logic-only updates retain the old completed pass numbers, so +receipt presence alone does not establish a fresh paint. This is an image-shape submission receipt, +not acknowledgement of GPU execution, compositor presentation or every visible paint. + ## Native and browser execution +Native Single, All and live CAD preparation workers use `kernel::kernel_thread` +with an 8 MiB stack for Solidcore rc1. The admitted image executors consume the +captured triangles; this worker policy adds no kernel calls to image execution. + Each application installs one CPU host, shared by its documents. Native execution uses one worker and at most two queued inputs across documents; it runs without UI polling. The browser uses the same incremental task, pumped by UI frames, without threads. diff --git a/docs/render-light-union.md b/docs/render-light-union.md index 5f122a792..0c31bf9cb 100644 --- a/docs/render-light-union.md +++ b/docs/render-light-union.md @@ -1,8 +1,9 @@ # Combined CPU direct lights -Source-only integration: compilation, tests, native PNG inspection, Clippy, -wasm and full CI have **NOT RUN** on this revision. Historical component -results do not qualify this combination. +The combined CPU-feature renderer has executed mixed-light radiance, maximum +union, continuation and cancellation/work regressions. Current combined engine, +UI, native PNG inspection and full-project/platform qualification remain separate; +historical component results do not qualify those gates. The existing native `render.preflight` / `render.start` engine commands, also available through persistent MCP, accept these transient `raytrace` fields: @@ -57,17 +58,18 @@ terms. Each secondary hit resets area and punctual continuation state. The existing HDR/reflection estimator partition and `primary_samples` 1/4/16 policy remain; this adds no glass, MIS, GI, denoiser or material persistence. -The ordinary CLI `render` wrapper still selects the raster path. Optional -desktop CPU/AA controls are described in [CPU ray images](render-raytrace-image.md); -they do not expose explicit light authoring. This integration adds no CLI -lighting flags or UI light editor. A persistent native MCP session with the -existing `raytrace-cpu` build and installed host is the command route for these -lights. Feature-off and unavailable hosts refuse before capture. +At the original source handoff, this light-union unit added no CLI lighting +flags or UI light editor. The current Render workspace exposes installed CPU +light families through the shared [Lighting controls](render-cpu-workspace.md). +A persistent native MCP session with the existing `raytrace-cpu` build and +installed host uses the same engine request. Feature-off and unavailable hosts +refuse before capture; current combined workflow qualification remains separate. Written tests cover combined counts/capacities, recipe preservation and atomic refusals, N-independent area weights, mixed radiance, continuation partitioning, 272 attempts, cancellation/work exhaustion, preflight and Record lease lifetime. -They remain **NOT RUN**. Combined anisotropic/reflection/HDR fixtures, CLI -workflow parity, exact-build layout and presentation acceptance remain pending. +Renderer mixed-light and anisotropic/reflection/HDR combination cases have +executed. Current combined engine contracts, CLI/UI workflow parity and native +presentation acceptance remain pending. No external assets, dependencies or license changes are introduced; the existing SolidCraft implementations and their contribution licenses are retained. diff --git a/docs/render-panels.md b/docs/render-panels.md index d2a6441ff..a4e3a8bc5 100644 --- a/docs/render-panels.md +++ b/docs/render-panels.md @@ -297,22 +297,26 @@ Approved by the owner. Each changes something the earlier design said, or a defa **Path tracing (GPU)** -- Samples per pixel (1–4096, powers of two) · maximum path depth · random seed -- Reduce noise in the finished image (denoise) +- Samples per pixel (1–4096, exact counts; legacy edits round to powers of two) · maximum path depth · random seed +- Reduce noise in progressive images and the final result (denoise) -**Adaptive (GPU)** +**Adaptive (CPU / GPU)** - Allocate samples with independent pilots · pilot samples · minimum production samples - Relative RGB error · absolute floor · coverage error -**Glass transport (GPU)** +**Glass transport (CPU / GPU)** -- Conditional Fresnel strata 1, 2, 4 · certified nested dielectrics +- CPU: certified Glass limits · Use progressive sampling for a fixed setup · + Enable Indirect lighting, or show the current path depth +- GPU: conditional Fresnel strata 1, 2, 4 · certified nested dielectrics **CPU ray tracing** - Resource profile: Compact, Studio, Workstation · limits: memory, triangles, bodies, samples -- Sampling mode: single image | progressive · edge samples per pixel 1, 4, 16 · progressive samples and seed +- New setups: progressive samples per pixel and seed +- Saved fixed setups: keep edge samples per pixel 1, 4, 16 until explicit Use progressive sampling +- The previous Single image / Progressive selector remains available through Use previous Render image defaults - Reflection depth 1–8 · reflection samples 1–64 ### Effects diff --git a/docs/render-parity.md b/docs/render-parity.md new file mode 100644 index 000000000..f4c9e77dc --- /dev/null +++ b/docs/render-parity.md @@ -0,0 +1,92 @@ +# CPU and GPU renderer parity + +This table describes the supported domains retained from published commit +`00edaf6a0e6b66acf509d877428163168d5e4fcd`, source tree +`38a7f0aff298cbe50368f367c327da9aeebb1ed7`, plus the Glass follow-up described below. +A control or saved field is +not proof that every producer accepts its geometry or effect combination. Raster +remains schematic; it is not physical Glass, GI or an alternate path tracer. + +## Transport and authoring + +| Capability | CPU ray tracing | GPU path tracing | +| --- | --- | --- | +| Progressive sampling | Explicit progressive camera samples; fixed jobs retain their authored AA. | Progressive fixed-SPP and independent-pilot adaptive jobs. | +| Adaptive sampling | Independent pilot seed/reset, fixed production allocation per pixel; optional, not a convergence guarantee. | Same bounded pilot/production policy, with its own producer implementation. | +| Opaque PBR and clear coat | Common stable saved opaque coats; direct and explicit Path consume them. Selected reflection/anisotropy overrides cannot share a coat target. | Common saved coats plus the existing raw GPU coat override. | +| Built-in surface maps and aging | Saved built-in base-colour/normal/roughness/metallic maps on opaque targets; ordered aging preserves the supported closure. | Same saved built-in roles and ordered aging, under GPU source/upload limits. | +| External map files | No published common portable importer or CPU engine/UI file-map capture route. Unsupported intent refuses; built-in IDs remain usable offline. | Existing bounded PNG/JPEG temporary-input route. Portable external import is separate unqualified work. | +| Lights and environment | Bounded directional, point/spot and rectangle/LED sources. Finite Sun/Sky and diffuse environment GI require explicit Path; HDR NEE uses uniform solid angle. | Bounded hard/finite directional, point/spot and area sources, Sun/Sky and HDR importance sampling under its own limits. | +| Mesh emission | Explicit body emission is visible and Path continuation can light neighbors; no mesh-emitter next-event sampler. | No authored mesh-emission consumer; analytic area lights are a separate source type. CPU emission intent cannot be silently dropped on a method switch. | +| Glass without CPU Path | Certified one/two-triangle planar sheets and axis-aligned boxes, including valid planar tilings up to 65,536 triangles. Saved closed_mesh intent retains the legacy box projection. | Smooth thin-sheet and captured closed-mesh transport; no CPU legacy route is inferred. | +| General closed Glass | Explicit Path, progressive `primary_samples: 1` and traced shadows. Exact captured-f64 manifold/vertex-link/contact/outward certificate; no welding or geometry repair. | Captured-f32 closed/oriented homogeneous topology certificate and its documented precision/domain limits. It does not prove all self-intersections absent. | +| Nested media and inside eye/pupil | Certified Path nesting with convex enclosing parents, exact origin/near-segment checks and bounded medium stack. Touching/crossing boundaries refuse. | Explicit nested-media mode, certified hierarchy and actual shader-origin query. Default mode retains outside/disjoint restrictions. | +| Transmitted thin shadows | Explicit Path flag; parallel-sheet Fresnel/Beer with sample-count MIS. Legacy route refuses. | Enabled by thin-sheet default in the raw adapter; exact slab response on a straight connection. | +| Transmitted closed shadows | Refused, including with Path. Physical sampled Glass paths still reach emitters/environment. | Explicit opt-in 64-interface straight-through NEE approximation; not focusing, refracted silhouettes or caustics. | +| Interior subsurface scattering | Selected certified closed Path medium; active scattering requires disabled surface Denoise. | Selected closed medium; active scattering requires Denoise off, one Fresnel stratum and no active external volume. | +| External Atmosphere with Glass | Refused. Active Atmosphere is an explicit opaque-Path route and also refuses surface Denoise. | Active bounded Atmosphere also refuses Glass boundaries and active selected-medium scattering. | +| 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. | + +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 +opaque coat/maps. Different opaque targets retain their supported effects. Local +edits are prospective until explicit Save/replacement/Remove; painting never +saves. Unsupported combinations retain authored values and refuse. + +Both routes retain their existing request/profile/job/host limits, fallible exact +capacity checks, cumulative work or bounded-dispatch cancellation and completed +frame ownership. A maximum in one dimension does not guarantee the other limits +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). + + + +## Historical published qualification + +Full CI7 on tree 38a completed all 86 native test binaries: 12,223 passed, 34 failed, +58 ignored; exit 1. The renderer library passed 744 tests (1 existing ignore), +GPU library 210 (3 existing ignores), and all 433 unique Render workspace tests +passed inside the full UI library (4,396 passed, 2 failed, 19 ignored). The doctest +side job and the 14-crate WASM check passed separately. The later CI offline-web stage +was not reached after the failed test gate. + +All 34 failure-site files match selected upstream c553. That is source equality, +not proof of unchanged callgraphs or cause. Only two Boolean cases have an +independent original-input clean-c553 baseline run. See the public +[CI7 assessment](https://github.com/0xlillith/solidcraft/releases/download/material-finishes-demo-20261015/render-solidcore-main-20261103-v3-ci7-assessment.json) +and [433-test pass list](https://github.com/0xlillith/solidcraft/releases/download/material-finishes-demo-20261015/render-solidcore-main-20261103-v3-render-workspace-433.json). +No green full-CI, complete effect parity, default-quality or convergence claim +follows from the passing scoped tests. + +Actual native CPU/GPU Check, Render and same-frame PNG/raw EXR, plus CPU Cancel, +save and fresh reopen evidence used tree 562 and binary 9b. Publication differs by one cfg(test) +JSON literal; production source is identical. The native scene is an opaque +Sample Plate. It does not qualify a native Glass/scattering/Atmosphere visual, +every progressive paint, every backend or every material combination. + +## Glass follow-up (this change) + +CPU general-Glass Check performs the full geometric certificate. Each strict +prepared submission retains its ready task and moves its own source/proof into +the renderer under its owning lease and cumulative work debit. A separate Render +click prepares fresh captured intent rather than reusing an earlier Check proof. +Advertised boundaries reflect +explicit CPU Path. The editor merges saved target A and new prospective target B +without an incompatible raw-override lane or implicit Save. A checked file HDR +keeps those stable targets through CPU and GPU runtime capture; stable bindings +cannot be mixed with ordinal optical overrides. + +These are current source behaviors in this change. See +[PR #11087](https://github.com/tangency-labs/solidcraft/pull/11087) for follow-up +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. diff --git a/docs/render-path.md b/docs/render-path.md index 854db0fc2..3765176ec 100644 --- a/docs/render-path.md +++ b/docs/render-path.md @@ -35,8 +35,24 @@ checking or starting an image. These controls are transient image-job intent that can also be retained in typed saved setups. Each new saved concept uses the pending-format mechanism, without manually changing a version number. The canvas switches between live product preview and a large completed-image result, -with Fit and 100% framing. Jobs report sample progress and export the completed PNG; -partial accumulation buffers are not displayed on the canvas. +with Fit and 100% framing. Fixed-sampling jobs publish an immutable PNG after every +complete nonfinal production pass, using the same transport, denoising and finishing +as the completed image. Partially computed passes are not displayed. The host retains +at most two prepaid snapshots; pinned external snapshots may skip a publication without +stalling final rendering, and this is counted in `preview_retention_skips`. Screen repaints may coalesce fast complete-pass updates. +Provisional PNGs never become exportable results or retained linear EXR masters. +Adaptive jobs also publish each complete pilot pass and production iteration. Pilot +images show the pilot mean; those samples remain excluded from the final master. +Production images normalize unfinished sums by their completed iteration count and +retain already finished pixel means. Neither readback nor the optional preview +denoiser writes the production accumulation. Progress labels distinguish pilots +from production iterations because production counts vary per pixel. The host +target includes pilots plus the configured maximum production count. + +Adaptive readback reserves one additional float4 plane (16 bytes per pixel). When +denoising is selected, another independently reserved float4 plane supplies a +normalized display input to the same filter; final denoising keeps its original +production input. Final PNG and raw EXR remain identical with preview work disabled. ```json {"command":"render.start","params":{"settings":{"width":800,"height":600,"exposure_ev":0},"progressive":true,"samples":64,"max_depth":8,"seed":0}} @@ -83,9 +99,10 @@ transmission record is rejected by the path executor. Runtime [area lights](render-studio-lighting.md), [sun/HDR environment lighting](render-environment.md) and [opaque planar color/normal maps](render-runtime-textures.md) are available through explicit job inputs. They do not add saved document fields. An optional bounded edge-aware a-trous -[denoiser](render-denoise.md) filters the final output while preserving raw accumulation. -Texture LOD/mipmap selection, EXR and Final mode remain unimplemented by this -executor; a path-traced preview does not declare those capabilities. +[denoiser](render-denoise.md) filters progressive and final display images while preserving +raw accumulation. Optional raw scene-linear EXR masters are retained only for completed +images, before display filters. Texture LOD/mipmap selection and Final mode remain +unimplemented by this executor; a path-traced preview does not declare those capabilities. Each job builds a BVH over its immutable captured meshes with a sixteen-bin surface-area heuristic on triangle centres; there is no cross-document cache to @@ -160,3 +177,8 @@ fraction. This applies to the specular term and both diffuse transmission factor The existing actual-GPU BRDF oracle checks the limit at normal, oblique and grazing angles against the f64 surface, including mixed metallic values. Clear-coat and physical transmission contracts are unchanged by this base-lobe correction. + +The normal GPU Samples editor keeps the exact requested count, including values +such as 17 or 31; every complete pass is published. Merely opening a saved setup +does not round its count. **Use previous Render image defaults** retains the +previous power-of-two rounding for an edited GPU Samples value. diff --git a/docs/render-primary-aa.md b/docs/render-primary-aa.md index 2af9a238a..ff99b9fba 100644 --- a/docs/render-primary-aa.md +++ b/docs/render-primary-aa.md @@ -1,19 +1,20 @@ # Bounded primary spatial AA proposal (#620 / existing render-quality work) -Source port on the personal rendering branch's CPU/GPU2 snapshot. Written tests -for this recovered unit have not run on this integrated revision; compilation, -layout, PNG, performance and full project validation remain the caller's next -gate. See [advanced CPU integration](render-cpu-advanced-integration.md) for the -exact source baseline and recovery provenance. +This unit originated as a source port on the personal rendering branch's +CPU/GPU2 snapshot. The combined CPU-feature renderer build, layout and numerical +regressions have now executed. Current combined engine/UI/native qualification, +performance and full-project validation remain separate gates. See +[advanced CPU integration](render-cpu-advanced-integration.md) for the exact source baseline and recovery provenance. -`raytrace.primary_samples` is a transient request option: omitted/1 retains the +`raytrace.primary_samples` is the runtime option, also saved as CPU +`job.options.primary_samples`: omitted/1 retains the legacy fixed-centre route,4 uses a2x2 pixel-box grid,16 uses4x4. Other counts refuse. Default1 is omitted from serialized options to preserve the default -request representation. Nothing is added to document/RenderSetup persistence, -undo, GPU MSAA, material libraries or optical boundary definitions. The integrated -CPU image UI already exposes 1/4/16 primary samples; engine/MCP and the CLI's +request representation. Typed CPU setup edits use the existing save/Undo path; +GPU MSAA, material libraries and optical boundary definitions are independent. +The integrated CPU image UI already exposes 1/4/16 primary samples; engine/MCP and the CLI's runtime raytrace options use the same request contract. This recovered follow-up -changes the bounded reuse implementation, without introducing saved AA state. +changes the bounded reuse implementation, without adding a second saved AA authority. The single-primary branch keeps its former generator, reuse proof, R addition order/divisor, primary-background shortcut, seeds, work debits and encoding. @@ -44,8 +45,10 @@ apply exposure/Reinhard once to G, then composite C*T(G)+(1-C)*decode(background in display-linear sRGB before one sRGB encoding. All-miss pixels retain the exact background bytes; full coverage omits background operations. Background remains display-referred, not an emitter and not exposure-controlled. Do not averageRGB8, -individually tone-mapped paths or tone the premultiplied P. Output alpha stays255; -coverage is internal quadrature, not transparency/refraction support. +individually tone-mapped paths or tone the premultiplied P. Opaque output keeps +alpha255; explicit [transparent PNG](render-cpu-output.md#transparent-png-coverage) +exports straight RGB and rounded geometric coverage. Neither mode turns material +opacity into physical refraction. One ImageTask/PendingPixel/BVH/host pool and one cumulative1e9 WorkBudget remain. AA retains fixed scalar/Vec3 accumulators; reuse adds no fields. Per-R-add @@ -56,7 +59,8 @@ cancellation is checked again just before pixel bytes are emitted. Running progress still counts completed OUTPUT pixels. No partial PNG or samples reduced on exhaustion. Existing384MiB job/512MiB host limits and PNG encoder are retained. A compile-time type-length check and written layout regression require actual -ImageTask<=4096 bytes; because no build has run, actual layout is NOT qualified. +ImageTask<=4096 bytes; that guard passed in the combined CPU-feature build. +Other feature/platform configurations retain their own validation gates. Cost can grow with S*R, traversal, lights, HDR and bounces. Retaining exact intra-spatial primary reuse does not establish any work-budget success. Limits @@ -73,7 +77,8 @@ same caps/layout. The blanket birth-proof policy assertion changes as described above; existing observable assertions remain. New actual-consumer tests compare every ordered R accumulator prefix, logical coverage and PNG bytes with the same ImageTask route whose proof is revoked before its first shading completion. -Execution, type/layout checks and all acceptance gates are pending. +The renderer numerical and type/layout checks have executed. Current combined +engine/UI/native and full-project acceptance remain pending. Default-vs-historical exact-build byte/work comparison, engine/host preflight validation, arbitrary projection scenes, allocation/layout and ownership gates, Clippy/wasm and required cargo xtask ci are required before publication. Designer diff --git a/docs/render-raytrace-core.md b/docs/render-raytrace-core.md index a9c98c272..bbe356e42 100644 --- a/docs/render-raytrace-core.md +++ b/docs/render-raytrace-core.md @@ -107,12 +107,13 @@ The source includes analytic distance/barycentric/normal tests, tiny/huge and grazing cases, shared-edge ties, slab/parallel cases, BVH-versus-brute-force seeded closest/any-hit comparisons, hostile float admission, deterministic incremental stepping, depth/degenerate termination and work/memory/cancellation -checks. These are planned executable checks, **not passing results until run**. +checks. These renderer regressions have executed on the combined CPU-feature source. Required validation before publication: project quality gates, default and feature-enabled render tests/strict Clippy, and feature-enabled wasm checking. -The current source-only preparation intentionally does not run Cargo while -another owner holds the shared machine's build window. +The original source-only preparation deferred Cargo while another owner held +the build window. That historical handoff does not describe the later executed +CPU renderer checks; current combined workflow/platform gates remain separate. RT2 is the separate useful image unit: explicitly selected opaque CPU visibility and cast shadows, using the existing camera/scene and host ownership/accounting. diff --git a/docs/render-raytrace-dielectrics.md b/docs/render-raytrace-dielectrics.md index 8f2f91248..b98365191 100644 --- a/docs/render-raytrace-dielectrics.md +++ b/docs/render-raytrace-dielectrics.md @@ -1,8 +1,10 @@ # Bounded CPU dielectric preview (#1655) -Source implementation only: focused tests, real native PNG acceptance and full -project gates have not run on this integrated revision. The render and engine -crates keep `raytrace-cpu` optional; the application controls whether its normal +This page describes CPU dielectric transport **without explicit Path**. The +published source's renderer, document, engine and workspace tests executed in +CI7; the full gate remains red and native Glass visual acceptance is pending. +Explicit Path has the separate [general Glass](render-cpu-general-glass.md) +contract. See [qualification](render-parity.md#qualification). The render and engine crates keep `raytrace-cpu` optional; the application controls whether its normal build enables it. The CPU executor remains native only. This unit reuses the image-job host, queue, cancellation, admission lease, incremental BVH traversal and PNG encoder. @@ -11,22 +13,26 @@ on the CPU route (`integrator: "raytrace"`, without `progressive: true`). GPU progressive requests retain their own dielectric schema and transport. Neither path infers glass from a saved appearance's alpha value. -CPU preflight reports `transparency: "physical_transmission"` when its request -contains admitted dielectric overrides, with `dielectric_boundaries` limited to +Without Path, CPU preflight reports `transparency: "physical_transmission"` when +its request contains admitted dielectric overrides, with `dielectric_boundaries` limited to `["thin_sheet","closed_box"]`. Without overrides it reports `"opaque_only"` and an empty boundary list. This metadata describes the requested transport; both CPU -raytrace cases still require surface alpha one and an opaque PNG background. +raytrace cases still require surface alpha one. The optional transparent PNG +background exports primary geometry coverage; glass does not gain a compositing +matte for a different transmitted background. The native host's `descriptor_for(Raytrace)` advertises `refraction` in its Preview / Image / PNG profile, and CPU requests containing dielectric overrides require that capability during both preflight and host submission. This is the -bounded `thin_sheet` / `closed_box` contract below: it does not advertise general -closed-mesh transmission, final-quality rendering or progressive CPU images. +bounded `thin_sheet` / `closed_box` contract below, shared by fixed and progressive +CPU sampling: it does not advertise general closed-mesh transmission, caustics +or diffuse global illumination. Raster and the cooperative CPU host do not advertise this capability. The `render.backends` registry publishes the additional `cpu-raytrace` descriptor only -for an installed native CPU worker with the build feature enabled. Raster remains -the default, and the explicit CPU raytrace route resolves its own integrator-specific -descriptor. See [backend discovery](render-backends.md#installed-image-methods). +for an installed native CPU worker with the build feature enabled. New unsaved +setups use CPU progressive when this host is available and legacy defaults are +off; saved, legacy and offline setups retain their existing route. The explicit +CPU raytrace route resolves its own integrator-specific descriptor. See [backend discovery](render-backends.md#installed-image-methods). A CPU request example: @@ -82,13 +88,14 @@ optics equations; no rendering-engine source was consulted or adapted. The was consulted as a mathematical reference only; no text or assets were copied. Primary misses preserve the request's display-sRGB background bytes, independent -of exposure. Reflected/transmitted misses default to black. An explicit runtime +of exposure, or zero RGBA when transparent background is requested. Reflected/transmitted misses default to black. An explicit runtime `environment:{color:[r,g,b],intensity:n}` supplies a constant secondary radiance: finite linear-sRGB channels in 0–1 and relative intensity in 0–64. It is separate from the display background and receives the same one-time exposure/display mapping as the accumulated optical contributions. Unit white environment radiance maps to approximately 188/255 at zero exposure. It is not HDRI lighting and does -not illuminate opaque diffuse surfaces. Transparent PNG backgrounds remain unsupported. +not illuminate opaque diffuse surfaces. Transparent PNG exports primary geometry +coverage with straight RGB; transmitted/reflected paths and raw EXR are unchanged. Transport deterministically splits Fresnel branches using a fixed nine-slot DFS stack, at most eight dielectric boundary events and 511 paths per pixel. An @@ -113,7 +120,12 @@ must fit that 32 KiB allowance. The original request's directional-light vector, dielectric-selector vector and name capacities have a separate lease in the same host pool, held by the immutable status record independently of PNG retention or eviction. Original capacities are validated before cloning. Total job and shared-host limits remain -384/512 MiB. Certification is a bounded admission check of at most 96 triangles. +384/512 MiB for the compatibility Compact envelope. Current closed boxes may +contain 12 through 65,536 boundary triangles; every triangle must remain on the exact +outward box boundary and satisfy the unchanged edge/area certificate. Fallible +triangle/edge/sort scratch is prepaid for the largest selected box and reused +between boxes, in addition to the fixed state above. Other CPU profiles retain +their separately documented limits. Preparation, all traversals and optical transitions consume the existing cumulative billion-unit budget and cancellation token; limit exhaustion fails the job without publishing a partial image. Each task unit performs one cursor @@ -124,13 +136,13 @@ not OS timing or RSS guarantees. Source regressions cover F0=0.04, Snell/reversibility, TIR, absorption and slab offset scaling, closure/winding/identity refusals, nested-volume admission, bounded runtime DTOs, cancellation and small decoded PNG controls for clear -volumes and 2/8 mm absorption. They are **not passing results until executed**. +volumes and 2/8 mm absorption. These renderer regressions have executed. Required acceptance also includes an original native scene with identifiable background geometry, paired oblique slab PNGs, physical/persistence invariants, work exhaustion, cancellation and captured-resource release. Current source tests alone do not establish this visible acceptance or qualify the draft PR. -## Thin-sheet polarization correction (source only) +## Thin-sheet polarization correction The incoherent internal-return series is evaluated separately for s and p polarization. For one polarization with interface power reflectance `F` and @@ -153,5 +165,43 @@ This correction preserves polarization only inside the analytic parallel-sheet closure. The existing transport still carries a scalar unpolarized response; it does not add full Stokes transport or change the closed-volume approximation. The runtime schema, boundary certification, millimetre units, path limits, and -virtual-thickness geometry contract are unchanged. These new Rust regressions -have not been built or run; the source-only correction is not acceptance proof. +virtual-thickness geometry contract are unchanged. The rational-value and +actual decoded PNG regressions have executed in the CPU renderer suite; native +visual and combined workflow acceptance remain separate. + + +## Saved optical bindings and common Glass controls + +The existing stable `RenderSetup.optics` contract can also be consumed by an +explicit CPU job. Definition/feature/component/occurrence identity resolves into +an exact visible captured body name and ordinal at Check/Render. The CPU request +uses its existing `DielectricOptions`; no engineering material, product opacity, +physical transmission, CAD geometry or mass changes. + +Without Path, saved `closed_box` and `closed_mesh` intent execute only when the +captured mesh passes the strict axis-aligned-box certificate, including valid +planar tilings within its 65,536-triangle bound. The saved boundary is retained unchanged; a sphere, cylinder, +rotated box or arbitrary closed mesh does not gain support. Thin sheets retain +the strict one/two-triangle planar certificate and authored virtual thickness. +All overlap, near-plane, camera/lens, coat and per-path guards still apply. + +CPU glass supports the authored IOR and per-mm Beer extinction for at most eight +targets. Extinction is 0..100 per mm and virtual thickness 0..10000 mm. Authored +transmissive shadows and any subsurface value refuse explicitly. Common thin +recipes retain their transmissive-shadow flag: turn that flag off explicitly +before rendering on this legacy route. CPU/GPU opaque coats and saved built-in +maps are separate supported contracts; they cannot share a Glass target. Explicit +Path provides general Glass/nested media and diffuse GI under its own certificate; +this legacy route does not gain those features, and no caustic claim is made. + +The common Glass editor creates temporary request-local presets and can save +compatible numerical optics with the existing reviewed bind command in one undo. +Reopening a selected stable saved target shows its actual enabled state, IOR, +Beer extinction and boundary without allocating a temporary override on paint. +Edits to those saved controls replace or remove only their exact target in a +cloned image request, so live feedback uses the prospective values immediately. +The document changes only through explicit Save/replacement or Remove. Discard +returns to the saved values. Other saved rows remain intact; stale identities or +changed sources refuse instead of targeting a new body. Mixed legacy temporary +bindings or file-only HDR inputs retain an explicit conflict where they cannot +share this typed request. diff --git a/docs/render-runtime-textures.md b/docs/render-runtime-textures.md index 982b8f5fc..551f3b712 100644 --- a/docs/render-runtime-textures.md +++ b/docs/render-runtime-textures.md @@ -1,6 +1,6 @@ -# Runtime planar opaque maps +# Opaque surface maps -The renderer supports built-in sources, absolute-color mode, explicit V orientation, linear roughness/metallic maps and content-addressed texture sharing. See [built-in library](render-built-in-library.md) for its bounded resource contract. Legacy examples below retain modulation and rows-down defaults. +Surface maps provide base colour, OpenGL tangent-space normals, roughness and metallic values. Built-in sources can be saved with a shot using stable definition/feature/occurrence identity and pinned version/digests. See [built-in library](render-built-in-library.md) for its bounded resource contract. Legacy examples below retain modulation and rows-down defaults. Engineering geometry and material properties are unchanged. Progressive GPU jobs accept immutable per-body base-color and OpenGL tangent-space normal maps. Runtime commands capture file bytes once; queued work does not reopen paths. @@ -13,6 +13,26 @@ physical grain orientation, offline reopening and native CPU execution. {"progressive":true,"raytrace":{"textures":[{"body_index":3,"body_name":"Walnut tabletop","frame":{"origin":[0,0,480],"u":[900,0,0],"v":[0,90,0]},"base_color_srgb":"C:/art/wood.png","normal_opengl":"C:/art/wood-normal.png","normal_strength":0.35}]}} ``` +CPU ray tracing consumes saved opaque maps in direct lighting and the optional +progressive Indirect lighting route. In the library, choose a surface and **Save +maps to shot**. The same binding command works offline without a render host: + +```json +{"name":"Studio","set":{"job":{"method":"cpu_raytrace","options":{"progressive":{"samples_per_pixel":16,"seed":9}}}},"surface":{"id":"SURF-001","body_index":0,"body_name":"Panel"}} +``` + +Pass this object to `render.library.surface.bind`; it is one Undo step. The target +must match `render.scene`. Check and Start resolve the saved stable identity again. +Missing, hidden, changed or ambiguous targets and mismatched installed source +versions/digests refuse rather than rebinding another body. CPU temporary map paths +remain unavailable. Imported design-owned images use the separate saved-resource +workflow described in [portable surfaces](render-portable-surfaces-and-stages.md). +CPU maps require an opaque target. With Indirect lighting, Glass may be assigned to +another body, but maps and Glass cannot share a target. Selected custom reflections, +anisotropic faces and procedural surface-effect overrides remain incompatible; +authored settings stay intact and the request refuses. Raster does not consume +these bindings. A CPU producer must be installed before a CPU image can start. + Each `u` and `v` world-space vector spans one complete repeat, in millimetres. The vectors must be nonzero, orthogonal, and 0.001–1,000,000 mm long. The origin is UV zero. Image V increases downwards; normal red and green point along the positive @@ -53,6 +73,9 @@ not change their encoded samples or introduce a new refusal. Portable design-own imports require normalized sRGB declarations for base color and validate static metadata before publication. The native CPU metadata worker also rejects conflicting base-color declarations. Normal and scalar roles retain their raw numerical channels. +The cooperative native CPU map worker accepts static noninterlaced 8-bit PNG +layouts and refuses JPEG, interlace, APNG and other depths. For CPU execution, normalize JPEG or interlaced images to this PNG contract before +import. Import stores exact supplied bytes and performs no conversion. No implicit color-profile conversion is performed. The sRGB base/data normal distinction follows the public [Khronos glTF material semantics](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#materials), @@ -77,6 +100,17 @@ The independent progressive device requests six storage buffers per shader stage. An adapter limited to fewer cannot install this executor; raster and tessellation device requirements remain unchanged. +CPU completes the Effects→Maps→Aging closure before the hit's direct/GI BRDF, +PDF and proposal, and before deterministic denoise guides. Supported combinations +are documented in [CPU Path](render-cpu-path.md) and [CPU Glass](render-cpu-general-glass.md). +Maps add no rays or sampling dimensions. Omitted maps allocate no prepared cache +and retain the original image calculation. CPU work and registered-executor +resource Arcs move into work; public requests retain summaries. Completed frames, +raw EXR masters and status handles do not retain source bytes after work release. +`work_released`, rather than a terminal phase alone, remains the retirement barrier. +Cancellation, decode failure and late cancellation cannot publish a partial cache +or completed image. + Independent f64 tests cover explicit sRGB decoding, linear normal channels, repeat filtering, handedness, degenerate fallback, admission and lifecycle. GPU reference tests compare the actual packed storage and WGSL sampler/normal diff --git a/docs/render-settings.md b/docs/render-settings.md index e3f99d8e2..b6ab9642f 100644 --- a/docs/render-settings.md +++ b/docs/render-settings.md @@ -33,7 +33,7 @@ model without applying or saving anything. An unsaved client draft can instead pass `{settings: }`; `{}` inspects the default setup. Neither form selects a UI shot. Unknown parameters, null selectors, both selectors, missing setup names and invalid settings refuse without mutation or evaluation. -CPU directional/point/spot/rectangle sources and GPU sun/rectangle sources expose +CPU/GPU hard-directional/sun/point/spot/rectangle sources expose `id`, `kind`, `name`, `name_key`, `number`, `implicit`, `intensity`, `colour` and their world-space geometry. Background and environment illumination are separate from this source list. Implicit fixed studios and CPU presets are expanded; @@ -47,13 +47,30 @@ document identities. Unnamed lights display Key, Fill, Rim, then Light 4, etc.; clients translate `name_key`, substituting `number` for later lights. Names are not persisted by this command. -Colour is linear RGB. CPU colour/intensity retain their saved values. GPU RGB +Successful light edits additionally return bounded `id_remap` entries +`{before: Light, after_id}` for each surviving original source. The engine uses +original slot identity, not numerical-value matching: a duplicate is a new source +even when its values equal its parent. CPU/GPU canonicalization puts the finite Sun +first. The UI verifies each before record against its current draft, then remaps +mute, solo and surviving unrelated selection; unmatched identities from a different +settings override are cleared. Add/set/duplicate still select their actual result. +Numeric editor drafts are invalidated. A source RenderSettings Arc tracks verified +authoring provenance. Unverified structural Undo/Redo, checkpoint, replacement or +same-shape reorder clears mute/solo, Light selection and parameter drafts, rather +than guessing identity from ordinals or equal values. One bounded before/after +Weak-Arc proof preserves the latest verified numerical light-set Undo/Redo; older +or otherwise unproved transitions clear. Fallback labels remain ordinal (Key, Fill, +etc.) and may change after insertion; this adds no persistent custom naming. +Untouched original Sun/area rows retain their raw authored RGB rather than an +unrelated common-editor divide/multiply round trip. + +Colour is linear RGB. CPU colour/intensity retain their saved values. GPU hard directional colour/intensity also retain their exact saved values. Finite Sun RGB and GPU area RGB radiance is factored into its largest channel as intensity and normalized colour (black uses intensity zero and white colour). Their product recovers radiance; no photometric equivalence between methods is implied. All rectangle edges are full side vectors in millimetres, including GPU half-edges multiplied by two. Directional vectors point towards a source; spot axes point from it. The optional -directional `angular_radius_rad` identifies a finite GPU sun. +directional `angular_radius_rad` identifies a finite Sun (CPU requires explicit Indirect lighting). `render.lights.add`, `.set`, `.duplicate` and `.remove` edit a named setup in one undo step. They accept `name`, `id` except for add, optional complete `settings` @@ -64,11 +81,18 @@ as an unsaved starting point, and optional `expected_revision`. Add/set accept `reference_distance_mm` and `minimum_distance_mm`. These lower into the existing light fields; there is no new saved light metadata. Temperature is an original three-band, 6500 K white-balanced Planck tint approximation stored as linear RGB. -Area softness changes emitter size; GPU Sun softness changes angular radius. +Area softness changes emitter size; finite Sun softness changes angular radius. Hard CPU directional and point/spot sources refuse unsupported emitter softness. -CPU admits 8 directional, 8 point/spot and 4 areas; GPU admits one Sun and four -areas. GPU Point/Spot controls and the legacy three-directional GPU studio editor -remain unavailable with reasons, rather than silently losing light sources. +CPU and GPU each admit 8 directional, 8 point/spot and 4 areas. Directional +sources include at most one finite Sun; CPU finite Sun requires explicit Indirect lighting. Point and Spot share eight slots. Both +methods expose Spot emission axis and inner/outer half angles; the UI displays +degrees while saved/runtime fields retain radians. A GPU feather needs +`cos(inner) - cos(outer) >= 1/1024`; narrower authored CPU cones explicitly refuse +on GPU rather than being widened or ignored. Materializing or duplicating the implicit GPU +studio preserves all three hard source values; it does not replace them with a Sun. +A directional source without angular_radius_rad is hard on either method. GPU +Add offers both Directional and the existing Sun (.02-radian radius). Finite Sun +duplication refuses; hard sources duplicate until the combined eight-source cap. `render.lights.solo {id?, solo}` and `render.lights.mute {id, mute}` validate and echo view requests. Enabling solo requires an id; disabling solo clears it. @@ -88,8 +112,9 @@ CPU ray tracing and explicit GPU rigs refuse these fixed-studio weights. The selectable Lights group runs `view.render_select {kind: "lighting"}` and opens Lighting: Light source, Shadows and sampling, then Budget. Its + still adds a light. CPU presets require review and consent before replacing directional lights; -Custom materialises their existing values. GPU budgets show one Sun and four -Areas; CPU eight directional and eight point/spot plus four Areas. Counts are +Custom materialises their existing values. GPU budgets show eight directional +sources including the optional Sun and four Areas; CPU eight directional and +eight point/spot plus four Areas. Counts are read-only sliders. Unsupported controls stay faded with a reason. No rig identity is saved, so there is no Rig row. @@ -144,7 +169,7 @@ are millimetres, angles are radians and light colours/radiances are linear RGB. | Method | Saved fields | Main limits and defaults | |---|---|---| | `raster` | `transparent_background` | Defaults to false; no nonzero exposure or raytrace controls | -| `cpu_raytrace` | `options`: optional `progressive`, `primary_samples`, `preset`, `lights`, `punctual_lights`, `area_lights`, `area_samples`, `seed`, `shadows`, constant `environment`, embedded `hdr` | Primary samples 1/4/16 (default 1); shadows true; optional progressive/lists/preset/environment/HDR absent. At most 8 directional, 8 point/spot and 4 rectangular lights; progressive has the narrower contract below. | +| `cpu_raytrace` | `transparent_background` (default false), `options`: optional `progressive`, `primary_samples`, `preset`, `lights`, `punctual_lights`, `area_lights`, `area_samples`, `seed`, `shadows`, constant `environment`, embedded `hdr`, optional `lens` and `output` presentation | Primary samples 1/4/16 (default 1); shadows true; optional progressive/lists/preset/environment/HDR absent. At most 8 directional, 8 point/spot and 4 rectangular lights; progressive has the narrower contract below. | | `gpu_path` | `transparent_background`, `options`: `samples`, `max_depth`, `seed`, `tone_map`, `denoise`, `lens`, `lighting`, sky `environment`, embedded `hdr` | Samples 1..4096 (default 64), depth 1..16 (default 8), seed u32 (default 0), Reinhard tone map, denoise false, optional values absent | CPU `preset` and explicit `lights` are mutually exclusive. An omitted/null light @@ -159,18 +184,43 @@ validation contracts. CPU `progressive: {samples_per_pixel, seed}` stores bounded camera accumulation using the existing CPU transport. An absent/null value preserves fixed AA; an -empty object defaults to 16 samples and seed 0. Samples are 1..64 and the seed is -u32. `primary_samples` must be 1, output is at most 1,048,576 pixels, and +empty object defaults to 16 samples and seed 0. With the Compact profile, samples +are 1..64 and the seed is u32. `primary_samples` must be 1, output is at most 1,048,576 pixels, and `width × height × samples_per_pixel` is at most 16,777,216. Saving checks these -limits without a render host. Area/LED lights, dielectric and anisotropic-face -overrides are refused in this mode; the fixed CPU route retains them. Embedded -HDR and one setup exposure remain compatible. See +limits without a render host. Larger CPU profiles use their own bounds; for example, +Studio admits 3840 × 2160 at 128 samples per pixel. Other memory, geometry and work +limits still apply. See [CPU resource profiles](render-cpu-resource-profiles.md). +Rectangular and continuous LED lights retain their +bounded direct-light integral for each camera sample. Dielectric and anisotropic-face +overrides retain the existing certified thin-sheet/axis-aligned-box and planar-face +transport and geometry guards. Embedded HDR and one setup exposure remain compatible. See [CPU progressive sampling](render-cpu-progressive.md) for reflection limits, work admission and provisional/final publication. The top-level runtime `progressive: true` continues to select GPU. -GPU `lighting` retains the complete RGB ambient radiance, optional sun and at most -four rectangular lights. Omitted/null lighting keeps the renderer's legacy studio; +CPU `lens` stores the same `{aperture_radius_mm, focus_distance_mm}` as GPU. +Positive aperture requires explicit progressive sampling plus a bounded perspective +setup camera. No second camera is saved; Frame lens edits preserve the saved +camera and current navigation. Absent/null keeps pinhole behavior; an explicit +zero aperture remains explicit and keeps the old fixed-AA/orthographic pixels. +Whole-pupil glass clearance and bounded ray intervals are checked against the +captured scene at render admission. See [physical thin lens](render-thin-lens.md). + +CPU `output` optionally stores `{tone_map, finishing, backdrop, linear_exr}` using +exactly the shared presentation operators. It has no second exposure/background: +setup exposure and background remain authoritative. Omission/null preserves the +original CPU f64 PNG, as does identity presentation with optional raw retention. +Nonidentity effects apply to every complete progressive pass; only final completion +retains a raw master. The shared output envelope is 8192 per side and 16,777,216 +pixels, independently of a larger CPU resource profile. See +[CPU output presentation](render-cpu-output.md). + +GPU `lighting` retains the complete RGB ambient radiance, optional sun, at most +four rectangular lights and a bounded `directional_lights` array of +`{direction:[x,y,z], color:[r,g,b], intensity}`. Hard directions share the CPU +contract: finite nonzero vectors with components within +/-1e9, linear RGB 0..1, +relative intensity 0..64. The hard list and optional Sun total at most eight sources. +Empty hard lists are omitted when saving; existing designs preserve their meaning. Omitted/null lighting keeps the renderer's legacy studio; an explicit all-zero lighting object means a black studio. Those values are not interchangeable. `lens` retains aperture radius and axial focus distance; nonzero aperture requires a perspective camera. An explicit zero-aperture lens remains @@ -229,8 +279,8 @@ existing runtime request API remains available; it has no inferred CPU/GPU metho ### Explicit portability boundary -External HDR paths, texture maps, GPU dielectric/clear-coat/texture body bindings and CPU -reflection, anisotropy, emission, surface-effect and dielectric bindings are not +External HDR paths, texture maps, temporary GPU clear-coat/texture body bindings and CPU +reflection, anisotropy, emission and surface-effect bindings are not part of this saved job format. Their fields are rejected, even when an unsupported list is empty. Runtime requests can still use those existing features with an inline setup whose `job` is null. Saving a complete setup must not discard them or @@ -249,11 +299,12 @@ Named setups live in `render: {setups: {name: setup}, resources?: {sha256: resou empty render state is omitted. The optional numerical job adds the `render-job-intent` pending format descriptor. Embedded HDR adds its own `render-hdr-resources` descriptor. -The optional CPU sampling field adds `render-cpu-progressive`. +The optional CPU sampling field adds `render-cpu-progressive`. CPU presentation +and physical lens intent share the `cpu-output-presentation` pending descriptor. No historical format number or migration step is rewritten. Older designs need no job transformation: an absent job keeps their common settings and runtime API. -Pending builds without the descriptor refuse the newer design instead of silently -losing its saved options. Plain JSON, design containers and document autosave +Builds without the descriptor open the newer design with a warning and preserve +its saved options they cannot read. Plain JSON, design containers and document autosave snapshots carry all HDR bytes. A command-only crash replay before a new checkpoint still needs the source path recorded by `capture_hdr`; it must match the recorded digest. This unit does not make that journal self-contained. @@ -274,3 +325,74 @@ the setup stores image configuration, not material assignments. No new third-party dependency or asset is introduced. `doc` depends on the existing pure `render` crate for its shared camera and R1 identifiers, within the L2 → L1 rule. + + +CPU `transparent_background` is stored beside boxed numerical `options`, like +Raster/GPU, and defaults to false for older designs. True requests straight-alpha +primary geometry coverage in fixed/progressive PNGs; it does not alter engineering +appearance opacity or raw EXR. Active bloom, backdrop and photographic operators +still refuse with transparent output. The existing CPU output pending descriptor +covers this saved flag. See [transparent CPU PNG](render-cpu-output.md#transparent-png-coverage). + + +## CPU spatial denoising + +An explicit CPU job can save `job.options.denoise: true`. The default is false; +false is omitted from the canonical wire representation, so older CPU setups +keep their previous image and allocation path. It lowers only to the native +CPU `raytrace.denoise` option. The corresponding GPU field remains separate. + +The optional three-pass filter uses deterministic first-hit geometry guides, +filters every complete published image pass before presentation, and preserves +raw film, RNG/sample identity and final-only EXR. Its guide, ping-pong and task +storage is admitted under the unchanged CPU profile. Filtering shares the +8192-side/16,777,216-pixel output envelope and never silently reduces size or +changes the selected executor. Offline validation and save/reopen retain the +flag without initializing a renderer. See [spatial denoising](render-denoise.md) +for bypasses, bias, cancellation/work units and retained-master regrade limits. + + +### CPU consumer of portable optics + +Stable `optics` rows remain the same saved contract for CPU and GPU. An explicit +CPU job validates at most eight IOR/Beer targets offline. Without explicit Path it +refuses authored transmitted shadows/subsurface and keeps its strict sheet/box +certificate. The separately prepared Path route adds general closed Glass and +selected-medium scattering; its new source still needs qualification. On the original absent-Path route, a saved general closed boundary stays authored +as `closed_mesh` and must prove the box subset. No boundary, target, effect or material is silently +removed to make a job run. See [CPU certified glass](render-raytrace-dielectrics.md). +Common Glass controls hydrate actual saved numbers without creating a runtime +override on paint. Their unsaved edits overlay only the selected stable rows in +captured image settings; Save/replacement and Remove remain explicit document +commands with one undo. This consumes existing portable fields and adds no format +number or new design metadata. + + +The optional [CPU opaque path lighting](render-cpu-path.md) consumer is part of the combined source and has executed renderer regressions. It adds bounded progressive diffuse/specular GI only when `path` is authored; existing restrictions and bytes above describe the absent-path route. Prepared general Glass/SSS, independent bounded Atmosphere and Sun/Sky have separate source/qualification notes. Mixing active Atmosphere with Glass/SSS, selected anisotropy and combined document/engine/UI/native qualification remain incomplete. + + +GPU `lighting.punctual_lights` preserves each existing `PunctualLightOptions` field. +Intensity is the relative on-axis incident value at `reference_distance_mm` and +falls by inverse square distance, multiplied by the cosine-space Spot smoothstep. +This does not imply lumen/lux/IES calibration. Nearer-than-minimum or excessive +(above 1e12 linear RGB) samples contribute zero and increment typed diagnostics; +no inverse-square clamp is applied. Re-aimed finite shadow connections exclude +the source, and offset crossings increment a separate omission count. + +The registered worker publishes `punctual_diagnostics` through the existing job +status. GPU counters are cumulative through the most recent complete image +readback, including adaptive pilots and production Fresnel strata; an interrupted +partial dispatch need not appear in that last snapshot. Each counter is 64-bit +via two carry words, separate from unchanged medium-failure words 0..7. The +existing host metadata/work-release lifetimes and retained-options lease apply. + +CPU canonical quality chips use a separate `render.quality.prepare` projection, +`cpu_progressive_png`, from the same three Q-* entries. It returns only size, +progressive production count/seed and a bounded CPU profile; it does not enable +GI, change denoise or replace authored optics/effects. Optional `cpu` context +contains `minimum_budget` and the preserved `adaptive` policy. Profile selection +includes pilot+production camera work and never lowers that minimum profile. +The existing `fixed_samples_png` GPU and acknowledged imported-review contracts +remain unchanged. These projections are read-only and do not certify convergence. + +CPU saved `sun` and `sky` preserve the shared numerical domains and explicit method-switch/adoption policy described in [CPU celestial lighting](render-cpu-celestial.md). The renderer, saved/runtime and UI tests have executed; dedicated native Sun/Sky image-quality acceptance remains pending. diff --git a/docs/render-studio-lighting.md b/docs/render-studio-lighting.md index db1a252f8..c742937de 100644 --- a/docs/render-studio-lighting.md +++ b/docs/render-studio-lighting.md @@ -67,3 +67,59 @@ MIS estimates with a white furnace, validate bounded requests, and check that preflight leaves the document unchanged. GPU tests require an actual supported adapter when SOLIDCRAFT_REQUIRE_GPU is set; no visual milestone is implied by these numerical tests. + +## Hard directional sources + +The optional `lighting.directional_lights` array retains up to eight sources: +`{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}`. Direction points toward +the source, is finite/nonzero, and each component is within +/-1e9. Linear RGB is +0..1 and relative incident intensity is 0..64, matching CPU directional intent. +The optional finite Sun and this list share an eight-source total. The finite Sun +keeps its angular-radius, radiance and continuous-MIS contract. Hard sources use +delta next-event samples with MIS weight one and consume no random numbers; they +are not enlarged disks. Existing rectangle, environment and Sun sample ordering +is unchanged. Surface/transmissive and external-medium visibility are shared with +the existing source loop, with no extra inlined BVH call site or storage binding. + +Omitting `lighting` leaves the exact implicit three-source path. An omitted or +empty directional list adds no source or RNG consumption. Materializing the +implicit studio into explicit hard directions preserves those three values. +Zero-intensity/black sources remain authored but perform no sampling/visibility. +Mesh emission remains unsupported by this GPU consumer. Point and Spot sources +use the separate punctual-light contract below. + +The fixed uniform grows by 256 bytes, prepaid as device+host upload storage. Its +final `studio_weights.w` lane stays positive zero, preserving the portable +geometry arithmetic ABI. Nondefault captured options live in one exact-capacity +fallible allocation with a retained lease under the existing request/job/host +caps. Structural defaults allocate no options slot; authored `Some` values are +never collapsed merely because they look like an identity at runtime. + + +## Point and Spot sources + +`lighting.punctual_lights` is an optional bounded array of eight combined Point +and Spot sources, separate from the eight directional and four area slots. +Positions are world millimetres, RGB is linear, intensity 0..64 is defined at the +explicit reference distance 0.001..1e6 mm. Minimum distance 0.001..reference is an +omission boundary, not a brightness clamp. Spot emitted axes point FROM the +source; half cones retain exact authored radians. Smoothstep is in cosine space. +GPU feathers with cosine gaps below 1/1024 explicitly refuse before source I/O; +CPU retains its wider existing f64 cone domain. + +Each delta source is evaluated once at every admitted opaque or external-volume +vertex, including the final allowed bounce, with MIS weight 1 and no random +numbers. Physical hit-to-source deltas use camera-relative high/low source and +hit positions. The robust shadow connection is re-aimed separately, excludes the +source endpoint, respects opaque blockers and existing thin/solid transmission, +and applies finite external-volume Beer attenuation. This does not broaden the +existing glass/SSS/volume compatibility policies or add refracted caustic NEE. + +The additional fixed uniform is640bytes, charged for both device and host +upload. Three64-bit omission counters append24bytes to the existing failure +storage and readback, prepaid twice. Full nondefault `JobOptions` remains charged +by its exact retained slot size. No image plane, extra storage binding, cap raise +or new light-selection RNG dimension is introduced. Default/absent-list numerical +streams are protected by retained zero-source/mixed-family regressions, but +cross-platform byte identity, device validation and native usability still need +execution on this staged candidate. diff --git a/docs/render-studio-ui.md b/docs/render-studio-ui.md index 7bb68edf9..67efaf1d7 100644 --- a/docs/render-studio-ui.md +++ b/docs/render-studio-ui.md @@ -36,7 +36,7 @@ Changing or reloading a shot with an edited draft opens Save and continue / Disc The Appearance section provides an explicitly applied opaque body editor and the existing exact-target glass, clear-coat and four-channel map controls. Body color is sRGB; roughness, metallic fraction and optical IOR are not engineering constants. The reviewed target is revision/document checked. Existing face-specific appearances and physical material assignments remain separate. Temporary optical overrides retain their existing portability limitations and cannot masquerade as saved intent. -GPU illumination exposes analytic area/sun lighting and the shared environment controls. CPU controls expose directional and point/spot lights plus bounded rectangular emitters. CPU rectangle vectors are **full sides**, while GPU vectors are **half edges**; labels and native request schemas preserve the distinction. Sky zenith/horizon/ground are linear RGB. Display background is not an extra light source. +GPU illumination exposes analytic area/sun lighting and the shared environment controls. CPU controls expose directional and point/spot lights plus bounded rectangular emitters, with finite Sun and gradient Sky when explicit Indirect lighting is enabled. CPU rectangle vectors are **full sides**, while GPU vectors are **half edges**; labels and native request schemas preserve the distinction. Sky zenith/horizon/ground are linear RGB. Display background is not an extra light source. The Camera section edits the shared native camera via public commands, with millimeter position/distance, degree-displayed angles and explicit perspective FOV. Thin-lens controls remain GPU-specific. Navigation, camera fit and restore are not reimplemented as private mouse gestures. Unedited numeric values do not change merely because an editor is shown. diff --git a/docs/render-surface-emission.md b/docs/render-surface-emission.md index 9685283ce..fc5ab49a1 100644 --- a/docs/render-surface-emission.md +++ b/docs/render-surface-emission.md @@ -1,8 +1,10 @@ # Visible CPU surface emission (#1695) This transient option adds visible emission to the existing opaque CPU consumer. -The recovered source checkpoint was not compiled or run; its port requires its own -exact-revision tests, project gates and native PNG acceptance before publication. +At the recovery handoff the source checkpoint was not compiled or run. +Subsequent combined CPU renderer regressions have executed for linear radiance, +sidedness, zero identity, reflected hits, target refusal and work/cancellation. +Current combined engine/UI/native qualification and project gates remain pending. The transient `render.preflight` / `render.start` raytrace options accept: @@ -28,10 +30,12 @@ preserve baseline output. Explicit null, unknown fields and unsupported combinat refuse. The raster default and GPU preview gain no emission capability. Runtime inputs do not modify design storage, geometry, engineering properties or caches. -Emission does not add a sampled direct-light source for neighboring surfaces: no -emissive-triangle sampling or GI estimator is introduced. Existing selected specular -paths can reach an emitting surface. With other analytic/HDR lighting disabled and -no reflected emitter path, nonemitting surfaces remain dark. The primary background +Emission does not add a sampled direct-light source for neighboring surfaces. +Without optional [opaque path lighting](render-cpu-path.md), only existing selected +specular paths can reach an emitting surface; with other analytic/HDR lighting +disabled and no reflected emitter path, nonemitting surfaces remain dark. Explicit +path lighting can carry BSDF-sampled diffuse emission, without mesh-emitter +next-event sampling. The primary background retains its original display color. At most 32 emitter slots and 256 bytes per exact body name are admitted, including @@ -42,8 +46,8 @@ debit cumulative work and observe cancellation; no new scheduler or pool is used Tests written cover linear output/exposure, zero PNG equivalence, front/back normals, unlit neighbors, exact target refusal, duplicate/capacity/JSON bounds and metadata -accounting. They have not run yet. Full CI, wasm, real command/export acceptance and -review must follow on the real integrated revision before this is ready to merge. +accounting. The renderer cases have executed; current combined engine contracts, +full CI, wasm and real command/export/native acceptance remain separate gates. ## Integration with the current opaque consumer @@ -64,5 +68,5 @@ is integrated; programmatic preflight/start accept the same bounded typed reques The current-consumer port adds written regressions for AA/reflection divisors, combined directional/point/area lighting and emission reached by a reflected ray. -All newly ported tests and these three regressions require execution on the exact -candidate. Their presence is not a PASS or native acceptance claim. +The corresponding renderer integration regressions have executed on the combined +candidate. This does not qualify a visible emission editor or native acceptance. diff --git a/docs/render-surface-patterns.md b/docs/render-surface-patterns.md index e23b2226a..304fdaf35 100644 --- a/docs/render-surface-patterns.md +++ b/docs/render-surface-patterns.md @@ -69,10 +69,9 @@ shared surface; mirror/rough reflection through an emitting secondary hit; a rea and AA ordered-prefix/coverage/PNG/quantum checks. Existing malformed AA completion cases are retained and extended for surface state. -These are source contracts and written regressions. The recovered checkpoint and -this scratch port have not been compiled or executed in this review. Qualification -requires the exact candidate's formatting, target layout bound, render CPU ON/OFF -tests, engine/UI contracts, Clippy, wasm, actual full project CI, and any newly -exposed visible/native flow. Historical unrelated focal successes or full-CI -failures remain attached to their original source revisions; they do not qualify -this port. +At the recovery handoff these were source contracts and written regressions. +The combined CPU renderer has since executed analytic gradients, zero identity, +shared-surface lighting, ordered AA, binding and cancellation/work checks. Current +combined engine/UI contracts and visible/native flows still need qualification, +alongside default-feature/platform, Clippy, wasm and full-project gates. +Historical results remain attached to their original source revisions. diff --git a/docs/render-thin-lens.md b/docs/render-thin-lens.md index 378128b05..fd818f156 100644 --- a/docs/render-thin-lens.md +++ b/docs/render-thin-lens.md @@ -1,6 +1,12 @@ -# GPU depth of field +# Physical depth of field -`render.preflight` and `render.start` accept an optional runtime lens: +The Frame editor exposes the same physical thin lens for CPU ray tracing and GPU +path tracing. Lens changes save numerical intent in one undo step; they do not +move the view or replace the saved shot camera. Positive CPU aperture requires +explicit progressive sampling. A saved fixed CPU shot keeps its sampling choice +until the user adopts progressive sampling in Sampling. + +`render.preflight` and `render.start` accept the GPU runtime lens: ```json {"progressive":true,"samples":256, @@ -11,7 +17,20 @@ Use a perspective camera in `settings.camera` or the current view. Focus distanc is measured from the eye along the forward axis, to a plane perpendicular to that axis. It is not distance along each ray. Aperture is the physical radius in mm, not an f-number. Units follow the scene; a radius of 0.5 mm is small for a room and -large for a 3 mm object. No saved camera or render setup fields are added. +large for a 3 mm object. Saved CPU and GPU jobs both use `job.options.lens`; +the setup camera remains their single saved camera authority. The CPU runtime +form is nested inside `raytrace`, rather than the GPU top-level `lens`: + +```json +{"integrator":"raytrace", "settings":{"width":512,"height":512, + "camera":{"target":[0,0,0],"yaw":0,"pitch":0,"fov":0.7,"distance":120}}, "raytrace":{ + "progressive":{"samples_per_pixel":16,"seed":81}, "primary_samples":1, + "lens":{"aperture_radius_mm":0.5,"focus_distance_mm":120}}} +``` + +Saving, reopening and undoing lens intent work without an installed render host. +Neither a missing lens nor an explicitly saved zero aperture is inferred into an +active lens. Legacy fixed CPU and orthographic images keep their original path. A uniform-area circular aperture uses `r = radius * sqrt(u)` and `phi = 2*pi*v`. Each primary ray starts at that aperture point and aims at the pinhole ray's @@ -27,43 +46,39 @@ Radius is finite in [0, 1e7] mm and focus distance in [1e-6, 1e9] mm. Active len also require camera distance >= 1e-6 mm and tan(fov/2) in [1e-6, 1e6] to keep the f32 basis and focal point bounded. Existing image and scene caps still apply. The whole aperture must remain outside glass volumes, as must the pinhole camera. -No UI lens editor or dedicated CLI flags are included; use the shared render -commands through the control protocol, scripts or MCP. +CPU admission conservatively requires the sphere containing the entire circular +pupil to stay outside every certified closed glass box, including contact. This +can refuse a disk that would fit beside glass; it does not guess its starting +medium. Existing near-plane and per-path certification checks still apply. +CPU also checks the whole pupil's possible near/far ray interval against its +existing coordinate and distance envelope before starting transport. Extreme +physical lens/camera combinations that exceed that envelope refuse explicitly. +No general glass geometry or medium nesting is added. -Tests read rays from the production WGSL camera function and compare against -f64 geometric focus and defocus oracles, including an oblique rolled camera. +Tests read rays from the production GPU camera function and from the CPU camera +generator, comparing against analytical focus and defocus oracles with an oblique +rolled camera. CPU image tests also check actual defocused coverage, every +complete-pass prefix, worker-quanta independence, zero-aperture PNG/master/work +identity, cancellation and conservative glass admission. The CPU pupil sampler +uses a separate counter domain keyed by seed, pixel and absolute film ordinal; +it adds one charged continuation per camera sample, no extra rays or image +buffers. Existing job memory and cumulative work caps remain unchanged. At axial depth z, the displacement from a pinhole ray is `aperture_point * (1 - z/focus_distance)`: zero at focus, opposite-signed beyond it. Other tests cover strict admission, zero-aperture image identity and fixed-seed repeatability with an active lens. Glass evidence is an original procedural scene, with test-only uniform environment lighting, not a claim of HDRI implementation. -## CPU draft coordination +## Historical coordination -Read-only comparison: [CPU integration draft #1698](https://github.com/tangency-labs/solidcraft/pull/1698), -head `463a3e0daaa6b84f169ba5f8f215fba4642c194a` (2026-10-17). -No source from that draft is copied into this change. +The original GPU lens work compared the then-current CPU integration draft +[#1698](https://github.com/tangency-labs/solidcraft/pull/1698), head +`463a3e0daaa6b84f169ba5f8f215fba4642c194a` (2026-10-17), without copying its +source. That draft predates the current CPU lens and certified optical transport. +It is not the current capability contract. -- `raytrace/reflection.rs` uses the existing opaque surface's Schlick Fresnel, - GGX NDF sampling and solid-angle PDF `D(h)*n.h/(4*v.h)`. Our opaque lobe already - shares that surface oracle; the GPU mixes GGX and cosine samples with equal - probability. CPU sample sequences differ, so comparisons are statistical. -- The draft has no dielectric transport or thin-lens implementation to use as an - oracle. GPU glass retains the f64 Fresnel, Snell, slab and ball-lens checks. -- Both intersections use dominant-axis projection, closed edges and two-sided - triangles. CPU uses f64 with outward representable bounds; GPU uses f32 after - target rebasing and conservative epsilon bounds. CPU secondary rays use a - component-wise barycentric error bound and outward representable steps; GPU - still uses max(1e-5 mm, scene extent * 1e-7). This precision difference is - explicit; no CPU/GPU intersection identity is claimed. -- `lighting/environment_sampling.rs` defines +Z north, longitude atan2(y,x), - latitude acos(z), and inverse positive +Z rotation for lookup. The future GPU - environment adapter should use these conventions. CPU samples the sphere - uniformly with PDF 1/(4*pi); a GPU luminance CDF would use its own correctly - normalized solid-angle PDF and MIS. Neither is implemented by this lens change. -- CPU accepts only explicitly declared sRGB/D65 HDR primaries. GPU HDR input - must honor that boundary or provide a separately validated gamut conversion. - -The agreed shared dielectric fields are IOR, linear RGB extinction per mm and -thin-sheet thickness vs certified closed boundaries, identified by ordinal and name. -Persistence belongs to the shared contract follow-up, not this GPU executor slice. +CPU primary geometry uses f64 with outward representable bounds; GPU uses f32 +after target rebasing. Sample sequences and secondary-origin policies differ, +so cross-method pixel identity is not promised. Focus-plane geometry and shared +physical units are the analytical comparison. CPU HDR still requires declared +linear sRGB/D65 primaries; adding a lens does not add a gamut conversion or GI. diff --git a/docs/render-transmission.md b/docs/render-transmission.md index eb4690317..7238b799e 100644 --- a/docs/render-transmission.md +++ b/docs/render-transmission.md @@ -1,10 +1,11 @@ # Runtime dielectric overrides -The GPU executor uses the agreed shared CPU runtime contract from #1655 / -#1659, coordinated in Mailbox 9063, 9068 and 9075. Its wire adapter is isolated in -`crates/engine/src/cmd/render/transmission.rs` so the future shared type can replace it. -No document format number, migration, appearance field or persistent material -contract is added. The earlier experimental `pbr.transmission` proposal is removed. +The GPU runtime adapter uses the shared optical contract agreed in #1655. Its wire +adapter is isolated in `crates/engine/src/cmd/render/transmission.rs`. This raw +runtime API does not save an appearance or binding. The separate common Glass +editor and `RenderSetup.optics` provide stable saved assignments for CPU/GPU jobs; +see [workspace optics](render-workspace.md) and [renderer parity](render-parity.md). +The earlier experimental `pbr.transmission` proposal is removed. Pass this request to `render.preflight` or `render.start`: @@ -37,34 +38,41 @@ Boundary is one of: admitted and has no absorption, but retains the two-interface optical response. - `"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`: **GPU-only** extension for general closed sphere/lens meshes. - This is not a claim that the current CPU certificate admits those shapes. +- `"closed_mesh"` with `"thickness_mm":0`: general closed meshes under the selected + producer's certificate. GPU uses its captured-f32 certificate. Explicit CPU Path + uses the distinct exact-f64 [general Glass certificate](render-cpu-general-glass.md). + CPU without Path retains the strict box subset; the shared enum does not widen it. -Preparation matches topology representatives within 1e-6 mm Euclidean distance, +The GPU certificate matches topology representatives within 1e-6 mm Euclidean distance, searching neighboring spatial cells so a rounding boundary cannot split a valid CAD seam. It does not alter uploaded geometry or join chains beyond a representative's tolerance. Weld scratch is bounded and budgeted for the largest closed dielectric body being validated; opaque and thin-sheet bodies allocate none of it. Preparation requires paired opposite edges, exactly one edge-connected shell, positive outward volume, and requires -one homogeneous IOR/medium over a closed body's faces. Nested or overlapping -closed media are refused conservatively: dielectric body AABBs must be disjoint -when either body is closed. This can reject disjoint curved shapes whose boxes -overlap. Thin sheets can overlap each other's bounds. Camera and the entire lens -aperture must start outside volumes; unmatched exits fail without a published image. +one homogeneous IOR/medium over a closed body's faces. Without explicit GPU nested-media mode, selected closed-body bounds must be +disjoint. This conservative rule can reject separated curved shapes whose boxes +overlap. Explicit nested mode uses the hierarchy/origin policy in +[closed-glass boundaries](render-glass-boundaries.md); touching/overlapping media +are not repaired. Thin sheets can overlap each other's bounds. Default mode +requires outside camera/pupil origins. Unclassifiable crossings use the existing +medium diagnostics and failure policy. Multiple shells in one body are refused with a connected-component check and a negative two-shell fixture. Self-intersection of an otherwise oriented manifold is **not certified**; such geometry is outside the supported input contract and may not be detected. Edge counts and signed volume are not a proof of embedding. The hole, inward-winding, disconnected-shell, nested/overlapping bounds and -camera-inside refusal paths have negative fixtures. GPU preflight reports -`dielectric_boundaries: ["thin_sheet","closed_box","closed_mesh"]`; CPU preflight -reports `["thin_sheet","closed_box"]` when explicit runtime dielectric overrides -are present, and an empty list otherwise. CPU certification and finite-depth -transport have the stricter [bounded CPU dielectric preview](render-raytrace-dielectrics.md) -contract. The generic Refraction flag alone does not describe this policy. +camera-inside refusal paths have negative fixtures. GPU accepts the three named boundaries under that certificate. CPU without Path +uses the stricter [bounded dielectric preview](render-raytrace-dielectrics.md); +CPU Path uses [general Glass](render-cpu-general-glass.md). Preflight metadata must +describe the selected request, not infer arbitrary geometry from a generic +Refraction flag. The Glass follow-up reports the actual CPU Path boundaries. +Each strict prepared job carries its own certificate into the renderer; a +separate Start prepares fresh captured intent. Its qualification is separate +from historical CI7 in [renderer parity](render-parity.md). -Raster previews retain independently saved scalar opacity. CPU raytrace accepts -only the bounded dielectric overrides described above; lens controls remain GPU-only. +Raster previews retain independently saved scalar opacity. CPU ray tracing has +its own conditional optical contract and [physical lens](render-thin-lens.md); +these controls are not inferred from the GPU runtime adapter. CPU raytrace still requires surface opacity one, including for dielectric bodies. Scalar alpha is never inferred to mean physical glass. Old opaque PBR appearances still require opacity one. Unknown keys, nonfinite inputs, invalid ordinals and @@ -78,7 +86,8 @@ 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) 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 per-path stack storage is retained, but nested-entry events are errors. +The existing bounded per-path stack is retained. Default mode rejects nested +entries; explicit nested mode requires the separate containment certificate. `crates/render/src/dielectric_oracle_tests.rs` is an original self-contained f64 fixture module prepared for sharing with #1659: normal/oblique/Brewster s/p, diff --git a/docs/render-vndf-prototype.md b/docs/render-vndf-prototype.md index 741cd8511..7d39f695e 100644 --- a/docs/render-vndf-prototype.md +++ b/docs/render-vndf-prototype.md @@ -1,8 +1,9 @@ # Matched GGX visible-normal proposal (#1658) -Recovered VNDF source port, connected to the CPU image consumer. The tests are -written but have not run on this combined CPU/GPU2 revision. No measured variance -reduction or visual acceptance follows from this document. The exact integration +Recovered VNDF source port, connected to the CPU image consumer. The combined +CPU renderer has executed its PDF/moment/null-support, visible-sampler and actual +image-consumer regressions. No measured variance reduction or native visual +acceptance follows from these numerical results. The exact integration baseline and recovered source identity are recorded in [advanced CPU integration](render-cpu-advanced-integration.md). @@ -104,13 +105,13 @@ The current planar bridge rebuilds its frame from the oriented geometric normal and captured visual tangent; that receiver behavior is preserved. Its existing exact-equality regression now calls the visible-normal reference API, retaining every equality/rotation/reciprocity assertion. Projected-NDF controls remain -explicit and unchanged. All fifteen VNDF tests are WRITTEN, NOT RUN. +explicit and unchanged. The corresponding renderer VNDF regressions have executed. -Independent numerical review and actual execution must verify the cap measure/Jacobian, Smith -separability, no accidental NDF production path, geometric rejection, extreme -arithmetic and null accounting. Future separately allocated gates must compile -default/feature modes, run old controls and new VNDF tests, strict Clippy, wasm -and required full CI on the final receiver. Only then compare actual matched +Executed numerical checks cover the cap measure/Jacobian, Smith separability, +production visible-sampler path, geometric rejection, extreme arithmetic and null +accounting. Remaining gates include current combined workflow acceptance, +default/platform checks, strict Clippy, wasm and required full CI on the final +receiver. Only then compare actual matched images and measure error/work with appropriate references. The foundation publication is not held hostage by this unqualified follow-up. diff --git a/docs/render-workspace.md b/docs/render-workspace.md index b9092f5b4..d0fe5632f 100644 --- a/docs/render-workspace.md +++ b/docs/render-workspace.md @@ -1,6 +1,6 @@ # Integrated Render workspace (R3) -The native image panel offers CPU raster, optional CPU ray tracing and +The native image panel offers CPU raster for schematic output, optional CPU ray tracing and [GPU path tracing](render-path.md) as explicit image methods. All three methods can be edited and saved offline. Check and Start are enabled only when the selected method has an installed supporting host; an unavailable method never falls back. @@ -12,7 +12,46 @@ the asynchronous protocol, image limits, captured revisions and PNG export. The Choose **Render** in the workspace switcher after finishing a modelling operation. The current integrated GPU renderer shows a separate product scene. Return to Design restores its camera, projection preference and existing viewport drawing policy. -The live product preview remains independent of the selected image method. +New native setups select CPU ray tracing with progressive sampling when the installed +host supports it. Existing saved final settings keep their interpretation. +Preferences > Graphics > **Use previous Render image defaults** restores the previous manual workflow. + +A first entry with an active saved shot restores its authored camera when that camera +is more than the untouched default. An uncomposed setup still fits the current product. +Leaving Render remembers its transient camera separately from Design, so returning +preserves framing and a saved lens stays paired with its perspective projection. +Clicking a shot in the tree or Shots strip activates its numerical settings and +complete saved camera, including an active shot when its camera differs. Unsaved +edits retain Save/Discard/Keep. The standalone editor-selection command only focuses +its editor; numerical reloads, saves and Undo do not navigate. The compatibility preference keeps +the former camera-neutral thumbnail and entry-refit behaviour. + +## Live image feedback + +Render automatically computes a separate live image after visual edits settle for +200 ms. Appearance, lighting, camera, visibility and image settings invalidate the +capture; selecting an editor alone does not. The selected ray-traced method is retained. +The stage bar identifies the live resolution and accepted/current sample count and +offers Pause/Resume (`view.render_live {paused: true|false}`). Live resolution follows +the active output frame inside the free product canvas, with a longest edge of +512 pixels. Common output ratios use exact integer multiples; otherwise the live +image uses the nearest bounded pixel dimensions and picking uses that captured +aspect. Final output size and saved sampling settings are unchanged. Invalid +authored dimensions/sampling are refused before constructing the small live copy. An older image is marked as updating and cannot +be used to pick geometry against a different projection. + +Automatic images belong to an isolated scratch session. They do not enter retained +results or replace the completed image selected for Copy, Export or Regrade. An +explicit Render action displays its progressing image. If live capture or rendering +is still releasing resources, the captured final request waits for cleanup; a changed +source cancels that pending request instead of silently rendering different settings. + +CPU progressive and GPU jobs publish each complete nonfinal pass. Adaptive GPU +feedback distinguishes pilot passes from production iterations; each production +pixel has its own budget, and pilots are excluded from the final image. Fast +passes can coalesce between screen repaints. Unsupported combinations are not silently +converted to fixed sampling. Unsupported CPU optical combinations also retain their +settings and show their reason. These remain open parts of complete CPU/GPU parity. ## Retained comparisons and all-shot rendering @@ -51,7 +90,7 @@ above the Render label and Workspace caption. The header is 36 pt; the remaining 52 pt contains the tools, centred vertically below a 1 pt divider. Numbered **Look**, **Light**, **Frame** and **Output** chips run `view.render_stage {stage: look|light|frame|output}`. The selection belongs to the open document tab's view state; it is not saved in the design. Opening a stage never -applies or saves settings or starts an image job. It focuses the existing Inspector +applies or saves settings or submits a final image job. It focuses the existing Inspector page, while every Inspector page and registered Render command remains reachable. The headless command validates and echoes the request without changing the document. @@ -93,7 +132,11 @@ Apply prepares a review without changing the method or saved settings. The shared `ui_kit::ReviewAndApply` dialog presents a resource card, Replaces/Kept, variant controls and explicit acknowledgement before applying. Studio, rig fit, environment, ground/stage, physical plan, fixed quality budget and uniform/spatial -maps use this composition. A captured review expires when the document, revision, +maps use this composition. Canonical Draft, Balanced and High quality chips instead +apply their listed fixed GPU budget as one reversible numerical edit. Sampling shows +size, samples, depth, seed and noise reduction; the chip hover lists all three budgets. +Other image settings and the saved/live cameras are kept. Library specifications +retain the acknowledged review. A captured review expires when the document, revision, shot, method or settings change. Rig fitting offers centre, extent, captured bounds and emitters-only projection. Quality review reports projected dimensions, samples, depth and omissions; `render.quality.prepare` remains reachable through command @@ -130,19 +173,29 @@ edits or evaluates the design, moves the camera or creates an undo step. **CPU raster** produces the existing preview PNG with approximate transparency. **CPU ray tracing** requires a native worker and the `raytrace-cpu` build feature. -Its panel offers **Single image** with 1, 4 or 16 spatial samples per pixel, or -**CPU progressive** with 1–64 accumulated samples and a separate seed. Both use +Fresh native setups use **CPU progressive** with sample and seed controls. The +normal UI presents progressive sampling as the active mode; a loaded fixed +setup keeps its existing 1, 4 or 16 spatial samples until the user explicitly +adopts progressive sampling. The compatibility preference also exposes the old +Single image / Progressive selector. Sample and image limits follow the selected +[CPU resource profile](render-cpu-resource-profiles.md). Both routes use Neutral / Warm and cool / Key and rim lighting, cast shadows and exposure from -−16 to +16 EV. Progressive sampling has a 1,048,576-pixel and 16,777,216 pixel × sample -limit; the UI proposes a smaller size only as an explicit action. It requires an -opaque background; the panel explains the incompatibility and lets the user clear -Transparent background. Additional collapsible sections expose body reflections, +−16 to +16 EV. The UI proposes a smaller size only as an explicit action. Transparent +background exports straight-alpha edge coverage for both sampling modes; body and +face opacity still require 100%. Bloom, backdrop and photographic effects require +opaque output and remain explicit refusals. Additional collapsible sections expose body reflections, captured HDR or constant environments, directional lights and point lights. Reflection bindings require explicit confirmation after a document change; reusing a name cannot redirect them to another body. Check and the current job display their separate HDR capture metadata. See [CPU workspace controls](render-cpu-workspace.md) for units, -limits and the immutable capture contract. CPU glass, emission, surface effects, -anisotropy, area lights and spot cones remain API capabilities without panel editors. +limits and the immutable capture contract. The common Glass editor supports stable +saved targets. Without Indirect lighting, CPU Glass uses the certified sheet/box +subset. With Indirect lighting, [general Glass](render-cpu-general-glass.md) adds +certified closed meshes under its geometry, transmission and scattering restrictions. +The Lights editor exposes point/spot and rectangular lights. Emission, surface effects +and anisotropy retain their bounded API contracts. Indirect lighting has its own +Sampling controls and validates saved or temporary optical bindings against the +selected transport; unsupported combinations refuse without removing the bindings. **GPU path tracing** preserves asynchronous shader preparation and its timing display. Its independent image device requires Vulkan; the live viewport may use another backend. @@ -153,17 +206,19 @@ maximum path depth (1–16) and random seed. Exposure (−32 to +32 EV) lives in exposure field controls the selected image method. Switching methods retains their local numeric drafts while submitting and saving only the active method. Reloading or choosing another setup replaces those drafts with the saved numeric intent. -The live product preview keeps its fixed studio response and does not apply image -exposure, environments, lens or material overrides. +Automatic ray-traced live images use the captured image exposure, environment, lens and +supported material effects at interactive resolution. The integrated direct-light preview +is the fallback while no live image is available, or for Raster and the compatibility workflow. Effects > Tone exposes Reinhard / ACES fitted tone mapping. Sampling > Path tracing -owns optional final edge-aware denoising; Shot owns thin-lens depth of field. Positive aperture +owns optional edge-aware noise reduction for progressive and final display images; +Shot owns thin-lens depth of field. Positive aperture requires a perspective product camera. Denoising preserves raw accumulation but can -soften detail; glass and sharp specular first hits bypass its final spatial filter. +soften detail; glass and sharp specular first hits bypass its spatial filter. The Environment Browser row opens the Environment editor. The legacy Environment and Background pages use that same editor, with five sections in order: Source, -Orientation and strength, Backdrop, Ground and stage, and Atmosphere (GPU). +Orientation and strength, Backdrop, Ground and stage, and Atmosphere (CPU/GPU). Source offers None, Artistic sky, HDR file and embedded HDR for GPU, or None, Constant and HDR for CPU. Change opens the Environments scope of Studios and environments. Embedded HDR shows its name, kind and saved-in-design status; sky @@ -189,9 +244,13 @@ shared **Remove the saved stage?** confirmation. The fields expose extent margin clearance gap and linear reflectance, followed by the saved panel count. Atmosphere edits the bounded participating medium: enable, world bounds in mm, extinction, scattering albedo and phase. The transitional Aging page's airborne -section calls this same function. CPU and raster show the controls faded with -the GPU requirement. These controls use existing render state and commands; -opening the editor never changes the design or renderer. +section calls this same function. CPU supports Atmosphere with explicit +progressive Indirect lighting. Positive extinction cannot combine with Glass, +selected-medium subsurface scattering or surface Denoise; unsupported combinations +keep their authored values and explain the refusal. Raster shows the controls +faded with the raytrace requirement. These controls use existing render state and +commands; opening the editor never changes the design or renderer. See +[CPU Atmosphere](render-cpu-volume.md) for its bounds and compatibility conditions. The panel distinguishes a pending file, a checked file and **HDR saved inside this design**. It shows dimensions, declared colour primaries and intensity; the source @@ -213,7 +272,7 @@ The look card's source tag opens the inheritance chain. Reset restores the picke target's values from when it was opened; Save to library uses the existing design library export flow. -Glass and absorption (GPU), Clear coat (GPU), Maps (GPU), Saved with this shot, +Glass and absorption (CPU/GPU), Clear coat (CPU/GPU), built-in Maps (CPU/GPU), Saved with this shot, and Reflections (CPU) follow in that order and start collapsed. Unsupported methods remain visible with an explanation; opening a section never changes the renderer. Optical bindings currently target one whole visible body, so face, @@ -230,27 +289,46 @@ compute absorption per millimetre via -ln(T) / distance. Glass exposes boundary, IOR, thickness, RGB absorption, straight shadow transmission and closed-solid interior scattering. Thickness is disabled for closed glass, which uses geometric distance. Glass cannot share a body with coat or maps. Full topology, orientation, -overlap and optical-boundary checks run during GPU preparation; Check does not -certify those properties. +overlap and optical-boundary checks use the selected producer. CPU without +Indirect lighting keeps its strict sheet/axis-aligned-box subset. Explicit CPU +Path supports certified general closed meshes, nested media and selected-medium +scattering; GPU has its own certificate and nested-mode policy. The common +controls never bypass those geometry or combination checks. See +[renderer parity](render-parity.md) for historical qualification and this change's Glass follow-up. -Clear coat retains weight, roughness and IOR. Maps retain the bounded PNG/JPEG -picker flow for base colour, normal, metallic and roughness images, world-space -origin and U/V repeat vectors, normal strength, V orientation and base replacement. -The backend's map-size, encoded-byte, repeat and assignment limits still apply. -File-picker completion checks the original document, revision and body identity. +Clear coat retains weight, roughness and IOR in common CPU/GPU saved bindings. +Built-in surfaces can save base-colour, normal, metallic and roughness maps for +both methods, with stable target identity and a definition-local frame. External +PNG/JPEG picker maps remain GPU-only temporary inputs; portable external-map +import is separate unqualified work. The map-size, encoded-byte, repeat and +assignment limits still apply. File-picker completion checks the original +document, revision and body identity. -These local overrides are temporary on the document tab. Save these optics uses -render.optics.bind to save physical glass with the shot; replacement requires the -explicit Replace this body's saved optics checkbox. Coat and local image maps -remain temporary, and the save action explains that limit. Remove saved opens the +Local edits remain prospective on the document tab until saved. Save these optics +uses render.optics.bind; replacing different saved Glass requires the explicit +Replace this body's saved optics checkbox. Save coat to shot uses the separate +stable coat binding. Built-in surface bindings are also saved; external image +file mappings remain temporary. Remove saved opens the shared Remove saved optics? confirmation before render.optics.unbind; stale confirmations cannot affect a changed document. Saved authored surface bindings remain manageable in Saved with this shot. Reflections retains this body's Off/Mirror/Rough CPU binding and explicit target confirmation. -Active GPU overrides still cause Check/Start to refuse a CPU request. Both buttons -submit the same freshly validated runtime parameters and the engine captures file -contents at that boundary. +CPU uses the common IOR/Beer controls, while transport choices remain explicit. +Without Path, general boundaries, scattering and transmitted shadows refuse. +With Path, certified general Glass and thin transmitted shadows are supported; +closed transmitted shadows and external Atmosphere with Glass still refuse. +Coat/maps cannot share a Glass target, but unrelated opaque targets keep their +supported effects. Check and Start each use fresh captured intent. Strict +preparation performs the full general-Glass certificate and carries its proof +into that prepared job's renderer. A separate Render click prepares a fresh +capture; it does not reuse an earlier Check proof. +Saved target A and prospective target B merge as stable assignments; checked file +HDR capture preserves them on CPU and GPU without an ordinal-override detour. +Unsupported combinations refuse and no implicit Save occurs. See +[PR #11087](https://github.com/tangency-labs/solidcraft/pull/11087) for this +follow-up's exact source and qualification. Historical CI7 and opaque native +results remain separate. Check and Start build the same request from the current product camera, size and selected method, including when Render Result is open. Every click revalidates host @@ -324,11 +402,13 @@ for each open document, and loading a setup preserves completed images and resul | Active method | Saved numeric intent | | --- | --- | | CPU raster | Transparency, with zero exposure | -| CPU ray tracing | Single-image AA or progressive SPP/seed, preset or custom directional lights, point/spot lights, area lights and their samples/seed, shadows, constant RGB environment or embedded HDR with rotation/intensity/samples, setup exposure | +| CPU ray tracing | Transparency, fixed AA or progressive SPP/seed, resource profile, optional opaque path depth, guided noise reduction, physical lens, tone map/finishing/backdrop and raw EXR retention, certified saved optical bindings, preset or custom directional lights, point/spot and area lights with samples/seed, shadows, constant RGB environment or embedded HDR with rotation/intensity/samples, setup exposure | | GPU path tracing | Transparency, samples/depth/seed, tone map, denoise, lens, RGB studio lighting/sun/area lights, procedural sky or embedded HDR with rotation/intensity/explicit colour assumption, setup exposure | -The CPU panel preserves existing area-light and spot-cone fields even though it does -not yet edit every field. Opening a GPU setup retains non-power-of-two sample counts, +CPU path lighting can combine with certified optical bindings under the +[general Glass restrictions](render-cpu-general-glass.md). Incompatible saved +intent still refuses before HDR IO or scene capture. Opening a GPU +setup retains non-power-of-two sample counts, RGB environment values, exact sky gradients and radians. Explicit empty light lists, black environments and absent settings remain distinct. The only exposure authority is `RenderSetup.exposure_ev`: CPU requests lower it to their raytrace options with zero @@ -345,10 +425,12 @@ payload. The engine limits each source to 16 MiB and the design to 64 resources/ Check and Start use the same complete typed setup and then perform normal host, scene and capture admission. Temporary bindings can still use an embedded HDR through the -runtime resource selector. GPU maps and all body bindings, including disabled -assignments, cannot yet be saved as a complete job. -The panel explains the limitation and refuses Save before changing the document. -Those inputs can still execute through the existing transient request route. Older +runtime resource selector. Saved stable Glass, clear-coat and built-in surface +bindings travel with complete CPU/GPU jobs. Temporary runtime body bindings, +including disabled assignments and external GPU image maps, still cannot be saved +by full-job Save; use the explicit portable binding actions for supported inputs. +The panel explains those limitations and refuses unsupported Save before changing +the document. Temporary inputs can still execute through the transient request route. Older setups with nondefault legacy environment rotation/intensity are also retained and refused for full-job saving until explicitly converted; their values are never erased. @@ -360,10 +442,12 @@ Orbit around, zoom to the cursor, the SpaceMouse, the middle double-click, F6 an view or navigation cube all work and **Fit Product** frames visible product bodies without including sketches or selection. -While Frame shows the picture's frame, **Fit Product** and the fit on entering Render keep -the product inside that frame rather than the viewport, so a picture taller than wide moves -the camera back. The fit on entering waits for the saved setup to load, so it frames that -setup's aspect, not the draft it replaces. `render.camera.fit` takes the picture's `aspect` +In the normal workflow, **Fit Product**, entry fit, product drawing, navigation, +live capture and picking always use the active output frame inside the free canvas. +Selecting Shot, Sampling, Effects or Output changes neither its camera nor aspect; +a portrait output therefore stays portrait in every editor. Entry fit waits for +the saved setup to load. The previous Frame-only projection policy remains behind +**Use previous Render image defaults**. `render.camera.fit` takes the picture's `aspect` (width over height, 0.000001 to 1000000, default 1) and refuses a fit whose camera would be out of range, leaving the current camera as it was. @@ -372,7 +456,8 @@ and unsupported modes remain saved intent: the strict resolver reports the unsup viewport request. **Use Integrated Preview** is an explicit draft change, never an automatic fallback. The method selector describes the desired image execution independently of the installed host. It does not claim support for a saved final-mode or external-engine -preference. Saved image settings do not change the fixed live product preview. +preference. The integrated schematic fallback keeps its existing drawing policy; +its normal-workflow framing still follows the active output aspect. ## Host capabilities and resources @@ -510,8 +595,11 @@ Frame's floating panel offers five aspect presets and Custom, plus composition g Clicking a preset saves its output dimensions in one undo step; Custom preserves dimensions. `view.render_frame` independently validates and echoes transient aspect/guide preferences; headless calls never edit a design. Guides are per-document UI state, never saved in design JSON. -The frame and its size/lens chips appear only in Frame or the Shot editor. Product preview, -navigation and picking use the fitted frame aspect; image jobs and the Result canvas omit guides. +Composition guides and their size/lens chips appear only in Frame or the Shot editor. +Their transient/selected-shot aspect is independent of the active output camera; +hiding or changing those guides never changes normal-workflow product framing, +live pixels or picking. Image jobs and the Result canvas omit guides. Retained +results and comparison images continue to use their captured dimensions. The shared Browser lists Environment (with its source), Lights, saved Shots, Objects and Output (with image dimensions and format). Shots **+** opens the @@ -564,7 +652,7 @@ Output, each with a summary and its own editor. Sampling owns Quality, GPU Path tracing, Adaptive, Glass transport and CPU ray tracing. Method-specific controls stay visible and faded with their reason on other methods. Effects owns Tone, Creative looks, Lens effects, Finishing and Regrade, in that order; its controls -need GPU path tracing. Effect edits patch the saved job with `render.settings.set`; +support CPU ray tracing and GPU path tracing. Effect edits patch the saved job with `render.settings.set`; opening an editor never saves or switches methods. Check owns the preflight notes, This request, Renderers and collapsed Under the hood diagnostics. The legacy Effects, Output and Diagnostics pages call the same editors. @@ -573,7 +661,15 @@ The stage bar's Check chip and Output's note count open Check. Check now runs th read-only `render.preflight` without admitting a job. Notes offer links to their owning editor. Copy report and diagnostic JSON use `render.preflight.copy` and the platform clipboard queue; headless calls only validate and echo bounded text. -Named quality presets and EXR export remain faded with their existing reasons. +GPU Draft, Balanced and High apply a fresh canonical fixed budget in one undo step. +Sampling shows resolution, samples, path depth, seed and noise reduction; hovering +the chips lists all three budgets. Imported library specifications keep their +acknowledged review. The saved camera and other effects stay +intact; an incompatible combination leaves the draft unchanged. The highlight +follows the actual budget fields and returns to Custom after an edit. These GPU +budgets remain disabled on CPU and Raster. CPU keeps its own sample controls; +Raster remains the schematic method. EXR export is +available only for the selected completed image with an actual retained master. Destination selection uses the completed-image export picker. The pinned Render Image / All shots footer starts the active setup or queues all saved shots through `render.batch`; opening the editor never starts a job. @@ -583,3 +679,14 @@ pill with Cancel. The result viewer retains Copy, export, close, Fit/100% and sh pan/zoom. R starts the active setup; Escape closes the image without cancelling its job. Preferences › Graphics offers “Use previous Render preview geometry budget” (`render_previous_geometry_budget`). It restores the fixed limit (512 MiB on 64-bit desktop, 128 MiB elsewhere); by default, desktop previews use the device-based budget. Changes apply to the next preview frame. + + +CPU Glass uses the common body editor and stable saved optical targets. Fixed +jobs retain the strict sheet/axis-aligned-box subset and refuse scattering or +transmitted shadows. Explicit Indirect lighting selects the certified general +Glass path, including its conditional thin-shadow and scattering contracts. +Reopened controls preserve the actual saved numbers. Edits are prospective; +Save/replacement/Remove own document changes. Unchanged hydration and Discard do +not save or start a final job. The multi-target merge in this change does not +imply an automatic Save. See [general Glass](render-cpu-general-glass.md) and +[the qualification record](render-parity.md#qualification). diff --git a/skills/solidcraft-ui-text/SKILL.md b/skills/solidcraft-ui-text/SKILL.md index 29835dccf..a39c2bf4a 100644 --- a/skills/solidcraft-ui-text/SKILL.md +++ b/skills/solidcraft-ui-text/SKILL.md @@ -12,7 +12,7 @@ SolidCraft embeds its translations and works offline. The long form is `docs/loc 2. Use `app.tr("ui.some_id")` for static messages and `Locale::format` for whole sentences with named placeholders. Translate the whole sentence, punctuation included, so a translator can reorder arguments. Use stable ids directly for new messages, not the English-label adapter (`app.tr_label`), which exists for older tables. 3. Command labels live under `cmd.`; `cargo xtask i18n --add-missing` writes the ones that are missing into `en.json`. 4. Add the UK spelling to `assets/locales/en-GB.json` when the US spelling differs (Centre, Colour, Licence, ...). That file holds only the differing messages. -5. A new label needs `en`, `ja`, `zh`, `de` and `ko`. The other catalogs are partial and fall back to English; `cargo xtask i18n` reports their gaps without failing, and `every_complete_catalog_carries_every_english_message` fails a missing `ja` or `zh` entry. +5. New labels need `en`, `ar`, `he`, `ja`, `vi`, `zh`, `de` and `ko`. The complete catalogs (`ar`, `he`, `ja`, `vi`, `zh`) require every English key; others fall back to English. `cargo xtask i18n` reports gaps; tests reject gaps in complete catalogs. 6. Run `cargo xtask lists --fix` before committing, then `cargo xtask i18n`. ## Sorted catalogs diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 93eb55c9d..197b46cbe 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -153,6 +153,8 @@ render.camera.fit rendering: images, cameras, stages render.camera.get rendering: images, cameras, stages render.camera.set rendering: images, cameras, stages render.cancel rendering: images, cameras, stages +render.coat.bind render settings only: crates/engine/src/cmd/render/clear_coat.rs::stable_tests::stable_coats_save_reopen_replace_and_undo_offline_for_cpu_and_gpu_without_changing_sources +render.coat.unbind render settings only: crates/engine/src/cmd/render/clear_coat.rs::stable_tests::stable_coats_save_reopen_replace_and_undo_offline_for_cpu_and_gpu_without_changing_sources render.compare rendering: images, cameras, stages render.compare.divider rendering: images, cameras, stages render.effects.describe rendering: images, cameras, stages @@ -345,6 +347,7 @@ view.render_dock the view: camera, layout, display view.render_focus the view: camera, layout, display view.render_frame the view: camera, layout, display view.render_inspector the view: camera, layout, display +view.render_live live-image pause state only: crates/ui-egui/src/render_workspace_tests.rs::live_edits_coalesce_and_pause_drains_late_capture_without_document_or_result_changes view.render_select the view: camera, layout, display view.render_stage the view: camera, layout, display view.ribbon_tabs_only the view: camera, layout, display diff --git a/vendor/egui-wgpu/src/renderer.rs b/vendor/egui-wgpu/src/renderer.rs index 41d96e4c8..01a85315b 100644 --- a/vendor/egui-wgpu/src/renderer.rs +++ b/vendor/egui-wgpu/src/renderer.rs @@ -29,6 +29,11 @@ pub type CallbackResources = type_map::TypeMap; pub struct Callback(Box); impl Callback { + /// Inspect the concrete callback without preparing or painting GPU work. + pub fn downcast_ref(&self) -> Option<&T> { + (self.0.as_ref() as &dyn std::any::Any).downcast_ref() + } + /// Creates a new [`epaint::PaintCallback`] from a callback trait instance. pub fn new_paint_callback( rect: epaint::emath::Rect, @@ -85,7 +90,7 @@ impl Callback { /// # Example /// /// See the [`custom3d_wgpu`](https://github.com/emilk/egui/blob/main/crates/egui_demo_app/src/apps/custom3d_wgpu.rs) demo source for a detailed usage example. -pub trait CallbackTrait: Send + Sync { +pub trait CallbackTrait: Send + Sync + std::any::Any { fn prepare( &self, _device: &wgpu::Device,