Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
Sky portals: Solari samples the sky through a room's openings as a light
shinyobjectzb45cbe40857e
diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rsindex 2e7fba61..58537cfc 100644--- a/runtime/look/src/camera.rs+++ b/runtime/look/src/camera.rs@@ -30,6 +30,20 @@ pub fn env_shown(sent: Option<&V>, cam: &mut BTreeMap<String, V>) {/// An <Environment>'s source in env_srcs: its panorama's path, or for <Environment room> `room:` and its blur (three's/// RoomEnvironment, which raea-sys-environment's room.rs makes, #165).+/// <Environment portals>' openings, each four corners in order round it, as a corner and its two neighbours+fn portal_corners(list: &[Value]) -> Vec<[[f64; 3]; 3]> {+ let point = |p: &Value| -> Option<[f64; 3]> {+ let a = p.as_array()?;+ Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?])+ };+ list.iter()+ .filter_map(|q| {+ let c: Vec<[f64; 3]> = q.as_array()?.iter().filter_map(point).collect();+ (c.len() == 4).then(|| [c[0], c[1], c[3]])+ })+ .collect()+}+pub fn env_src(e: &Item) -> Option<String> {if e.props.get("room") == Some(&Value::Bool(true)) {return Some(format!("room:{}", n(&e.props, "blur", 0.0)));@@ -182,6 +196,10 @@ fn lit(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, id: &sif sky.iter().any(|s| *s > 0.0) {column(p, row, id, "sky_k", &sky);}+ // its sky portals (<Environment portals>), the first frame's: each a corner and its two neighbours+ if let Some(list) = envs.iter().flatten().find_map(|e| e.props.get("portals")).and_then(Value::as_array) {+ row.insert("env_portals".into(), V::S(serde_json::to_string(&portal_corners(list)).unwrap_or_default()));+ }}// a <Grade>'s colour fringes, keyed: each frame's own (0 where a frame has none), so a glitch's spike draws on its// frames and a frame is the same whichever others the render holds (it was the first frame's, for every frame)diff --git a/sdk/render/src/3d/effects.tsx b/sdk/render/src/3d/effects.tsxindex ddef1d66..53db8f8c 100644--- a/sdk/render/src/3d/effects.tsx+++ b/sdk/render/src/3d/effects.tsx@@ -265,6 +265,27 @@ export interface EnvironmentProps {background?: boolean;/** the sky's brightness, when it should differ from the light's (`intensity` by default) */backgroundIntensity?: number;+ /** the openings the sky lights a room through (a skylight, a window), each its four corners in order round it, in+ * metres (a rectangle or any parallelogram). Traced lighting (Solari, the path tracer) samples the sky through each+ * as it samples a lamp, so a room lit through a small opening gets that light smooth and whole, where rays bounced at+ * random find it too rarely for the denoiser to keep (photo 5's hall: half its floor's sky light). Light passes both+ * ways; up to 8; the first frame's hold. Raster lighting doesn't read them */+ portals?: [number, number, number][][];+}++/** an <Environment>'s portals: each four corners, a parallelogram with some area */+function checkPortals(portals: unknown) {+ if (portals === undefined) return;+ const bad = (why: string) => new TypeError(`Environment: portals ${why}, got ${JSON.stringify(portals)}`);+ if (!Array.isArray(portals) || portals.length > 8) throw bad("is a list of up to 8 openings");+ for (const q of portals) {+ if (!(Array.isArray(q) && q.length === 4 && q.every((p) => Array.isArray(p) && p.length === 3 && p.every((x) => typeof x === "number" && Number.isFinite(x))))) throw bad("are each four corners [x, y, z]");+ const [a, b, c, d] = q as [number, number, number][];+ const u = b.map((x, i) => x - a[i]), v = d.map((x, i) => x - a[i]);+ const edge = Math.max(Math.hypot(...u), Math.hypot(...v));+ if (!(edge > 0) || Math.hypot(...a.map((x, i) => x + c[i] - b[i] - d[i])) > 0.01 * edge) throw bad("are each a parallelogram, corners in order round it");+ if (Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) < 1e-6) throw bad("each have some area");+ }}/** Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal@@ -288,6 +309,7 @@ export function Environment(props: EnvironmentProps) {if (v !== undefined && !(typeof v === "number" && v >= 0 && Number.isFinite(v))) throw new RangeError(`Environment: ${k} must be 0 or more, got ${v}`);}if (props.rotation !== undefined && !(typeof props.rotation === "number" && Number.isFinite(props.rotation))) throw new RangeError(`Environment: rotation must be a number of radians, got ${props.rotation}`);+ checkPortals(props.portals);return node3d("Environment", props as unknown as Record<string, unknown>);}diff --git a/systems/environment/src/lib.rs b/systems/environment/src/lib.rsindex 3d3e20b6..9a8da5f5 100644--- a/systems/environment/src/lib.rs+++ b/systems/environment/src/lib.rs@@ -14,7 +14,8 @@//! Camera columns: env_srcs (a JSON list of panorama paths, or `room:SIGMA` for three's RoomEnvironment, which room.rs//! makes), env_i (which one this frame, -1 none; keyed), env_k (its//! intensity in cd/m²; keyed), env_rot (a turn about +Y, radians; keyed), sky_k (the sky's brightness, 0 no sky;-//! keyed).+//! keyed), env_portals (a JSON list of the openings the sky lights the scene through, each a corner and its two+//! neighbours: bevy_solari's SkyPortals, for traced lighting).use std::collections::BTreeMap;use std::path::Path;@@ -332,6 +333,10 @@ pub fn environment(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, insEnvMaps(maps.clone(), bakes),Suns(eqs.iter().map(Equirect::sun).collect()),));+ if let Some(V::S(list)) = vals.get("env_portals") {+ let portals: Vec<[[f32; 3]; 3]> = serde_json::from_str(list).map_err(|e| format!("camera: env_portals: {e}"))?;+ world.entity_mut(e).insert(bevy::solari::scene::SkyPortals(portals.iter().map(|q| q.map(Vec3::from)).collect()));+ }if vals.contains_key("sky_k") {let k = num(vals, "sky_k", 0.0);world.entity_mut(e).insert(Skybox { image: (k > 0.0 && num(vals, "env_i", 0.0) > -0.5).then(|| maps[i.min(maps.len() - 1)].clone()), brightness: k, rotation: rot });diff --git a/systems/fog/src/froxel_solari.wesl b/systems/fog/src/froxel_solari.weslindex b99e5e87..2f0b97d8 100644--- a/systems/fog/src/froxel_solari.wesl+++ b/systems/fog/src/froxel_solari.wesl@@ -259,8 +259,8 @@ fn solari(@builtin(global_invocation_id) id: vec3<u32>) {var w_sum = 0.0;for (var i = 0u; i < count; i += 1u) {let s = generate_random_light_sample(&rng).resolved_light_sample;- // a directional light (w 0) is the light pass's- if (s.world_position.w == 0.0) {+ // a directional light (w 0) is the light pass's, a sky portal's sky (w 2) the sky term's+ if (s.world_position.w != 1.0) {continue;}let p_hat = dot(toward_eye(s, P, V, g), LUMA);diff --git a/vendor/bevy_solari/src/pathtracer/pathtracer.wesl b/vendor/bevy_solari/src/pathtracer/pathtracer.weslindex 3baca26b..f9ac6286 100644--- a/vendor/bevy_solari/src/pathtracer/pathtracer.wesl+++ b/vendor/bevy_solari/src/pathtracer/pathtracer.wesl@@ -2,7 +2,7 @@ import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;import bevy_pbr::render::utils::{rand_f, rand_vec2f};import bevy_render::view::View;import package::scene::brdf::{evaluate_brdf, evaluate_and_sample_brdf, brdf_pdf, F_AB};-import package::scene::sampling::{generate_random_light_sample, calculate_resolved_light_contribution, trace_visibility, LightContribution, random_emissive_light_pdf, power_heuristic, sample_environment_map_light_and_sun};+import package::scene::sampling::{sky_portal_mis_weight, generate_random_light_sample, calculate_resolved_light_contribution, trace_visibility, LightContribution, random_emissive_light_pdf, power_heuristic, sample_environment_map_light_and_sun};import package::pathtracer::media::{media_collision, media_transmittance};import raea_sys_fog::froxel_volume::{henyey_greenstein, sample_phase};import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN, RAY_T_MAX, MIRROR_ROUGHNESS_THRESHOLD, materials, material_ids, material_alpha, coat_albedo, facing_normal, ALPHA_PREMULTIPLIED};@@ -144,7 +144,8 @@ fn pathtrace(@builtin(global_invocation_id) global_id: vec3<u32>) {if rand_f(&rng) >= rr { break; }throughput /= rr;} else {- radiance += throughput * sample_environment_map_light_and_sun(ray_direction, sees_sun);+ // raea: through a sky portal, weighted against light sampling, which finds that light too+ radiance += throughput * sample_environment_map_light_and_sun(ray_direction, sees_sun) * sky_portal_mis_weight(ray_origin, ray_direction, p_bounce, 1.0);break;}}diff --git a/vendor/bevy_solari/src/realtime/initial_path.wesl b/vendor/bevy_solari/src/realtime/initial_path.weslindex f4f71bac..548cd386 100644--- a/vendor/bevy_solari/src/realtime/initial_path.wesl+++ b/vendor/bevy_solari/src/realtime/initial_path.wesl@@ -5,7 +5,7 @@ import bevy_render::utils::octahedral_encode;import package::scene::brdf::{brdf_pdf, evaluate_and_sample_brdf, evaluate_brdf, EvaluateAndSampleBrdfResult, F_AB};import package::realtime::presample_light_tiles::unpack_resolved_light_sample;import package::realtime::bindings::{empty_reservoir, light_tile_resolved_samples, light_tile_samples, Reservoir, constants, view};-import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light_and_sun};+import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light_and_sun, sky_portal_mis_weight};import package::scene::bindings::{facing_normal, light_sources, MIRROR_ROUGHNESS_THRESHOLD, RAY_T_MAX, RAY_T_MIN, resolve_ray_hit_full, ResolvedMaterial, ResolvedRayHitFull, trace_ray};import package::realtime::world_cache_query::{get_cell_size, query_world_cache, query_world_cache_found, WORLD_CACHE_CELL_LIFETIME};@@ -121,7 +121,9 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, mat}// raea: the sun only off a mirror's specular lobe, which light sampling can't reach; elsewhere it finds the sun- let environment_map_light_radiance = sample_environment_map_light_and_sun(next_bounce.wi, path.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD && !next_bounce.diffuse_selected);+ // raea: and through a sky portal, weighted against light sampling, which finds that light too+ let environment_map_light_radiance = sample_environment_map_light_and_sun(next_bounce.wi, path.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD && !next_bounce.diffuse_selected)+ * sky_portal_mis_weight(path.ray_origin, next_bounce.wi, next_bounce.pdf, p_nee * f32(di_samples));@if(RESTIR) {generate_environment_map_light_candidate(&path, next_bounce, environment_map_light_radiance, primary_F_ab, bounce, rng);} @else {diff --git a/vendor/bevy_solari/src/realtime/presample_light_tiles.wesl b/vendor/bevy_solari/src/realtime/presample_light_tiles.weslindex be26d89a..c2c9c9bc 100644--- a/vendor/bevy_solari/src/realtime/presample_light_tiles.wesl+++ b/vendor/bevy_solari/src/realtime/presample_light_tiles.wesl@@ -24,7 +24,8 @@ fn pack_resolved_light_sample(sample: ResolvedLightSample) -> ResolvedLightSamplsample.world_position.x,sample.world_position.y,sample.world_position.z,- pack2x16unorm(octahedral_encode(sample.world_normal)),+ // raea: the lowest bit marks a sky portal's sample (w 2)+ (pack2x16unorm(octahedral_encode(sample.world_normal)) & ~1u) | u32(sample.world_position.w == 2.0),vec3_to_rgb9e5_(log2(sample.radiance * view.exposure + 1.0)),sample.inverse_pdf * select(1.0, -1.0, sample.world_position.w == 0.0),);@@ -32,7 +33,7 @@ fn pack_resolved_light_sample(sample: ResolvedLightSample) -> ResolvedLightSamplfn unpack_resolved_light_sample(packed: ResolvedLightSamplePacked, exposure: f32) -> ResolvedLightSample {return ResolvedLightSample(- vec4(packed.world_position_x, packed.world_position_y, packed.world_position_z, select(1.0, 0.0, packed.inverse_pdf < 0.0)),+ vec4(packed.world_position_x, packed.world_position_y, packed.world_position_z, select(select(1.0, 0.0, packed.inverse_pdf < 0.0), 2.0, (packed.world_normal & 1u) != 0u)),octahedral_decode(unpack2x16unorm(packed.world_normal)),(exp2(rgb9e5_to_vec3_(packed.radiance)) - 1.0) / exposure,abs(packed.inverse_pdf),diff --git a/vendor/bevy_solari/src/realtime/world_cache_update.wesl b/vendor/bevy_solari/src/realtime/world_cache_update.weslindex 73fa4597..7a2bfab5 100644--- a/vendor/bevy_solari/src/realtime/world_cache_update.wesl+++ b/vendor/bevy_solari/src/realtime/world_cache_update.wesl@@ -2,7 +2,7 @@ import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;import bevy_pbr::render::utils::{rand_f, rand_range_u, sample_cosine_hemisphere};import bevy_render::maths::PI;import package::realtime::presample_light_tiles::unpack_resolved_light_sample;-import package::scene::sampling::{calculate_resolved_light_contribution, trace_visibility, sample_environment_map_light};+import package::scene::sampling::{calculate_resolved_light_contribution, trace_visibility, sample_environment_map_light, sky_portal_light_pdf};import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN, RAY_T_MAX};import package::realtime::world_cache_query::query_world_cache_found;import package::realtime::bindings::{@@ -70,7 +70,9 @@ fn sample_gi(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invlet origin = geometry_data.world_position + (geometry_data.world_normal * RAY_T_MIN) + ray_direction * cut;escapes = trace_ray(origin, ray_direction, 0.0, RAY_T_MAX, RAY_FLAG_TERMINATE_ON_FIRST_HIT).kind == RAY_QUERY_INTERSECTION_NONE;}- if escapes {+ // raea: light that came in through a sky portal is light sampling's (the cache's light is what it can't sample, as+ // an emissive's own light is left out of it)+ if escapes && sky_portal_light_pdf(geometry_data.world_position, ray_direction) == 0.0 {world_cache.active_cells_new_radiance[active_cell_id.x] += PI * sample_environment_map_light(ray_direction);}}diff --git a/vendor/bevy_solari/src/scene/binder/bind_group.rs b/vendor/bevy_solari/src/scene/binder/bind_group.rsindex 670881dc..eae7cff8 100644--- a/vendor/bevy_solari/src/scene/binder/bind_group.rs+++ b/vendor/bevy_solari/src/scene/binder/bind_group.rs@@ -4,7 +4,7 @@ use super::{};use crate::scene::extract::ExtractedEnvironmentMapLight;use bevy_ecs::system::{Res, ResMut};-use bevy_math::{Mat3, Vec3};+use bevy_math::{Mat3, Vec3, Vec4};use bevy_pbr::DfgLut;use bevy_render::{render_asset::RenderAssets,@@ -353,7 +353,7 @@ pub fn prepare_raytracing_scene_bind_group());}-#[derive(ShaderType, Default)]+#[derive(ShaderType)]pub struct GpuEnvironmentMapLight {pub light_from_world: Mat3,pub intensity: f32,@@ -365,6 +365,43 @@ pub struct GpuEnvironmentMapLight {// raea: 1 when some material in the scene is see-through, so trace_ray runs its second query for them; with none// (a forest of opaque needles), that query only walked the TLAS again for nothingpub any_alpha: u32,+ // raea: the sky portals (SkyPortals), three rows each: the corner and the area, then the two edges+ pub portal_count: u32,+ pub portals: [Vec4; 3 * crate::scene::MAX_SKY_PORTALS],+}++impl Default for GpuEnvironmentMapLight {+ fn default() -> Self {+ Self {+ light_from_world: Mat3::IDENTITY,+ intensity: 0.0,+ sun_direction: Vec3::Y,+ sun_cos: 2.0,+ sky: Vec3::ZERO,+ any_alpha: 0,+ portal_count: 0,+ portals: [Vec4::ZERO; 3 * crate::scene::MAX_SKY_PORTALS],+ }+ }+}++/// raea: the environment's sky portals as the uniform holds them (no more than MAX_SKY_PORTALS; one with no area is left+/// out, so `count` may be fewer)+pub fn pack_sky_portals(portals: &[[Vec3; 3]]) -> (u32, [Vec4; 3 * crate::scene::MAX_SKY_PORTALS]) {+ let mut out = [Vec4::ZERO; 3 * crate::scene::MAX_SKY_PORTALS];+ let mut count = 0;+ for [corner, a, b] in portals.iter().take(crate::scene::MAX_SKY_PORTALS) {+ let (u, v) = (*a - *corner, *b - *corner);+ let area = u.cross(v).length();+ if !(area > 1e-6) {+ continue;+ }+ out[3 * count] = corner.extend(area);+ out[3 * count + 1] = u.extend(0.0);+ out[3 * count + 2] = v.extend(0.0);+ count += 1;+ }+ (count as u32, out)}/// raea: RAEA_SOLARI_ALPHA_PASS=always runs trace_ray's see-through query even in a scene with no see-through material,@@ -400,6 +437,8 @@ fn prepare_environment_map_light<'a>(sun_cos: extracted_environment_map_light.sun.map_or(2.0, |s| bevy_math::ops::cos(s.angular_size / 2.0)),sky: extracted_environment_map_light.sun.map_or(Vec3::ZERO, |s| s.sky),any_alpha: 0,+ portal_count: 0,+ portals: [Vec4::ZERO; 3 * crate::scene::MAX_SKY_PORTALS],},),None => (@@ -409,6 +448,9 @@ fn prepare_environment_map_light<'a>(};uniform.any_alpha = any_alpha as u32;+ if cubemap.is_some() {+ (uniform.portal_count, uniform.portals) = pack_sky_portals(&extracted_environment_map_light.portals);+ }buffer.set(uniform);buffer.write_buffer(render_device, render_queue);texturediff --git a/vendor/bevy_solari/src/scene/binder/lights.rs b/vendor/bevy_solari/src/scene/binder/lights.rsindex 368d7f06..58b5893c 100644--- a/vendor/bevy_solari/src/scene/binder/lights.rs+++ b/vendor/bevy_solari/src/scene/binder/lights.rs@@ -33,6 +33,8 @@ pub struct GpuLightSource {pub enum LightSourceId {EmissiveMesh(Entity),Directional(Entity),+ // raea: the environment's sky portals, by their index in the environment uniform+ SkyPortal(u32),}#[derive(Default)]@@ -106,6 +108,14 @@ impl GpuLightSource {id: directional_light_id,}}++ /// raea: a sky portal (bindings.wesl LIGHT_SOURCE_KIND_SKY_PORTAL), its index in the environment uniform+ fn new_sky_portal(portal_id: u32) -> GpuLightSource {+ Self {+ kind: 3,+ id: portal_id,+ }+ }}#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]@@ -159,6 +169,8 @@ pub struct LightState {previous_index: HashMap<LightSourceId, u32>,nonidentity_translations: Vec<u32>,directional_slots: SlotAllocator<Entity>,+ /// raea: how many sky portals are in the light list+ sky_portals: u32,/// Set by the lighting node once it has recorded work reading the translation table.translations_consumed: AtomicBool,}@@ -182,6 +194,7 @@ impl LightState {previous_index: HashMap::default(),nonidentity_translations: Vec::new(),directional_slots: SlotAllocator::new(),+ sky_portals: 0,translations_consumed: AtomicBool::new(false),}}@@ -230,6 +243,20 @@ impl LightState {self.remove_light(LightSourceId::Directional(entity));}+ // raea: the environment's sky portals, one light each, as the environment uniform packs them (bind_group.rs)+ let portals = if environment.cubemap.is_some() && environment.intensity > 0.0 {+ super::bind_group::pack_sky_portals(&environment.portals).0+ } else {+ 0+ };+ for portal in 0..portals {+ self.add_light(LightSourceId::SkyPortal(portal), GpuLightSource::new_sky_portal(portal));+ }+ for portal in portals..self.sky_portals {+ self.remove_light(LightSourceId::SkyPortal(portal));+ }+ self.sky_portals = portals;+self.write_light_id_translations();if self.index.len() > u16::MAX as usize {diff --git a/vendor/bevy_solari/src/scene/bindings.wesl b/vendor/bevy_solari/src/scene/bindings.weslindex ef3a4e6f..93c26feb 100644--- a/vendor/bevy_solari/src/scene/bindings.wesl+++ b/vendor/bevy_solari/src/scene/bindings.wesl@@ -111,6 +111,8 @@ struct LightSource {const LIGHT_SOURCE_KIND_EMISSIVE_MESH = 0u;const LIGHT_SOURCE_KIND_DIRECTIONAL = 1u;+// raea: an opening the environment map lights the scene through (SkyPortals); id: its index in environment_map_light+const LIGHT_SOURCE_KIND_SKY_PORTAL = 3u;struct DirectionalLight {direction_to_light: vec3<f32>,@@ -128,6 +130,25 @@ struct EnvironmentMapLight {sky: vec3<f32>,// raea: 1 when some material is see-through (bind_group.rs), else trace_ray skips its second queryany_alpha: u32,+ // raea: the sky portals (bind_group.rs pack_sky_portals): three rows each, the corner and the area, then the edges+ portal_count: u32,+ portals: array<vec4<f32>, 24>,+}++// raea: a sky portal, the parallelogram corner + a u + b v for a and b from 0 to 1; normal: cross(u, v), unit length+struct SkyPortal {+ corner: vec3<f32>,+ area: f32,+ u: vec3<f32>,+ v: vec3<f32>,+ normal: vec3<f32>,+}++fn sky_portal(id: u32) -> SkyPortal {+ let c = environment_map_light.portals[3u * id];+ let u = environment_map_light.portals[3u * id + 1u].xyz;+ let v = environment_map_light.portals[3u * id + 2u].xyz;+ return SkyPortal(c.xyz, c.w, u, v, normalize(cross(u, v)));}const LIGHT_NOT_PRESENT_THIS_FRAME = 0xFFFFFFFFu;diff --git a/vendor/bevy_solari/src/scene/extract.rs b/vendor/bevy_solari/src/scene/extract.rsindex 8b88046d..18a9c147 100644--- a/vendor/bevy_solari/src/scene/extract.rs+++ b/vendor/bevy_solari/src/scene/extract.rs@@ -1,4 +1,4 @@-use super::{EnvironmentSun, RaytracingMesh3d, RaytracingSceneBindings};+use super::{EnvironmentSun, RaytracingMesh3d, RaytracingSceneBindings, SkyPortals};use bevy_asset::{AssetEvent, AssetId, Assets, Handle};use bevy_camera::Camera;use bevy_ecs::{@@ -160,6 +160,8 @@ pub struct ExtractedEnvironmentMapLight {pub rotation: Quat,// raea: the camera's EnvironmentSunpub sun: Option<EnvironmentSun>,+ // raea: the camera's SkyPortals+ pub portals: Vec<[bevy_math::Vec3; 3]>,}/// Finds the environment map light to use for the raytraced scene, if any.@@ -170,13 +172,14 @@ pub fn extract_raytracing_environment_map_light(Option<&GeneratedEnvironmentMapLight>,Option<&EnvironmentMapLight>,Option<&EnvironmentSun>,+ Option<&SkyPortals>,)>,>,mut environment_map_light: ResMut<ExtractedEnvironmentMapLight>,) {let mut extracted_env_map_light = ExtractedEnvironmentMapLight::default();- for (camera, generated, pregenerated, sun) in &cameras {+ for (camera, generated, pregenerated, sun, portals) in &cameras {if !camera.is_active {continue;}@@ -187,12 +190,14 @@ pub fn extract_raytracing_environment_map_light(intensity: generated.intensity,rotation: generated.rotation,sun: sun.copied(),+ portals: portals.map(|p| p.0.clone()).unwrap_or_default(),},(None, Some(pregenerated)) => ExtractedEnvironmentMapLight {cubemap: Some(pregenerated.specular_map.clone()),intensity: pregenerated.intensity,rotation: pregenerated.rotation,sun: sun.copied(),+ portals: portals.map(|p| p.0.clone()).unwrap_or_default(),},(None, None) => continue,};diff --git a/vendor/bevy_solari/src/scene/mod.rs b/vendor/bevy_solari/src/scene/mod.rsindex b092329c..06bd1d38 100644--- a/vendor/bevy_solari/src/scene/mod.rs+++ b/vendor/bevy_solari/src/scene/mod.rs@@ -8,7 +8,7 @@ use bevy_shader::load_shader_library;pub use binder::prepare_raytracing_scene_resources;pub use binder::{RaytracingSceneBindings, RaytracingSceneNeedsPreviousFrameData};// raea: EnvironmentSun, a panorama's sun sampled as a light-pub use types::{EnvironmentSun, RaytracingMesh3d};+pub use types::{EnvironmentSun, RaytracingMesh3d, SkyPortals, MAX_SKY_PORTALS};use crate::SolariPlugins;use bevy_app::{App, Plugin};diff --git a/vendor/bevy_solari/src/scene/sampling.wesl b/vendor/bevy_solari/src/scene/sampling.weslindex 51c459b6..7113ebb5 100644--- a/vendor/bevy_solari/src/scene/sampling.wesl+++ b/vendor/bevy_solari/src/scene/sampling.wesl@@ -1,7 +1,7 @@import bevy_pbr::render::pbr_lighting::D_GGX;import bevy_pbr::render::utils::{rand_vec2f, rand_u, rand_range_u};import bevy_render::maths::{PI_2, orthonormalize};-import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, LIGHT_SOURCE_KIND_DIRECTIONAL, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD};+import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, LIGHT_SOURCE_KIND_DIRECTIONAL, LIGHT_SOURCE_KIND_SKY_PORTAL, sky_portal, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD};enable wgpu_ray_query;@@ -162,7 +162,8 @@ fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightSlet light_source = light_sources[light_id];var triangle_id = 0u;- if light_source.kind != LIGHT_SOURCE_KIND_DIRECTIONAL {+ // an emissive mesh (raea: an even kind; directional lights and sky portals are odd)+ if (light_source.kind & 1u) == 0u {let triangle_count = light_source.kind >> 1u;triangle_id = rand_range_u(triangle_count, rng);}@@ -177,6 +178,17 @@ fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightS}fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) -> ResolvedLightSample {+ // raea: a sky portal: a point on the opening, w 2, its radiance white; the environment map's light through it+ // depends on where it's seen from, so calculate_resolved_light_contribution looks it up+ if light_source.kind == LIGHT_SOURCE_KIND_SKY_PORTAL {+ if light_source.id >= environment_map_light.portal_count {+ return ResolvedLightSample(vec4(0.0, 0.0, 0.0, 2.0), vec3(0.0, 1.0, 0.0), vec3(0.0), 0.0);+ }+ let portal = sky_portal(light_source.id);+ var rng = light_sample.seed;+ let r = rand_vec2f(&rng);+ return ResolvedLightSample(vec4(portal.corner + portal.u * r.x + portal.v * r.y, 2.0), portal.normal, vec3(1.0), portal.area);+ }if light_source.kind == LIGHT_SOURCE_KIND_DIRECTIONAL {let directional_light = directional_lights[light_source.id];@@ -221,18 +233,61 @@ fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) ->}fn calculate_resolved_light_contribution(resolved_light_sample: ResolvedLightSample, ray_origin: vec3<f32>, origin_world_normal: vec3<f32>) -> LightContribution {- let ray = resolved_light_sample.world_position.xyz - (resolved_light_sample.world_position.w * ray_origin);+ // raea: a sky portal's point (w 2) is placed as an emissive's is, lit by the environment map along the way through+ // it, from either side+ let portal = resolved_light_sample.world_position.w == 2.0;+ let w = min(resolved_light_sample.world_position.w, 1.0);+ let ray = resolved_light_sample.world_position.xyz - (w * ray_origin);let light_distance = length(ray);let wi = ray / light_distance;- let cos_theta_light = saturate(dot(-wi, resolved_light_sample.world_normal));+ var cos_theta_light = saturate(dot(-wi, resolved_light_sample.world_normal));+ var emitted = resolved_light_sample.radiance;+ if portal {+ cos_theta_light = abs(dot(wi, resolved_light_sample.world_normal));+ emitted *= sample_environment_map_light(wi);+ }let light_distance_squared = light_distance * light_distance;let denominator = cos_theta_light / light_distance_squared;- let radiance = resolved_light_sample.radiance * denominator;+ let radiance = emitted * denominator;let inverse_solid_angle_pdf = resolved_light_sample.inverse_pdf * denominator;- return LightContribution(radiance, resolved_light_sample.inverse_pdf, inverse_solid_angle_pdf, wi, resolved_light_sample.world_position.w == 1.0);+ return LightContribution(radiance, resolved_light_sample.inverse_pdf, inverse_solid_angle_pdf, wi, w == 1.0);+}++// raea: the pdf light sampling (generate_random_light_sample) has for the direction wi from origin, where wi leaves+// through a sky portal (solid angle); 0 where it crosses none+fn sky_portal_light_pdf(origin: vec3<f32>, wi: vec3<f32>) -> f32 {+ for (var i = 0u; i < environment_map_light.portal_count; i++) {+ let portal = sky_portal(i);+ let cos_portal = dot(wi, portal.normal);+ if abs(cos_portal) < 1e-6 { continue; }+ let t = dot(portal.corner - origin, portal.normal) / cos_portal;+ if t <= 0.0 { continue; }+ // where it crosses, in the portal's (u, v)+ let h = origin + wi * t - portal.corner;+ let uu = dot(portal.u, portal.u);+ let uv = dot(portal.u, portal.v);+ let vv = dot(portal.v, portal.v);+ let det = uu * vv - uv * uv;+ let a = (dot(h, portal.u) * vv - dot(h, portal.v) * uv) / det;+ let b = (dot(h, portal.v) * uu - dot(h, portal.u) * uv) / det;+ if a < 0.0 || a > 1.0 || b < 0.0 || b > 1.0 { continue; }+ return t * t / (f32(arrayLength(&light_sources)) * portal.area * abs(cos_portal));+ }+ return 0.0;+}++// raea: what a ray that escaped to the sky along wi keeps of the environment map's light, where it left through a sky+// portal that light sampling also finds that light through: the power heuristic against light sampling's pdf, scaled+// by nee_scale (the candidates the ray's vertex drew, times the chance it drew any). A ray drawn with no pdf (bounce_pdf+// 0: a camera ray) or along a mirror's delta lobe (infinite) keeps all of it, as does one that crossed no portal.+fn sky_portal_mis_weight(origin: vec3<f32>, wi: vec3<f32>, bounce_pdf: f32, nee_scale: f32) -> f32 {+ if bounce_pdf <= 0.0 || isinf(bounce_pdf) || environment_map_light.portal_count == 0u { return 1.0; }+ let p_light = sky_portal_light_pdf(origin, wi);+ if p_light <= 0.0 { return 1.0; }+ return power_heuristic(bounce_pdf, p_light * nee_scale);}fn trace_visibility(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {@@ -244,6 +299,9 @@ fn trace_visibility(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {let dist = length(ray);ray_direction = ray / dist;ray_t_max = dist - RAY_T_MIN;+ } else if point.w == 2.0 {+ // raea: a sky portal's point: through it, out to the sky+ ray_direction = normalize(point.xyz - ray_origin);}if ray_t_max < RAY_T_MIN { return 0.0; }@@ -261,6 +319,9 @@ fn trace_visibility_previous_frame(ray_origin: vec3<f32>, point: vec4<f32>) -> flet dist = length(ray);ray_direction = ray / dist;ray_t_max = dist - RAY_T_MIN;+ } else if point.w == 2.0 {+ // raea: a sky portal's point: through it, out to the sky+ ray_direction = normalize(point.xyz - ray_origin);}if ray_t_max < RAY_T_MIN { return 0.0; }diff --git a/vendor/bevy_solari/src/scene/types.rs b/vendor/bevy_solari/src/scene/types.rsindex f1d3aba8..212dbdb8 100644--- a/vendor/bevy_solari/src/scene/types.rs+++ b/vendor/bevy_solari/src/scene/types.rs@@ -38,3 +38,15 @@ pub struct EnvironmentSun {/// The sky's radiance around it, linear RGB, before the intensity: what the environment map shows inside the disk.pub sky: bevy_math::Vec3,}++/// raea: the openings a camera's environment map lights the scene through (a skylight, a window), in world space: each+/// a parallelogram, a corner and its two neighbours. Solari samples each as a light (points on the opening, lit by the+/// environment map along the way through it), so a room lit by the sky through a small opening gets that light as+/// direct light, which rays bounced at random find too rarely for the denoiser to keep; a ray that leaves through an+/// opening is weighted against that sampling (MIS), so the light counts once. Light passes both ways; up to+/// MAX_SKY_PORTALS are used.+#[derive(Component, Clone, Debug, Default, PartialEq)]+pub struct SkyPortals(pub Vec<[bevy_math::Vec3; 3]>);++/// raea: how many sky portals the environment uniform holds (bindings.wesl's array)+pub const MAX_SKY_PORTALS: usize = 8;