The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Stream textures: an app replaces a texture's pixels while the scene runs (#148)
Evan (Yifeng) Wang138978a25dc1
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 477a193..9488580 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -779,6 +779,38 @@ threert-render play game.js --assets games/openstrike \(picked a folder, read a model from it, converted it across frames, stored it, shown from the store; a second runshows it from the store without asking).+## Stream textures++A texture whose pixels the app replaces while the scene runs: a screen in the scene that shows what a program+draws, a camera, a video. The scene describes it once, by name and size:++```ts+import { MeshStandardMaterial, StreamTexture } from "@threert/scene";++const picture = new StreamTexture("screen", 640, 360); // black until the first picture arrives+const panel = new MeshStandardMaterial({ color: 0x000000, emissive: 0xffffff, emissiveMap: picture, emissiveIntensity: 300 });+```++and the app that embeds the engine hands over pictures by that name:++```rust+core.write_stream("screen", 640, 360, &rgba)?; // LiveCore, before the frame's `render`+```++- **Nothing is rebuilt.** A stream's identity in the texture pages is its name and size, not its pixels+ (`texpack::stream_key`), so `texpack::set_key` does not change with a picture. `Gpu::write_stream` writes the+ texture's padded rect (its content, its gutters as `pack` fills them, every mip level: `texpack::patch`) into+ its place with `queue.write_texture`. A 640 x 360 picture is about 1.4 MB of texels a frame.+- **The last picture is kept** (`Gpu.streams`): pages that are packed again for another texture set show it, not+ the picture the scene was described with.+- **A size other than the texture's** is resized to it (the packer shrinks a power-of-two texture of 512 or more+ by its gutters).+- **For a picture that changes every frame, emit it from a material function** (docs/MATERIAL_FUNCTIONS.md):+ emission from a function keeps the live view's short history, so the screen shows this frame's picture and+ not a blend of the last sixteen.+- The script side has no call for it: pictures come from the app (`write_stream`), not through the script+ runtime. A script's own `DataTexture` with `needsUpdate` still rebuilds, as before.+## The runtime's shape: Rust owns the world, the script engine is a guestDecided by the user on 2026-11-10, with the measurements below.diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex 8f29f4a..c6e7b6d 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -2261,6 +2261,26 @@ export class DataTexture extends Texture {}}+/** A texture whose pixels the app replaces while the scene runs: a screen that shows what a program draws, a camera,+ * a video. The app names the stream when it writes a picture (the engine's `LiveCore::write_stream`); the scene and+ * its history are not rebuilt. `rgba` is what the texture shows until the first picture arrives (black by default).+ * Clamped by default: a screen's edge does not show the opposite edge. */+export class StreamTexture extends DataTexture {+ readonly stream: string;+ constructor(stream: string, width: number, height: number, rgba?: Uint8Array, colorSpace: "srgb" | "linear" = "srgb") {+ super(width, height, rgba ?? opaqueBlack(width, height), colorSpace);+ if (!stream || stream.length > 64 || stream.includes("|")) throw new RangeError(`StreamTexture: a stream's name is 1 to 64 characters without "|", not ${JSON.stringify(stream)}`);+ this.stream = stream;+ this.wrap = "clamp";+ }+}++function opaqueBlack(width: number, height: number): Uint8Array {+ const px = new Uint8Array(width * height * 4);+ for (let i = 3; i < px.length; i += 4) px[i] = 255;+ return px;+}+/** Two-tone checkerboard (sRGB hex colors), `cells` squares per side. */export function checkerTexture(a = 0xd0d0d0, b = 0x303030, cells = 8, size = 512): DataTexture {const px = new Uint8Array(size * size * 4);diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.tsindex c4d555c..0caa2ce 100644--- a/packages/scene/src/engine.ts+++ b/packages/scene/src/engine.ts@@ -10,7 +10,7 @@import {AmbientLight, compatNote, DirectionalLight, Fog, FogExp2, GLTFModel, HDRIEnvironment, HemisphereLight, InstancedMesh, Light, MeshBasicMaterial, MaterialFunction, Mesh, MeshPhysicalMaterial, type MeshStandardMaterial, Object3D,type ParticleBinding, type ParticleFunction, Particles, GpuParticles, type ParticleProgram, type ParticleProgramBinding, type VolumeBinding, type VolumeFunction, VolumeMesh, type DensityGrid, type GridProgram, type GridProgramBinding, ProceduralMesh, ProceduralGeometry,- DataTexture, PerspectiveCamera, PointLight, RectAreaLight, Scene, SkyAtmosphere, SkyColor, SkyGradient, SpotLight, Texture, trackChanges, vec3, takePhysicsCommands,+ DataTexture, StreamTexture, PerspectiveCamera, PointLight, RectAreaLight, Scene, SkyAtmosphere, SkyColor, SkyGradient, SpotLight, Texture, trackChanges, vec3, takePhysicsCommands,bindBody, unbindBody, usePhysicsEngine, physicsStepped, physicsBodies, Joint, getEngineBodies,type SceneChanges, type ShaderBinding, type SwayDesc, type PhysicsDesc, type BoundBody,} from "./core.ts";@@ -145,6 +145,8 @@ export interface TextureDesc {uri?: string;/** The bytes are RGBA8 pixels of this size (DataTexture), not an encoded image. */size?: Vec2;+ /** The app replaces the pixels while the scene runs, under this name (StreamTexture). */+ stream?: string;srgb: boolean;wrap: boolean;repeat: Vec2;@@ -1134,7 +1136,7 @@ export class SceneBinding {this.textures.set(t, id);t.needsUpdate = false;const raw = t instanceof DataTexture;- const desc: TextureDesc = { ...(raw || t.data ? {} : { uri: t.uri }), ...(raw ? { size: [t.width, t.height] as Vec2 } : {}), srgb: t.colorSpace === "srgb", wrap: t.wrap !== "clamp", repeat: [...t.repeat], offset: [...t.offset] };+ const desc: TextureDesc = { ...(raw || t.data ? {} : { uri: t.uri }), ...(raw ? { size: [t.width, t.height] as Vec2 } : {}), ...(t instanceof StreamTexture ? { stream: t.stream } : {}), srgb: t.colorSpace === "srgb", wrap: t.wrap !== "clamp", repeat: [...t.repeat], offset: [...t.offset] };this.engine.texture(id, desc, raw ? t.pixels : (t.data ?? null));}return id;diff --git a/renderer/src/api.rs b/renderer/src/api.rsindex 655b483..6e1f528 100644--- a/renderer/src/api.rs+++ b/renderer/src/api.rs@@ -144,7 +144,11 @@ pub fn texture(w: &mut World, id: u32, j: &Value, data: Option<&[u8]>) -> Resultif bytes.len() != width as usize * height as usize * 4 {return Err(Error::Type(format!("engine.texture: {} bytes are not {width}x{height} RGBA8 pixels", bytes.len())));}- TextureSource::Pixels { width, height, rgba: Arc::new(bytes.to_vec()) }+ match j["stream"].as_str() {+ Some(name) if !name.is_empty() && name.len() <= 64 && !name.contains('|') => TextureSource::Stream { name: name.to_string(), width, height, rgba: Arc::new(bytes.to_vec()) },+ Some(name) => return Err(Error::Type(format!("engine.texture: a stream's name is 1 to 64 characters without '|', not {name:?}"))),+ None => TextureSource::Pixels { width, height, rgba: Arc::new(bytes.to_vec()) },+ }}(Some(bytes), _) => TextureSource::Encoded(Arc::new(bytes.to_vec())),(None, Some(uri)) => TextureSource::File(uri.to_string()),diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex 595e066..7702476 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -7,6 +7,17 @@ use anyhow::{anyhow, Result};use web_time::Instant;use wgpu::util::DeviceExt;+/// The uploaded texture pages of a texture set (texpack.rs).+struct Pages {+ /// `texpack::set_key` of the set.+ key: u64,+ texture: wgpu::Texture,+ view: wgpu::TextureView,+ info: std::sync::Arc<Vec<[f32; 4]>>,+ /// Stream textures by name: where their pixels go (`Gpu::write_stream`).+ streams: Vec<(String, crate::texpack::Place)>,+}+pub struct Gpu {pub instance: wgpu::Instance,pub adapter: wgpu::Adapter,@@ -56,7 +67,9 @@ pub struct Gpu {/// Hardware ray queries (Metal / Vulkan RT). Software BVH traversal otherwise.pub hwrt: bool,/// Last uploaded texture pages, reused while the scene's texture set is unchanged (live edits re-upload often).- pages: std::sync::Mutex<Option<(u64, wgpu::TextureView, std::sync::Arc<Vec<[f32; 4]>>)>>,+ pages: std::sync::Mutex<Option<Pages>>,+ /// The last picture of each stream texture (`write_stream`), kept for pages that are packed again.+ streams: std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<image::RgbaImage>>>,/// The translucency pass (hardware RT): group 2's layout (translucent.wgsl), the kernel layout with it, and its/// pipelines (`translucent`, `volume_train`) by the kernel's variant key.tl_layout: Option<wgpu::BindGroupLayout>,@@ -1906,7 +1919,7 @@ impl Gpu {} else {(None, None, None, None)};- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })+ Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })}/// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).@@ -2094,9 +2107,9 @@ impl Gpu {fn texture_pages(&self, scene: &Scene, timings: &mut Vec<(String, f64)>) -> (wgpu::TextureView, std::sync::Arc<Vec<[f32; 4]>>) {let key = crate::texpack::set_key(&scene.textures);let mut cache = self.pages.lock().unwrap();- if let Some((k, view, info)) = cache.as_ref() {- if *k == key {- return (view.clone(), info.clone());+ if let Some(p) = cache.as_ref() {+ if p.key == key {+ return (p.view.clone(), p.info.clone());}}let t = Instant::now();@@ -2125,11 +2138,48 @@ impl Gpu {}let view = tex.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });let info = std::sync::Arc::new(packed.info);+ // Streams show their last picture, not the one the scene was described with.+ let last = self.streams.lock().unwrap();+ for (name, place) in &packed.streams {+ if let Some(img) = last.get(name) {+ self.write_place(&tex, place, img);+ }+ }timings.push(("texture_pages_ms".into(), t.elapsed().as_secs_f64() * 1000.0));- *cache = Some((key, view.clone(), info.clone()));+ *cache = Some(Pages { key, texture: tex, view: view.clone(), info: info.clone(), streams: packed.streams });(view, info)}+ fn write_place(&self, pages: &wgpu::Texture, place: &crate::texpack::Place, img: &image::RgbaImage) {+ for l in crate::texpack::patch(place, img) {+ self.queue.write_texture(+ wgpu::TexelCopyTextureInfo { texture: pages, mip_level: l.level, origin: wgpu::Origin3d { x: l.x, y: l.y, z: place.layer }, aspect: wgpu::TextureAspect::All },+ &l.rgba,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(l.width * 4), rows_per_image: Some(l.height) },+ wgpu::Extent3d { width: l.width, height: l.height, depth_or_array_layers: 1 },+ );+ }+ }++ /// New pixels for the stream texture `name` (world.rs `TextureSource::Stream`): written into its place in the+ /// texture pages, every mip level, before the next frame's passes. Nothing of the scene is rebuilt. True when the+ /// uploaded scene has the stream; the picture is kept either way, for the pages a later scene packs.+ pub fn write_stream(&self, name: &str, width: u32, height: u32, rgba: &[u8]) -> Result<bool> {+ let img = image::RgbaImage::from_raw(width, height, rgba.to_vec()).ok_or_else(|| anyhow::anyhow!("stream {name}: {} bytes are not {width}x{height} RGBA8 pixels", rgba.len()))?;+ let img = std::sync::Arc::new(img);+ self.streams.lock().unwrap().insert(name.to_string(), img.clone());+ let cache = self.pages.lock().unwrap();+ let Some(pages) = cache.as_ref() else { return Ok(false) };+ let mut found = false;+ for (n, place) in &pages.streams {+ if n == name {+ self.write_place(&pages.texture, place, &img);+ found = true;+ }+ }+ Ok(found)+ }+/// Uploads a prepared scene (geometry, materials, textures, environment, acceleration structures) and returns the/// bind group used by both the offline and the live kernels. `accum` holds one 80-byte Pixel per output pixel.#[allow(clippy::too_many_arguments)]diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex d4d7344..99d4aaa 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -682,6 +682,13 @@ impl LiveCore {self.reset = true;}+ /// The next picture of a stream texture (a material's `StreamTexture`, by its name): a screen in the scene shows+ /// what the app draws. The pixels go into the texture's place; the scene and the history stay. True when the+ /// scene has the stream.+ pub fn write_stream(&mut self, name: &str, width: u32, height: u32, rgba: &[u8]) -> Result<bool> {+ self.g.write_stream(name, width, height, rgba)+ }+/// Ray tracing on or off (see `rays`). The history starts over: the two modes light a pixel differently.pub fn set_rays(&mut self, on: bool) {if self.rays != on {diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 573e9ff..e5030c0 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -917,6 +917,12 @@ fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<imagelet key = bytes_key(&format!("pixels{width}x{height}"), rgba);Ok((key.clone(), cached_image(&key, || image::RgbaImage::from_raw(*width, *height, rgba.to_vec()).context("generated texture: size does not match the pixels"))?))}+ // A stream's identity is its name and size, whatever its pixels: the pages keep its place (texpack.rs+ // `stream_name`), and the app's pictures go straight into it (gpu.rs `write_stream`).+ world::TextureSource::Stream { name, width, height, rgba } => {+ let image = image::RgbaImage::from_raw(*width, *height, rgba.to_vec()).context("stream texture: size does not match the pixels")?;+ Ok((crate::texpack::stream_key(name, *width, *height), Arc::new(image)))+ }}}diff --git a/renderer/src/texpack.rs b/renderer/src/texpack.rsindex 82b2494..46a34e9 100644--- a/renderer/src/texpack.rs+++ b/renderer/src/texpack.rs@@ -19,6 +19,68 @@ pub struct Packed {pub layers: Vec<Vec<image::RgbaImage>>,/// Per texture two vec4: (u0, v0, du, dv) of the content rect in page UV; (layer, wrap, width, height).pub info: Vec<[f32; 4]>,+ /// Where each stream texture (`stream_key`) sits, by name: its pixels are replaced in place (`patch`).+ pub streams: Vec<(String, Place)>,+}++/// A texture's padded rect in the pages (aligned to `ALIGN`, so its mips are its own) and its content's size.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Place {+ pub layer: u32,+ pub x: u32,+ pub y: u32,+ pub padded: (u32, u32),+ /// The content's size in the page: the texture's, or smaller (`pack` shrinks some).+ pub size: (u32, u32),+ pub wrap: bool,+}++/// The key of a stream texture (scene.rs `texture_image`): its name and size, not its pixels.+pub fn stream_key(name: &str, width: u32, height: u32) -> String {+ format!("stream:{name}|{width}x{height}")+}++/// The stream a texture key names, if it is one.+pub fn stream_name(key: &str) -> Option<&str> {+ key.strip_prefix("stream:")?.split('|').next()+}++/// One level of a patch: the rect to write in a page's level, and its RGBA8 texels.+pub struct PatchLevel {+ pub level: u32,+ pub x: u32,+ pub y: u32,+ pub width: u32,+ pub height: u32,+ pub rgba: Vec<u8>,+}++/// New pixels for a placed texture: its padded rect (the content, the gutters filled as `pack` fills them) at every+/// level. `img` is resized to the place's content size when it has another.+pub fn patch(place: &Place, img: &image::RgbaImage) -> Vec<PatchLevel> {+ let resized;+ let img = if img.dimensions() == place.size {+ img+ } else {+ resized = resize_triangle(img, place.size.0, place.size.1);+ &resized+ };+ let (w, h) = (img.width() as i64, img.height() as i64);+ let (pw, ph) = place.padded;+ let fold = |v: i64, n: i64| if place.wrap { v.rem_euclid(n) } else { v.clamp(0, n - 1) } as usize;+ let src: &[u32] = bytemuck::cast_slice(img.as_raw());+ let mut level0 = vec![0u32; (pw * ph) as usize];+ let g = GUTTER as i64;+ let cols: Vec<usize> = (0..pw as i64).map(|x| fold(x - g, w)).collect();+ level0.par_chunks_mut(pw as usize).enumerate().for_each(|(row, dst)| {+ let sy = fold(row as i64 - g, h);+ let src_row = &src[sy * w as usize..(sy + 1) * w as usize];+ for (o, &sx) in dst.iter_mut().zip(&cols) {+ *o = src_row[sx];+ }+ });+ let chain = mip_chain(image::RgbaImage::from_raw(pw, ph, bytemuck::cast_slice(&level0).to_vec()).unwrap());+ chain.into_iter().enumerate().map(|(l, i)| PatchLevel { level: l as u32, x: place.x >> l, y: place.y >> l, width: i.width(), height: i.height(), rgba: i.into_raw() }).collect()}fn round_up(v: u32) -> u32 {@@ -28,7 +90,7 @@ fn round_up(v: u32) -> u32 {pub fn pack(textures: &[Texture]) -> Packed {if textures.is_empty() {let img = image::RgbaImage::from_pixel(ALIGN, ALIGN, image::Rgba([255, 255, 255, 255]));- return Packed { side: ALIGN, layers: vec![mip_chain(img)], info: vec![[0.0; 4], [0.0; 4]] };+ return Packed { side: ALIGN, layers: vec![mip_chain(img)], info: vec![[0.0; 4], [0.0; 4]], streams: vec![] };}// Power-of-two textures >= 512 give up 2 x GUTTER texels so the padded rect stays a power of two and four// 2048s (or sixteen 1024s) fill a page exactly; anything else keeps its size and is padded.@@ -119,7 +181,15 @@ pub fn pack(textures: &[Texture]) -> Packed {image::RgbaImage::from_raw(side, side, bytemuck::cast_slice(&page).to_vec()).unwrap()}).collect();- Packed { side, layers: pages.into_par_iter().map(mip_chain).collect(), info }+ let streams = textures+ .iter()+ .enumerate()+ .filter_map(|(i, t)| {+ let (layer, x, y) = place[i];+ Some((stream_name(&t.key)?.to_string(), Place { layer, x, y, padded: padded[i], size: src[i].dimensions(), wrap: t.wrap }))+ })+ .collect();+ Packed { side, layers: pages.into_par_iter().map(mip_chain).collect(), info, streams }}/// 2x2 box-filtered chain (sRGB-encoded texels are averaged as stored, like most engines' default mip gen).@@ -249,6 +319,36 @@ mod tests {}}+ /// A stream's patch is what `pack` would have put there for the same pixels: every level of its padded rect.+ #[test]+ fn a_patch_is_the_pages_texels() {+ let other = tex(300, 200, true, |x, y| [(x % 251) as u8, (y % 241) as u8, 9, 255]);+ let stream = |f: fn(u32, u32) -> [u8; 4]| {+ let mut t = tex(640, 360, false, f);+ t.key = format!("{}|true|false", stream_key("screen", 640, 360));+ t+ };+ let first = pack(&[other, stream(|_, _| [0, 0, 0, 255])]);+ let picture: fn(u32, u32) -> [u8; 4] = |x, y| [(x % 256) as u8, (y % 256) as u8, ((x * 7 + y * 3) % 256) as u8, 255];+ let want = pack(&[tex(300, 200, true, |x, y| [(x % 251) as u8, (y % 241) as u8, 9, 255]), stream(picture)]);+ assert_eq!(first.streams.len(), 1);+ let (name, place) = &first.streams[0];+ assert_eq!(name, "screen");+ assert_eq!(*place, want.streams[0].1);+ assert_eq!((place.x % ALIGN, place.y % ALIGN, place.padded.0 % ALIGN, place.padded.1 % ALIGN), (0, 0, 0, 0));+ let levels = patch(place, &stream(picture).rgba);+ assert_eq!(levels.len() as u32, MIPS);+ for l in &levels {+ let page = &want.layers[place.layer as usize][l.level as usize];+ for y in 0..l.height {+ for x in 0..l.width {+ let o = ((y * l.width + x) * 4) as usize;+ assert_eq!(&l.rgba[o..o + 4], &page.get_pixel(l.x + x, l.y + y).0, "level {} at {x},{y}", l.level);+ }+ }+ }+ }+#[test]fn rects_gutters_and_mips() {// 1024 (pow2 >= 512: shrinks by 2 x GUTTER), a 100x60 clamped texture, a 300x200 wrapped one.diff --git a/renderer/src/world.rs b/renderer/src/world.rsindex aec1fac..272c5b4 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -108,6 +108,10 @@ pub enum TextureSource {Encoded(Arc<Vec<u8>>),/// RGBA8 pixels generated by the scene code.Pixels { width: u32, height: u32, rgba: Arc<Vec<u8>> },+ /// RGBA8 pixels the app replaces while the scene runs, under a name (`LiveCore::write_stream`: a screen, a+ /// camera, a video). `rgba` is the picture until the first one arrives. Its place in the texture pages is its+ /// name and size, so new pixels rebuild nothing.+ Stream { name: String, width: u32, height: u32, rgba: Arc<Vec<u8>> },}#[derive(Clone, Debug)]@@ -1191,7 +1195,7 @@ impl World {});let textures = self.textures.values().filter_map(|t| match &t.source {TextureSource::File(uri) => Some(uri.clone()),- TextureSource::Encoded(_) | TextureSource::Pixels { .. } => None,+ TextureSource::Encoded(_) | TextureSource::Pixels { .. } | TextureSource::Stream { .. } => None,});let procs = self.proc_geometries.values().filter_map(|g| match &g.source {ProcSource::Asset(uri) => Some(uri.clone()),