Skip to content

programmatic video rendering framework that is actually fast

feat(fframes_three_d): textures of images that stay on the GPU

Dmitriy Kovalenkodf8d76bc9679
diff --git a/Cargo.lock b/Cargo.lock
index 5ce5802c..f5a2c909 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1326,6 +1326,7 @@ dependencies = [
"glam",
"gltf",
"image",
+ "lru",
"png 0.17.16",
"pollster",
"rayon",
diff --git a/fframes-media/src/images.rs b/fframes-media/src/images.rs
index 63289c27..59dbc9df 100644
--- a/fframes-media/src/images.rs
+++ b/fframes-media/src/images.rs
@@ -169,6 +169,39 @@ impl<'a> ImageData<'a> {
}
}
+/// An image of premultiplied RGBA pixels, `width * 4` bytes per row. Each image gets a new
+/// id, so a cache keyed by the id never returns an old image.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn rendered_image(width: u32, height: u32, rgba: Vec<u8>) -> ImageData<'static> {
+ use std::sync::atomic::{AtomicU64, Ordering};
+
+ static NEXT_ID: AtomicU64 = AtomicU64::new(0);
+ let id = format!("fframes-svgr:{}", NEXT_ID.fetch_add(1, Ordering::Relaxed));
+ ImageData::new_from_raw_data(
+ Arc::new(usvgr::PreloadedImageData {
+ data: Cow::Owned(rgba),
+ width,
+ height,
+ id: id.clone(),
+ }),
+ id,
+ ImageMetadata { width, height },
+ )
+}
+
+/// The pixels of `image`. An image on the GPU (`fframes::wgpu_layer`) is read back, which
+/// waits for the GPU. `None` when that fails. Other images are their own pixels.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn image_pixels(
+ image: &Arc<usvgr::PreloadedImageData>,
+) -> Option<Arc<usvgr::PreloadedImageData>> {
+ #[cfg(feature = "wgpu")]
+ if let Some(layer) = crate::wgpu_layer::resolve_wgpu_layer(image) {
+ return layer.pixels();
+ }
+ Some(Arc::clone(image))
+}
+
#[cfg(not(target_arch = "wasm32"))]
pub fn decode_image(
filename: &str,
diff --git a/fframes-three-d/Cargo.toml b/fframes-three-d/Cargo.toml
index 9f3384ad..e28f9a55 100644
--- a/fframes-three-d/Cargo.toml
+++ b/fframes-three-d/Cargo.toml
@@ -28,6 +28,8 @@ ttf-parser = "0.25.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
usvgr.workspace = true
+# The mipmap levels of images that several textures share.
+lru = "0.18.5"
# The `gpu` feature only.
wgpu = { version = "30", optional = true, default-features = false, features = ["std", "parking_lot", "wgsl", "vulkan", "metal", "dx12"] }
pollster = { version = "1", optional = true }
diff --git a/fframes-three-d/src/gpu/mip.wgsl b/fframes-three-d/src/gpu/mip.wgsl
new file mode 100644
index 00000000..2d5bee5f
--- /dev/null
+++ b/fframes-three-d/src/gpu/mip.wgsl
@@ -0,0 +1,44 @@
+// The mipmap levels of a material texture from an image on the GPU (an svgr image or a 3D
+// render). They follow `levels_of_premultiplied` and `downsample` in `texture.rs`. The
+// target is an sRGB level, so the shaders return linear colors.
+
+@group(0) @binding(0) var src: texture_2d<f32>;
+
+@vertex
+fn vs_fullscreen(@builtin(vertex_index) index: u32) -> @builtin(position) vec4f {
+ let uv = vec2f(f32((index << 1u) & 2u), f32(index & 2u));
+ return vec4f(uv * 2.0 - 1.0, 0.0, 1.0);
+}
+
+fn to_linear(c: f32) -> f32 {
+ if c <= 0.04045 {
+ return c / 12.92;
+ }
+ return pow((c + 0.055) / 1.055, 2.4);
+}
+
+// Level 0: the premultiplied sRGB texels of the image with straight alpha, rounded like
+// on the CPU.
+@fragment
+fn fs_level0(@builtin(position) position: vec4f) -> @location(0) vec4f {
+ let texel = round(textureLoad(src, vec2i(position.xy), 0) * 255.0);
+ var rgb = texel.rgb;
+ if texel.a > 0.0 && texel.a < 255.0 {
+ rgb = min(floor(rgb * 255.0 / texel.a), vec3f(255.0));
+ }
+ let c = rgb / 255.0;
+ return vec4f(to_linear(c.r), to_linear(c.g), to_linear(c.b), texel.a / 255.0);
+}
+
+// The next level: each texel is the mean of four texels of the level before, in linear
+// light. The level before is an sRGB view, so its texels load as linear.
+@fragment
+fn fs_down(@builtin(position) position: vec4f) -> @location(0) vec4f {
+ let last = vec2i(textureDimensions(src)) - 1;
+ let base = vec2i(position.xy) * 2;
+ var sum = vec4f(0.0);
+ for (var i = 0; i < 4; i++) {
+ sum += textureLoad(src, min(base + vec2i(i & 1, i >> 1), last), 0);
+ }
+ return sum / 4.0;
+}
diff --git a/fframes-three-d/src/gpu/mod.rs b/fframes-three-d/src/gpu/mod.rs
index e5ead9c2..07b3a1c1 100644
--- a/fframes-three-d/src/gpu/mod.rs
+++ b/fframes-three-d/src/gpu/mod.rs
@@ -317,7 +317,7 @@ struct GpuMesh {
}
struct GpuTexture {
- source: Weak<Texture>,
+ source: Weak<crate::texture::Levels>,
view: wgpu::TextureView,
}
@@ -338,6 +338,8 @@ pub(crate) struct Gpu {
queue: wgpu::Queue,
/// The queue lock of the backend, when the backend shares the device.
queue_lock: Option<Arc<Mutex<()>>>,
+ /// The [`SharedGpu::id`] of the device, when the backend shares it.
+ shared_id: Option<u64>,
scene_module: wgpu::ShaderModule,
frame_layout: wgpu::BindGroupLayout,
draw_layout: wgpu::BindGroupLayout,
@@ -353,6 +355,10 @@ pub(crate) struct Gpu {
particle_additive: wgpu::RenderPipeline,
particle_normal: wgpu::RenderPipeline,
post: PostPipelines,
+ /// Make the mipmap levels of an image on the GPU, see `mip.wgsl`.
+ mip_layout: wgpu::BindGroupLayout,
+ mip_level0: wgpu::RenderPipeline,
+ mip_down: wgpu::RenderPipeline,
linear_repeat: wgpu::Sampler,
linear_clamp: wgpu::Sampler,
env_sampler: wgpu::Sampler,
@@ -528,7 +534,7 @@ fn shared_gpu() -> Option<(SharedGpu, Arc<Gpu>)> {
Gpu::with_device(
shared.device().clone(),
shared.queue().clone(),
- Some(shared.queue_lock()),
+ Some((shared.queue_lock(), shared.id())),
)
});
Some((shared, gpu))
@@ -603,13 +609,14 @@ impl Gpu {
Ok(Self::with_device(device, queue, None))
}
- /// The renderer on `device`. When the backend shares the queue, the renderer holds
- /// `queue_lock` while it submits.
+ /// The renderer on `device`. When the backend shares the device, `shared` is its queue
+ /// lock and its [`SharedGpu::id`]. The renderer holds the lock while it submits.
fn with_device(
device: wgpu::Device,
queue: wgpu::Queue,
- queue_lock: Option<Arc<Mutex<()>>>,
+ shared: Option<(Arc<Mutex<()>>, u64)>,
) -> Gpu {
+ let (queue_lock, shared_id) = shared.unzip();
let scene_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("scene"),
source: wgpu::ShaderSource::Wgsl(include_str!("scene.wgsl").into()),
@@ -849,6 +856,34 @@ impl Gpu {
encode: post_pipeline("fs_encode", &[Some(OUTPUT.into())]),
};
+ let mip_module = device.create_shader_module(wgpu::include_wgsl!("mip.wgsl"));
+ let mip_layout = bind_group_layout("mip", &[float_2d(0)]);
+ let mip_pipeline_layout = pipeline_layout("mip", &[Some(&mip_layout)]);
+ let mip_pipeline = |entry: &str| {
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some(entry),
+ layout: Some(&mip_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &mip_module,
+ entry_point: Some("vs_fullscreen"),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ buffers: &[],
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &mip_module,
+ entry_point: Some(entry),
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ targets: &[Some(wgpu::TextureFormat::Rgba8UnormSrgb.into())],
+ }),
+ multiview_mask: None,
+ cache: None,
+ })
+ };
+ let (mip_level0, mip_down) = (mip_pipeline("fs_level0"), mip_pipeline("fs_down"));
+
let linear = |address_mode_u, address_mode_v, anisotropy_clamp| {
device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u,
@@ -902,9 +937,13 @@ impl Gpu {
wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
),
post,
+ mip_layout,
+ mip_level0,
+ mip_down,
device,
queue,
queue_lock,
+ shared_id,
scene_module,
frame_layout,
draw_layout,
@@ -1028,14 +1067,31 @@ impl Gpu {
)
}
- /// The view of a material texture with its mipmaps, uploaded on first use.
+ /// The view of a material texture with its mipmaps, made on first use. Textures that
+ /// share their levels share the view.
fn texture(&self, texture: &Arc<Texture>) -> wgpu::TextureView {
- let key = (Arc::as_ptr(texture) as usize, texture.srgb);
+ let levels = texture.shared_levels();
+ let key = (Arc::as_ptr(levels) as usize, texture.srgb);
let mut textures = lock(&self.textures);
if let Some(t) = textures.get(&key) {
return t.view.clone();
}
textures.retain(|_, t| t.source.strong_count() > 0);
+ let on_this_gpu =
+ (levels.layer()).filter(|layer| texture.srgb && Some(layer.gpu_id()) == self.shared_id);
+ let view = match on_this_gpu {
+ Some(layer) => self.mipmaps(layer.texture()),
+ None => self.upload(texture),
+ };
+ let entry = textures.entry(key).or_insert(GpuTexture {
+ source: Arc::downgrade(levels),
+ view,
+ });
+ entry.view.clone()
+ }
+
+ /// Uploads the mipmap levels that the texture made on the CPU.
+ fn upload(&self, texture: &Texture) -> wgpu::TextureView {
let format = if texture.srgb {
wgpu::TextureFormat::Rgba8UnormSrgb
} else {
@@ -1060,11 +1116,48 @@ impl Gpu {
bytemuck::cast_slice(texels),
);
}
- let entry = textures.entry(key).or_insert(GpuTexture {
- source: Arc::downgrade(texture),
- view: gpu_texture.create_view(&wgpu::TextureViewDescriptor::default()),
+ gpu_texture.create_view(&wgpu::TextureViewDescriptor::default())
+ }
+
+ /// A color texture with the mipmap levels of `image` (premultiplied sRGB on this
+ /// device), made on the GPU like the CPU makes them. The image does not leave the GPU.
+ fn mipmaps(&self, image: &wgpu::Texture) -> wgpu::TextureView {
+ let (width, height) = (image.width(), image.height());
+ let texture = self.device.create_texture(&wgpu::TextureDescriptor {
+ mip_level_count: width.max(height).ilog2() + 1,
+ ..texture_desc(
+ "material texture",
+ width,
+ height,
+ wgpu::TextureFormat::Rgba8UnormSrgb,
+ wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ )
});
- entry.view.clone()
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ let mut source = image.create_view(&wgpu::TextureViewDescriptor::default());
+ for level in 0..texture.mip_level_count() {
+ let target = texture.create_view(&wgpu::TextureViewDescriptor {
+ base_mip_level: level,
+ mip_level_count: Some(1),
+ ..Default::default()
+ });
+ let group = self.bind_group(
+ "mip",
+ &self.mip_layout,
+ &[wgpu::BindingResource::TextureView(&source)],
+ );
+ let pipeline = if level == 0 {
+ &self.mip_level0
+ } else {
+ &self.mip_down
+ };
+ fullscreen(&mut encoder, pipeline, &[&group], &[&target], None);
+ source = target;
+ }
+ self.submit(encoder.finish());
+ texture.create_view(&wgpu::TextureViewDescriptor::default())
}
/// The view and the level count of an environment panorama, uploaded on first use.
diff --git a/fframes-three-d/src/lib.rs b/fframes-three-d/src/lib.rs
index 7ef0fe9d..00c017a2 100644
--- a/fframes-three-d/src/lib.rs
+++ b/fframes-three-d/src/lib.rs
@@ -21,6 +21,11 @@
//! this with its `wgpu` feature. [`Renderer::render`] then renders on that device into a
//! texture that Skia draws. The 3D image stays on the GPU until the encoder.
//!
+//! A texture can show fframes content: [`Texture::from_image`] of
+//! `ctx.render_svgr(svgr, width, height)` puts an svgr tree on a surface, and a 3D render is
+//! an image for the next svgr tree. So svgr and 3D nest to any depth. On the shared GPU the
+//! svgr image stays a texture too, and the GPU makes its mipmap levels.
+//!
//! Units are meters and radians. Colors as hex numbers or `&str` are sRGB.
//!
//! # Example
@@ -77,12 +82,16 @@
//! | `GLTFLoader` + `AnimationMixer` | [`Model::from_gltf`] + [`ModelInstance::play`] |
//! | `STLLoader`, `toCreasedNormals` | [`Geometry::from_stl`], [`Geometry::smooth`] |
//! | `VideoTexture` | [`Texture::from_image`] of a decoded video frame, for each frame |
+//! | `CanvasTexture` | [`Texture::from_image`] of `ctx.render_svgr(svgr, width, height)` |
//! | `UnrealBloomPass`, `ACESFilmicToneMapping` | [`Bloom`], [`ToneMapping`] |
//! | `Points` | [`Node::particles`] |
//! | `InstancedMesh`, `instanceColor` | [`Node::instanced`] with [`Instances`] |
// Colors are hex numbers as in three.js: `0xff8800`.
#![allow(clippy::unreadable_literal)]
+// A texture can hold a wgpu texture. Proving that a texture is `Sync` goes deep into the
+// types of wgpu in release builds.
+#![recursion_limit = "256"]
// Rasterization and mesh generation index several parallel arrays in one loop.
#![allow(clippy::needless_range_loop, clippy::items_after_statements)]
diff --git a/fframes-three-d/src/texture.rs b/fframes-three-d/src/texture.rs
index ec032eb0..4db46c68 100644
--- a/fframes-three-d/src/texture.rs
+++ b/fframes-three-d/src/texture.rs
@@ -1,4 +1,4 @@
-use std::sync::OnceLock;
+use std::sync::{Arc, OnceLock};
use glam::{Vec2, Vec4};
@@ -7,14 +7,16 @@ use crate::color::{linear_to_srgb, srgb_to_linear};
/// An RGBA8 image that materials sample. The image repeats outside `0..1`. Sampling is
/// trilinear between mipmap levels that match the pixel footprint, so fine detail (floor
-/// tiles, text) does not shimmer.
+/// tiles, text) does not shimmer. Clones share the image.
#[derive(Clone)]
pub struct Texture {
pub width: u32,
pub height: u32,
- /// Mipmap levels. Level 0 is the image. Each next level has half the size, down to one
- /// texel.
- levels: Vec<Level>,
+ levels: Arc<Levels>,
+ /// The image the texture comes from. While it lives, the backend does not draw into its
+ /// texture on the GPU again, see [`Levels::layer`].
+ #[cfg(not(target_arch = "wasm32"))]
+ _image: Option<Arc<usvgr::PreloadedImageData>>,
/// True for color data. The texture keeps it as sRGB and converts it to linear when it
/// samples it. False for linear data such as metalness and roughness.
pub srgb: bool,
@@ -24,6 +26,37 @@ pub struct Texture {
pub offset: Vec2,
}
+/// The mipmap levels of a texture. Level 0 is the image. Each next level has half the size,
+/// down to one texel.
+pub(crate) struct Levels {
+ cpu: OnceLock<Vec<Level>>,
+ /// The width and the height of level 0.
+ size: (u32, u32),
+ /// The texture on the GPU that the image is (feature `gpu`): an svgr image or a 3D
+ /// render that stays on the GPU. The GPU renderer makes the levels from it on the GPU.
+ /// The CPU levels are its pixels, read back on first use. It is weak: the layer and its
+ /// device go with the image and with the backend.
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ layer: Option<std::sync::Weak<fframes_media::wgpu_layer::WgpuLayer>>,
+}
+
+impl Levels {
+ fn cpu(levels: Vec<Level>) -> Arc<Self> {
+ Arc::new(Self {
+ size: (levels[0].width, levels[0].height),
+ cpu: OnceLock::from(levels),
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ layer: None,
+ })
+ }
+
+ /// The texture on the GPU that the levels come from.
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ pub(crate) fn layer(&self) -> Option<Arc<fframes_media::wgpu_layer::WgpuLayer>> {
+ self.layer.as_ref()?.upgrade()
+ }
+}
+
#[derive(Clone)]
struct Level {
width: u32,
@@ -37,7 +70,7 @@ impl std::fmt::Debug for Texture {
.field("width", &self.width)
.field("height", &self.height)
.field("srgb", &self.srgb)
- .field("levels", &self.levels.len())
+ .field("levels", &self.cpu_levels().len())
.finish_non_exhaustive()
}
}
@@ -71,28 +104,37 @@ impl Texture {
))
}
- /// A color texture from an fframes image: a media file, a decoded video frame, or a
- /// rendered frame of another video. Use a new texture for each frame of a video, so a
- /// screen in the scene plays it. Resize large frames first (`into_resized_image`), because
- /// the texture makes its mipmap levels on the CPU.
+ /// A color texture from an fframes image: a media file, a decoded video frame, a
+ /// rendered frame of another video, an svgr tree from `ctx.render_svgr`, or a 3D render.
+ /// Use a new texture for each frame of a video, so a screen in the scene plays it.
+ ///
+ /// The texture makes its mipmap levels on the CPU, once for each image: a texture of
+ /// the same image again (a static svgr tree, a media file) reuses them. Resize large
+ /// video frames first (`into_resized_image`). An image that stays on the GPU (an svgr
+ /// image or a 3D render on the Skia Vulkan backend with the `wgpu` feature) gets its
+ /// levels on the GPU with the `gpu` feature and does not leave the GPU.
#[cfg(not(target_arch = "wasm32"))]
pub fn from_image(image: &fframes_media::ImageData<'_>) -> Self {
let source = &image.image;
- // fframes keeps premultiplied alpha; the texture keeps straight alpha
- let rgba: Vec<u8> = source
- .data
- .as_chunks::<4>()
- .0
- .iter()
- .flat_map(|&[r, g, b, a]| match a {
- 0 | 255 => [r, g, b, a],
- _ => {
- let straight = |c: u8| (u32::from(c) * 255 / u32::from(a)).min(255) as u8;
- [straight(r), straight(g), straight(b), a]
- }
+ let levels = images::levels(source, || {
+ #[cfg(feature = "gpu")]
+ if let Some(layer) = fframes_media::wgpu_layer::resolve_wgpu_layer(source) {
+ return Arc::new(Levels {
+ cpu: OnceLock::new(),
+ layer: Some(Arc::downgrade(&layer)),
+ size: (layer.texture().width(), layer.texture().height()),
+ });
+ }
+ // an image on the GPU without the `gpu` feature is read back
+ Levels::cpu(match fframes_media::image_pixels(source) {
+ Some(pixels) => levels_of_premultiplied(&pixels, true),
+ None => transparent(),
})
- .collect();
- Self::from_rgba8(source.width, source.height, &rgba, true)
+ });
+ Self {
+ _image: Some(Arc::clone(source)),
+ ..Self::with_levels(levels, true)
+ }
}
/// Decodes a PNG, JPEG or WebP image of linear data: a normal, roughness, metalness or
@@ -144,32 +186,47 @@ impl Texture {
}
fn from_level(level: Level, srgb: bool) -> Self {
- let (width, height) = (level.width, level.height);
- let mut levels = vec![level];
- while let Some(last) = levels.last()
- && (last.width > 1 || last.height > 1)
- {
- let next = downsample(last, srgb);
- levels.push(next);
- }
+ Self::with_levels(Levels::cpu(mip_chain(level, srgb)), srgb)
+ }
+
+ fn with_levels(levels: Arc<Levels>, srgb: bool) -> Self {
Self {
- width,
- height,
+ width: levels.size.0,
+ height: levels.size.1,
levels,
+ #[cfg(not(target_arch = "wasm32"))]
+ _image: None,
srgb,
repeat: Vec2::ONE,
offset: Vec2::ZERO,
}
}
+ /// The mipmap levels. Clones of the texture share them.
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ pub(crate) fn shared_levels(&self) -> &Arc<Levels> {
+ &self.levels
+ }
+
/// The mipmap levels as width, height and RGBA8 texels, largest first.
#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
pub(crate) fn levels(&self) -> impl Iterator<Item = (u32, u32, &[[u8; 4]])> {
- self.levels
+ self.cpu_levels()
.iter()
.map(|l| (l.width, l.height, l.data.as_slice()))
}
+ /// The mipmap levels on the CPU. A texture on the GPU reads them back on first use.
+ fn cpu_levels(&self) -> &[Level] {
+ self.levels.cpu.get_or_init(|| {
+ #[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
+ if let Some(pixels) = self.levels.layer().and_then(|l| l.pixels()) {
+ return levels_of_premultiplied(&pixels, self.srgb);
+ }
+ transparent()
+ })
+ }
+
/// Sets how many times the texture repeats along U and V.
pub fn repeat(mut self, u: f32, v: f32) -> Self {
self.repeat = Vec2::new(u, v);
@@ -185,19 +242,20 @@ impl Texture {
/// half the size. Returns linear RGBA with straight alpha.
pub(crate) fn sample_lod(&self, uv: Vec2, lod: f32) -> Vec4 {
let uv = uv * self.repeat + self.offset;
- let max = (self.levels.len() - 1) as f32;
+ let levels = self.cpu_levels();
+ let max = (levels.len() - 1) as f32;
let lod = if lod.is_finite() {
lod.clamp(0.0, max)
} else {
0.0
};
let l0 = lod.floor() as usize;
- let a = self.bilinear(&self.levels[l0], uv);
+ let a = self.bilinear(&levels[l0], uv);
let f = lod - l0 as f32;
- if f < 1e-3 || l0 + 1 >= self.levels.len() {
+ if f < 1e-3 || l0 + 1 >= levels.len() {
return a;
}
- a.lerp(self.bilinear(&self.levels[l0 + 1], uv), f)
+ a.lerp(self.bilinear(&levels[l0 + 1], uv), f)
}
/// Anisotropic sample like the GPU sampler (`anisotropy_clamp` 8). `dx` and `dy` are the
@@ -239,6 +297,104 @@ impl Texture {
}
}
+/// One transparent texel, for an image that has no pixels to read.
+fn transparent() -> Vec<Level> {
+ vec![Level {
+ width: 1,
+ height: 1,
+ data: vec![[0; 4]],
+ }]
+}
+
+/// Level 0 and the levels below it.
+fn mip_chain(level: Level, srgb: bool) -> Vec<Level> {
+ let mut levels = vec![level];
+ while let Some(last) = levels.last()
+ && (last.width > 1 || last.height > 1)
+ {
+ let next = downsample(last, srgb);
+ levels.push(next);
+ }
+ levels
+}
+
+/// The levels of premultiplied pixels (how fframes keeps images). The texture keeps
+/// straight alpha.
+#[cfg(not(target_arch = "wasm32"))]
+fn levels_of_premultiplied(image: &usvgr::PreloadedImageData, srgb: bool) -> Vec<Level> {
+ let data = image
+ .data
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .map(|&[r, g, b, a]| match a {
+ 0 | 255 => [r, g, b, a],
+ _ => {
+ let straight = |c: u8| (u32::from(c) * 255 / u32::from(a)).min(255) as u8;
+ [straight(r), straight(g), straight(b), a]
+ }
+ })
+ .collect();
+ mip_chain(
+ Level {
+ width: image.width,
+ height: image.height,
+ data,
+ },
+ srgb,
+ )
+}
+
+/// The levels of the images that textures were made of, so that a texture of the same
+/// image again reuses them.
+#[cfg(not(target_arch = "wasm32"))]
+mod images {
+ use std::num::NonZeroUsize;
+ use std::sync::{Arc, Mutex, PoisonError, Weak};
+
+ use lru::LruCache;
+ use usvgr::PreloadedImageData;
+
+ use super::Levels;
+
+ /// Images that live for a whole render (media files) stay in the cache. This bounds
+ /// their memory.
+ const CAPACITY: NonZeroUsize = NonZeroUsize::new(32).unwrap();
+
+ type Entry = (Weak<PreloadedImageData>, Arc<Levels>);
+
+ static IMAGES: Mutex<Option<LruCache<usize, Entry>>> = Mutex::new(None);
+
+ /// The levels of `image`: the ones made before, or the ones `make` makes. The cache
+ /// holds the image weakly. The entry goes when the image is dropped.
+ pub(super) fn levels(
+ image: &Arc<PreloadedImageData>,
+ make: impl FnOnce() -> Arc<Levels>,
+ ) -> Arc<Levels> {
+ let key = Arc::as_ptr(image) as usize;
+ let found = {
+ let mut images = IMAGES.lock().unwrap_or_else(PoisonError::into_inner);
+ let images = images.get_or_insert_with(|| LruCache::new(CAPACITY));
+ let dead: Vec<usize> = (images.iter())
+ .filter(|(_, (image, _))| image.strong_count() == 0)
+ .map(|(key, _)| *key)
+ .collect();
+ for key in dead {
+ images.pop(&key);
+ }
+ images.get(&key).map(|(_, levels)| Arc::clone(levels))
+ };
+ // the levels are made without the lock, so other threads go on
+ found.unwrap_or_else(|| {
+ let levels = make();
+ (IMAGES.lock().unwrap_or_else(PoisonError::into_inner))
+ .get_or_insert_with(|| LruCache::new(CAPACITY))
+ .put(key, (Arc::downgrade(image), Arc::clone(&levels)));
+ levels
+ })
+ }
+}
+
/// Converts a stored texel to linear RGBA in `0..1`. `lut` converts sRGB color channels;
/// without it the texel is linear data. Alpha is always linear.
#[inline]
diff --git a/fframes-three-d/tests/gpu_images.rs b/fframes-three-d/tests/gpu_images.rs
new file mode 100644
index 00000000..d5846386
--- /dev/null
+++ b/fframes-three-d/tests/gpu_images.rs
@@ -0,0 +1,135 @@
+//! Textures from images that stay on the GPU (`fframes::wgpu_layer`: svgr images and 3D
+//! renders on the Skia Vulkan backend). The GPU makes their mipmap levels. A surface at a
+//! low angle shows them like the CPU levels of the same pixels.
+#![cfg(feature = "gpu")]
+#![allow(clippy::unreadable_literal)]
+
+use std::sync::{Arc, Mutex};
+
+use fframes_three_d::*;
+
+#[allow(dead_code)]
+mod common;
+
+const SIZE: u32 = 256;
+
+/// A device of its own, registered as the GPU of a backend.
+fn shared_gpu() -> Option<fframes_media::wgpu_layer::SharedGpu> {
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
+ let adapter =
+ pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
+ .ok()?;
+ let (device, queue) =
+ pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?;
+ let gpu = fframes_media::wgpu_layer::SharedGpu::new(device, queue, Arc::new(Mutex::new(())));
+ fframes_media::wgpu_layer::register_shared_gpu(&gpu);
+ Some(gpu)
+}
+
+/// Premultiplied stripes and text-like detail: black and white lines one texel wide, a red
+/// square, and a half transparent blue band.
+fn pixels() -> Vec<u8> {
+ let mut rgba = Vec::with_capacity((SIZE * SIZE * 4) as usize);
+ for y in 0..SIZE {
+ for x in 0..SIZE {
+ rgba.extend(match (x, y) {
+ (64..128, 64..128) => [255, 0, 0, 255],
+ (_, 192..224) => [0, 0, 128, 128],
+ _ if (x / 2 + y / 3) % 2 == 0 => [255, 255, 255, 255],
+ _ => [20, 20, 20, 255],
+ });
+ }
+ }
+ rgba
+}
+
+/// `rgba` as a texture on `gpu` that the backend would sample in place.
+fn layer(
+ gpu: &fframes_media::wgpu_layer::SharedGpu,
+ rgba: &[u8],
+) -> fframes_media::ImageData<'static> {
+ let texture = gpu.device().create_texture(&wgpu::TextureDescriptor {
+ label: Some("test image"),
+ size: wgpu::Extent3d {
+ width: SIZE,
+ height: SIZE,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: fframes_media::wgpu_layer::WGPU_LAYER_FORMAT,
+ usage: fframes_media::wgpu_layer::WGPU_LAYER_USAGE,
+ view_formats: &[],
+ });
+ gpu.queue().write_texture(
+ texture.as_image_copy(),
+ rgba,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(SIZE * 4),
+ rows_per_image: Some(SIZE),
+ },
+ texture.size(),
+ );
+ let mut encoder = gpu
+ .device()
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ fframes_media::wgpu_layer::finish_wgpu_layer(&mut encoder, &texture);
+ gpu.submit([encoder.finish()]);
+ fframes_media::wgpu_layer::wgpu_layer(gpu, &texture)
+}
+
+/// The image on a floor seen at a low angle, where the mipmap levels and the anisotropic
+/// filter decide what shows.
+fn floor(image: &fframes_media::ImageData<'_>) -> (Scene, Camera) {
+ let mut scene = Scene::new();
+ scene.add(Node::mesh(
+ Geometry::plane(4.0, 4.0).rotate_x(-std::f32::consts::FRAC_PI_2),
+ Material::unlit(0xffffff).map(Texture::from_image(image)),
+ ));
+ let camera = Camera::perspective(40.0)
+ .at(0.0, 0.6, 2.6)
+ .look_at(vec3(0.0, 0.0, -0.5));
+ (scene, camera)
+}
+
+#[test]
+fn images_on_the_gpu_get_the_mipmaps_of_the_cpu() {
+ let Some(gpu) = shared_gpu() else {
+ eprintln!("no GPU, skipped");
+ return;
+ };
+ let rgba = pixels();
+ let on_gpu = layer(&gpu, &rgba);
+ assert!(fframes_media::wgpu_layer::resolve_wgpu_layer(&on_gpu.href()).is_some());
+ let in_memory = fframes_media::rendered_image(SIZE, SIZE, rgba);
+
+ let renderer = Renderer::new(480, 270).tone_mapping(ToneMapping::Linear);
+ let (scene, camera) = floor(&on_gpu);
+ // the GPU makes the levels from the texture, the CPU from the pixels it reads back
+ let gpu_levels = renderer.render_pixels(&scene, &camera);
+ let read_back = renderer.clone().cpu().render_pixels(&scene, &camera);
+ let (scene, camera) = floor(&in_memory);
+ let cpu_levels = renderer.render_pixels(&scene, &camera);
+ let cpu = renderer.clone().cpu().render_pixels(&scene, &camera);
+ common::save("gpu_image_levels", &gpu_levels);
+ common::save("cpu_image_levels", &cpu);
+
+ let mean = |a: &Pixels, b: &Pixels| {
+ let sum: u64 = (a.rgba.iter().zip(&b.rgba))
+ .map(|(a, b)| u64::from(a.abs_diff(*b)))
+ .sum();
+ sum as f64 / a.rgba.len() as f64
+ };
+ assert_eq!(read_back.rgba, cpu.rgba, "the CPU reads the texture back");
+ let levels = mean(&gpu_levels, &cpu_levels);
+ let parity = mean(&gpu_levels, &cpu);
+ eprintln!("GPU levels against uploaded CPU levels {levels:.3}, against the CPU {parity:.3}");
+ assert!(levels < 0.1, "the GPU levels differ by {levels} on average");
+ // the samplers of the GPU and the CPU differ most on one texel lines at a low angle
+ assert!(
+ parity < 3.0,
+ "the GPU differs from the CPU by {parity} on average"
+ );
+}
diff --git a/fframes/src/svgr_image.rs b/fframes/src/svgr_image.rs
index e467c4a8..8e36b004 100644
--- a/fframes/src/svgr_image.rs
+++ b/fframes/src/svgr_image.rs
@@ -7,13 +7,12 @@
//! `Video::render_frame` ([`SvgrImages::enter`]). `render_svgr` uses the images that the
//! thread entered.
-use std::borrow::Cow;
use std::cell::Cell;
use std::num::NonZeroUsize;
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, Mutex, PoisonError};
+use std::sync::{Mutex, PoisonError};
-use crate::media::{ImageData, ImageMetadata};
+use crate::media::ImageData;
+pub use crate::media::{image_pixels, rendered_image};
use crate::{Svgr, usvgr};
/// The number of images of static trees that one render keeps.
@@ -149,32 +148,3 @@ fn static_hash(svgr: &Svgr<'_>) -> Option<u64> {
let _ = svgr;
None
}
-
-/// An image of premultiplied RGBA pixels, `width * 4` bytes per row. Each image gets a new
-/// id, so a cache keyed by the id never returns an old image.
-pub fn rendered_image(width: u32, height: u32, rgba: Vec<u8>) -> ImageData<'static> {
- static NEXT_ID: AtomicU64 = AtomicU64::new(0);
- let id = format!("fframes-svgr:{}", NEXT_ID.fetch_add(1, Ordering::Relaxed));
- ImageData::new_from_raw_data(
- Arc::new(usvgr::PreloadedImageData {
- data: Cow::Owned(rgba),
- width,
- height,
- id: id.clone(),
- }),
- id,
- ImageMetadata { width, height },
- )
-}
-
-/// The pixels of `image`. An image on the GPU (`fframes::wgpu_layer`) is read back, which
-/// waits for the GPU. `None` when that fails. Other images are their own pixels.
-pub fn image_pixels(
- image: &Arc<usvgr::PreloadedImageData>,
-) -> Option<Arc<usvgr::PreloadedImageData>> {
- #[cfg(feature = "wgpu")]
- if let Some(layer) = crate::resolve_wgpu_layer(image) {
- return layer.pixels();
- }
- Some(Arc::clone(image))
-}