Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/scene/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ This package builds the scene. A ThreeRT client draws it:

Games add state and input with [`@threert/gameplay`](https://www.npmjs.com/package/@threert/gameplay); destructible voxel worlds use [`@threert/voxel`](https://www.npmjs.com/package/@threert/voxel).

## HDRI environments

Use a linear equirectangular OpenEXR or Radiance HDR texture to light the scene, reflect in materials, and show as the sky.

```typescript
import { HDRIEnvironment, Texture } from "@threert/scene";

scene.environment = new HDRIEnvironment(new Texture("assets/sky.exr", "linear"), 1, Math.PI / 2);
scene.backgroundPanorama = new HDRIEnvironment(new Texture("assets/camera-sky.exr", "linear"));
```

Rotation is in radians around +Y. `intensity` scales both the lighting and the visible sky. `skyLightIntensity` scales lighting and reflections only. Set `scene.background` for a solid color or `scene.backgroundPanorama` for a separate image with its own intensity and rotation.

## Links

[threert.dev](https://threert.dev) · [Docs](https://threert.dev/docs/) · [Showcase](https://threert.dev/showcase/) · [GitHub](https://github.com/meshy-dev/ThreeRT)
Expand Down
4 changes: 4 additions & 0 deletions packages/scene/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,8 @@ export class Scene extends Object3D {
environment: Environment | null = null;
/** three.js: what camera rays that miss show (a colour, sRGB as given; null: the environment). It lights nothing. */
background: Color | null = null;
/** Equirectangular image for camera rays. Takes precedence over `background` and does not light the scene. */
backgroundPanorama: HDRIEnvironment | null = null;
/** Height fog (three.js's `Fog` / `FogExp2` are kinds of it). */
fog: ExponentialHeightFog | null = null;
/** Global surface wetness 0..1 (material functions read it as `i.wetness`: SurfaceMaterial's `wet` / `puddles`,
Expand Down Expand Up @@ -2384,11 +2386,13 @@ export class SkyColor {
}
}

/** An equirectangular texture in its scene orientation. Rotation is around +Y, in radians. */
export class HDRIEnvironment {
readonly kind = "hdri";
texture: Texture;
intensity: number;
rotation: number;
/** Lighting and reflections multiplier, in addition to `intensity`. */
skyLightIntensity = 1;
constructor(texture: Texture, intensity = 1, rotation = 0) {
this.texture = texture;
Expand Down
5 changes: 4 additions & 1 deletion packages/scene/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export interface EnvironmentDesc {
sky: SkyDesc;
/** three.js `scene.background`: what camera rays that miss show (linear rgb, displayed as given), lighting nothing. */
background?: Vec3;
backgroundPanorama?: { texture: number; intensity: number; rotation: number };
fog?: FogDesc;
wetness?: number;
rain?: number;
Expand Down Expand Up @@ -1554,7 +1555,9 @@ export class SceneBinding {
const e: EnvironmentDesc = { sky: this.skyDesc() };
// three.js's background colour is shown as given: here as radiance at the level of the scene's light, so that it
// sits with the lit surfaces under any exposure (white: a white diffuse surface in the key light).
if (scene.background) e.background = vec3(scene.background).map((c) => c * this.lightLevel()) as Vec3;
const panorama = scene.backgroundPanorama;
if (panorama) e.backgroundPanorama = { texture: this.textureId(panorama.texture)!, intensity: panorama.intensity, rotation: panorama.rotation };
else if (scene.background) e.background = vec3(scene.background).map((c) => c * this.lightLevel()) as Vec3;
// Ambient lights light the scene, they are not seen: without a background colour, black (three.js's clear colour).
else if (!scene.environment && e.sky.type !== "atmosphere" && this.ambientSky()) e.background = [0, 0, 0];
if (scene.fog) {
Expand Down
2 changes: 1 addition & 1 deletion renderer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ bytemuck = { version = "1", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
gltf = { version = "1.4", features = ["KHR_materials_emissive_strength", "KHR_texture_transform", "KHR_materials_ior", "KHR_materials_transmission", "extensions"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "exr"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "exr", "hdr"] }
glam = { version = "0.30", features = ["bytemuck"] }
rayon = "1.10"
anyhow = "1"
Expand Down
46 changes: 36 additions & 10 deletions renderer/shaders/pathtrace.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ struct Params {
env: vec4<f32>, // has env map, env width, env height, sun light index (-1 none)
misc: vec4<f32>, // clamp (absolute radiance), - (the emitters' total weight is their table's: `emitter_totals`), env total weight, _
sky_color: vec4<f32>, // constant sky radiance when no env map
hdri: vec4<f32>, // longitude offset in turns, lighting scale, visible scale, enabled
counts2: vec4<u32>, // directional lights (first in `lights`), environment NEE on, output height for texture LOD (0 = traced height), first shadowed local light
time: vec4<f32>, // scene time (s), wetness, rain, -
fog: vec4<f32>, // density at fog height (1/m), height falloff (1/m), fog height, start distance (m)
Expand All @@ -118,7 +119,7 @@ struct Params {
ltree: vec4<f32>, // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), - (the tail's share is the table's: `emitter_totals`), candidates at camera hits (0 = off)
procs: vec4<u32>, // procedural geometry (F_PROC): -, object count, first record in `instances`, -
aerial: vec4<f32>, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -
background: vec4<f32>, // three.js scene.background (radiance), 1 (F_BACKGROUND)
background: vec4<f32>, // colour (RGB, 1) or panorama (longitude offset, intensity, 0, 2)
ltile: vec4<u32>, // live light tiles (`lt_list_start`): 1 with last frame's lists (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list
ltile2: vec4<u32>, // the traced size they were built at, -, -
lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
Expand Down Expand Up @@ -153,6 +154,7 @@ const VERTEX_VEC4: u32 = 3u;
@group(0) @binding(7) var textures: texture_2d_array<f32>;
@group(0) @binding(8) var samp: sampler;
@group(0) @binding(9) var env_tex: texture_2d<f32>;
@group(0) @binding(20) var background_tex: texture_2d<f32>;
// The scene's flat arrays, sections of one buffer of 32-bit words (heap.rs `Stream`), each from the word
// `P.word_first` names: the environment's CDF (floats: [0, H) the rows' marginal CDF, then H rows of W conditional
// entries; `env_cdf_at`), the procedural data (`pword`, `gdata`), the vertex colours (`vcolor_word`), the instances'
Expand Down Expand Up @@ -1901,16 +1903,29 @@ fn env_uv(d: vec3<f32>) -> vec2<f32> {
return vec2<f32>(u, v);
}

// The sampler wraps longitude. Clamp to the edge rows so opposite poles do not blend.
fn panorama_radiance(tex: texture_2d<f32>, uv: vec2<f32>) -> vec3<f32> {
let edge = 0.5 / f32(textureDimensions(tex).y);
return textureSampleLevel(tex, samp, vec2<f32>(uv.x, clamp(uv.y, edge, 1.0 - edge)), 0.0).rgb;
}

fn hdri_uv(d: vec3<f32>, offset: f32) -> vec2<f32> {
let uv = env_uv(d);
return vec2<f32>(fract(uv.x + offset), uv.y);
}

fn env_radiance(d: vec3<f32>) -> vec3<f32> {
if (P.env.x < 0.5) { return P.sky_color.rgb; }
if (P.hdri.w > 0.0) { return panorama_radiance(env_tex, hdri_uv(d, P.hdri.x)) * P.hdri.y; }
return textureSampleLevel(env_tex, samp, env_uv(d), 0.0).rgb;
}

fn env_pdf(d: vec3<f32>) -> f32 {
if (P.env.x < 0.5) { return 1.0 / (4.0 * PI); }
let w = u32(P.env.y); let h = u32(P.env.z);
let uv = env_uv(d);
let x = min(u32(uv.x * f32(w)), w - 1u);
let u = select(uv.x, fract(uv.x + P.hdri.x), P.hdri.w > 0.0);
let x = min(u32(u * f32(w)), w - 1u);
let y = min(u32(uv.y * f32(h)), h - 1u);
@if(!strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(y - 1u), y > 0u);
@if(strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(max(y, 1u) - 1u), y > 0u);
Expand Down Expand Up @@ -1945,7 +1960,7 @@ fn sample_env(rd: u32) -> vec3<f32> {
let u = (f32(x) + u4.z) / f32(w);
let v = (f32(y) + u4.w) / f32(h);
let theta = v * PI;
let phi = (u - 0.5) * 2.0 * PI;
let phi = (u - P.hdri.x - 0.5) * 2.0 * PI;
return vec3<f32>(sin(theta) * sin(phi), cos(theta), -sin(theta) * cos(phi));
}

Expand All @@ -1967,11 +1982,21 @@ fn offset_origin(p: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
return p + n * (1e-4 * max(1.0, max(abs(p.x), max(abs(p.y), abs(p.z)))));
}

// What a BSDF-sampled ray (solid-angle pdf `pdf`; 0 = the camera ray, no MIS) that left the scene brings back: the
// environment and the directional lights' disks, MIS-weighted against their sampling in `direct_light`.
fn sky_mis(d: vec3<f32>, pdf: f32) -> vec3<f32> {
// What a ray that left the scene brings back. A solid-angle PDF of zero disables MIS.
// The environment and the directional lights' disks are weighed against their sampling in `direct_light`.
fn sky_mis(d: vec3<f32>, pdf: f32, camera: bool) -> vec3<f32> {
// three.js scene.background: what camera rays (and paths bent straight through glass) see where nothing is.
if (has(F_BACKGROUND) && pdf <= 0.0) { return P.background.rgb; }
if (camera) {
if (has(F_BACKGROUND)) {
if (P.background.w > 1.0) {
return panorama_radiance(background_tex, hdri_uv(d, P.background.x)) * P.background.y;
}
return P.background.rgb;
}
if (P.hdri.w > 0.0) {
return panorama_radiance(env_tex, hdri_uv(d, P.hdri.x)) * P.hdri.z;
}
}
var wgt = 1.0;
if (pdf > 0.0 && P.counts2.y != 0u) {
wgt = power_heuristic(pdf, env_pdf(d));
Expand Down Expand Up @@ -3707,7 +3732,7 @@ fn cache_train(s0: Surface, d0: vec3<f32>, cone0: vec2<f32>, depth: u32, insert:
tr *= mh.tr;
}
if (miss) {
gather[k] = g + tr * sky_mis(l, pdf);
gather[k] = g + tr * sky_mis(l, pdf, false);
break;
}
cur_depth = 3u + k;
Expand Down Expand Up @@ -3902,7 +3927,7 @@ fn guide_hit(origin: vec3<f32>, dir: vec3<f32>, footprint: f32, through_glass: b
let h = trace(o, d, INF, TRACE_CLOSEST);
if (h.tri == 0xffffffffu) {
var sky = env_radiance(d);
if (through_glass) { sky = sky_mis(d, 0.0); }
if (through_glass) { sky = sky_mis(d, 0.0, true); }
return GuideHit(guide_color(sky), -d, 1.0, select(first, 1e4, i == 0u));
}
if (i == 0u) { first = h.t; }
Expand Down Expand Up @@ -4439,7 +4464,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
}
if (hit.tri == 0xffffffffu) {
var c = thr * sky_mis(d, select(0.0, last_pdf, depth > 0u && !bent));
let camera_sky = depth == 0u || (straight && behind_glass);
var c = thr * sky_mis(d, select(0.0, last_pdf, depth > 0u && !bent), camera_sky);
if (depth > 1u && !straight) {
let lum = luminance(c);
if (lum > clamp_v) { c *= clamp_v / lum; }
Expand Down
10 changes: 10 additions & 0 deletions renderer/src/desc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ pub struct Environment {
/// three.js `scene.background`: what camera rays that miss see (radiance, linear rgb), lighting nothing.
#[serde(default)]
pub background: Option<Vec3>,
#[serde(default, rename = "backgroundPanorama")]
pub background_panorama: Option<BackgroundPanorama>,
/// Global surface wetness 0..1 (material functions' `i.wetness`).
#[serde(default)]
pub wetness: f32,
Expand All @@ -149,6 +151,14 @@ pub struct Environment {
pub cloud_cover: f32,
}

/// Equirectangular background radiance for camera rays.
#[derive(Deserialize, Debug, Clone)]
pub struct BackgroundPanorama {
pub texture: u32,
pub intensity: f32,
pub rotation: f32,
}

/// Exponential height fog (UE ExponentialHeightFog): extinction `density * exp(-heightFalloff * (y - height))`.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
Expand Down
9 changes: 7 additions & 2 deletions renderer/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,15 @@ pub fn version(path: &Path) -> (u64, u128) {

/// A texture file decoded to RGBA8.
pub fn image(path: &Path) -> Result<image::RgbaImage> {
Ok(image_data(path)?.into_rgba8())
}

/// Decode a file without reducing its colour depth.
pub fn image_data(path: &Path) -> Result<image::DynamicImage> {
#[cfg(not(target_arch = "wasm32"))]
return Ok(image::open(path)?.to_rgba8());
return Ok(image::open(path)?);
#[cfg(target_arch = "wasm32")]
return Ok(image::load_from_memory(&read(path)?)?.to_rgba8());
return Ok(image::load_from_memory(&read(path)?)?);
}

/// A glTF / GLB file: its document, and the binary chunk of a GLB. (The buffers and images it names beside it are
Expand Down
34 changes: 23 additions & 11 deletions renderer/src/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ pub struct Params {
pub env: [f32; 4],
pub misc: [f32; 4],
pub sky_color: [f32; 4],
/// HDRI longitude offset in turns, lighting scale, visible scale, enabled.
pub hdri: [f32; 4],
pub counts2: [u32; 4], // directional lights (first in the light list), -, -, -
pub time: [f32; 4], // scene time (s), wetness, rain, -
pub fog: [f32; 4], // density at fog height (1/m), height falloff (1/m), fog height (m), start distance (m)
Expand All @@ -160,7 +162,7 @@ pub struct Params {
pub procs: [u32; 4],
/// The sky's aerial perspective (F_AERIAL; `scene::aerial_params`): density multiple, Rayleigh scale, Mie scale, -.
pub aerial: [f32; 4],
/// three.js `scene.background` (F_BACKGROUND): its radiance, 1.
/// Camera background (F_BACKGROUND): RGB, 1 for a colour, or longitude offset, intensity, 0, 2 for a panorama.
pub background: [f32; 4],
/// The live light tiles (pathtrace.wgsl "Light tiles"; live/frame.rs): 1 with the last frame's lists (0: none
/// this frame), tiles a row, the grid's offset when they were built (x | y << 16), candidates a
Expand Down Expand Up @@ -340,6 +342,7 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupL
layout_entry(9, float_texture(wgpu::TextureViewDimension::D2)),
layout_entry(10, float_texture(wgpu::TextureViewDimension::D3)),
layout_entry(11, write),
layout_entry(20, float_texture(wgpu::TextureViewDimension::D2)),
];
// Software traversal's trees: their leaves' triangles, their nodes.
if !hwrt {
Expand Down Expand Up @@ -384,6 +387,7 @@ pub struct BindParts {
pub leaves: wgpu::Buffer,
pub tex_view: wgpu::TextureView,
pub env_view: wgpu::TextureView,
pub background_view: Option<wgpu::TextureView>,
pub sampler: wgpu::Sampler,
/// The density grids' atlas (binding 19), or the one-cell texture of a scene without grids.
pub grid_view: wgpu::TextureView,
Expand Down Expand Up @@ -2056,10 +2060,11 @@ pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures:
f
}

#[derive(Clone)]
pub struct EnvMap {
pub width: u32,
pub height: u32,
pub texels: Vec<[f32; 4]>,
pub texels: std::sync::Arc<[[f32; 4]]>,
}

pub struct Frame {
Expand Down Expand Up @@ -2691,8 +2696,10 @@ impl Gpu {
assert!(parts.iter().enumerate().all(|(k, p)| p.0.index() == k), "the tables in `Table`'s order");
let heap = Heap::filled(d, &parts.map(|p| (p.1.len() + p.2) as u64), |put| parts.iter().for_each(|p| put(p.0, 0, p.1)));

let env_tex = self.env_texture(env);
let env_tex = self.env_texture(env)?;
let env_view = env_tex.create_view(&Default::default());
let background_view = scene.background_map.as_ref()
.map(|map| self.env_texture(map).map(|t| t.create_view(&Default::default()))).transpose()?;
let sampler = d.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
Expand Down Expand Up @@ -2859,7 +2866,7 @@ impl Gpu {
fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }
}
let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, sampler, grid_view };
let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, background_view, sampler, grid_view };
let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, vertices: &b_vertices, heap: &heap, words: &words, prev_vertices: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref() });
let kernel = Kernel { approx: self.approx, ..Kernel::new(scene) };
// Translucent particles (hardware RT): the translucency pass's own TLAS, built again after the particle pass:
Expand Down Expand Up @@ -3540,7 +3547,9 @@ impl Gpu {
}

/// An environment map's texture, with its texels.
fn env_texture(&self, env: &EnvMap) -> wgpu::Texture {
fn env_texture(&self, env: &EnvMap) -> Result<wgpu::Texture> {
let limit = self.device.limits().max_texture_dimension_2d;
anyhow::ensure!(env.width.max(env.height) <= limit, "environment map {} x {} exceeds device texture limit {limit}", env.width, env.height);
let t = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("env"),
size: wgpu::Extent3d { width: env.width, height: env.height, depth_or_array_layers: 1 },
Expand All @@ -3552,7 +3561,7 @@ impl Gpu {
view_formats: &[],
});
self.write_env_texels(&t, env);
t
Ok(t)
}

fn write_env_texels(&self, t: &wgpu::Texture, env: &EnvMap) {
Expand Down Expand Up @@ -3583,13 +3592,15 @@ impl Gpu {
return true;
}
let bytes = cdf.len() as u64 * 4;
if bytes > up.words.cap(Stream::EnvCdf) {
if !self.buffer_fits(up.words.size_with(Stream::EnvCdf, bytes)) {
return false;
}
let grow = bytes > up.words.cap(Stream::EnvCdf);
if grow && !self.buffer_fits(up.words.size_with(Stream::EnvCdf, bytes)) {
return false;
}
let Ok(texture) = self.env_texture(env) else { return false };
if grow {
up.words.grow(&self.device, &self.queue, Stream::EnvCdf, bytes);
}
up.env_tex = self.env_texture(env);
up.env_tex = texture;
up.bg_parts.env_view = up.env_tex.create_view(&Default::default());
up.words.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(cdf));
up.cdf_words = cdf.len();
Expand Down Expand Up @@ -3867,6 +3878,7 @@ impl Gpu {
view(9, &p.env_view),
view(10, &p.grid_view),
buffer_entry(11, b.accum),
view(20, p.background_view.as_ref().unwrap_or(&p.env_view)),
];
if !self.hwrt {
entries.push(buffer_entry(2, &p.leaves));
Expand Down
Loading