1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//! Offscreen render target pool for effect layers.
//!
//! Provides reusable GPU textures that can be both rendered to (as a color
//! attachment) and sampled from (as a texture binding). Used by blur and
//! custom shader effects that need to capture a subtree's rendered output.
use crate::gpu_stats::FrameStats;
use std::cell::OnceCell;
/// A GPU texture that can serve as both a render target and a texture source.
pub(crate) struct OffscreenTarget {
// Texture kept alive for the view's lifetime; the view borrows from it implicitly.
texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub width: u32,
pub height: u32,
/// Lazily-cached bind group for sampling this target as a texture.
/// Valid as long as the underlying texture is alive (i.e. while this target exists).
cached_bind_group: OnceCell<wgpu::BindGroup>,
}
impl OffscreenTarget {
pub(crate) fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
width: u32,
height: u32,
) -> Self {
Self::new_labeled(device, format, width, height, "Offscreen Target")
}
pub(crate) fn new_labeled(
device: &wgpu::Device,
format: wgpu::TextureFormat,
width: u32,
height: u32,
label: &'static str,
) -> Self {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC
| wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
Self {
texture,
view,
width,
height,
cached_bind_group: OnceCell::new(),
}
}
/// Returns true if this target exactly matches the requested dimensions.
///
/// Effects rely on a 1:1 mapping between render target texels and viewport
/// coordinates, so larger pooled textures are not considered compatible.
fn matches_size(&self, width: u32, height: u32) -> bool {
self.width == width && self.height == height
}
/// Get the cached texture bind group, creating it on first access.
///
/// The bind group binds this target's texture view and the provided sampler
/// for use in effect fragment shaders. Since the underlying texture never
/// changes while this target is alive, the bind group is valid for reuse.
pub fn get_or_create_bind_group(
&self,
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
sampler: &wgpu::Sampler,
) -> &wgpu::BindGroup {
self.cached_bind_group.get_or_init(|| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Offscreen Texture Bind Group (cached)"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&self.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(sampler),
},
],
})
})
}
pub(crate) fn texture(&self) -> &wgpu::Texture {
&self.texture
}
}
/// Pool of reusable offscreen render targets.
///
/// Targets are returned to the pool after use and reused when a suitable size
/// is available, avoiding per-frame GPU texture allocation. Capped to prevent
/// unbounded GPU memory growth from accumulating targets of varying sizes.
pub(crate) struct OffscreenPool {
available: Vec<OffscreenTarget>,
format: wgpu::TextureFormat,
max_texture_dim: u32,
}
/// Maximum pooled targets. Each target is a GPU texture (4 bytes/pixel RGBA).
/// At 1920×1080 each is ~8 MB, so 16 targets ≈ 128 MB worst case.
const MAX_POOLED_TARGETS: usize = 16;
impl OffscreenPool {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
Self {
available: Vec::new(),
format,
max_texture_dim: device.limits().max_texture_dimension_2d,
}
}
#[cfg(test)]
fn new_with_limit(format: wgpu::TextureFormat, max_texture_dim: u32) -> Self {
Self {
available: Vec::new(),
format,
max_texture_dim,
}
}
/// Maximum texture dimension supported by the GPU.
pub fn max_texture_dim(&self) -> u32 {
self.max_texture_dim
}
/// Number of targets currently in the pool.
pub fn pool_size(&self) -> usize {
self.available.len()
}
/// Approximate GPU memory held by pooled targets (bytes).
pub fn estimated_bytes(&self) -> usize {
self.available
.iter()
.map(|t| (t.width as usize) * (t.height as usize) * 4)
.sum()
}
/// Acquire an offscreen target for the given dimensions.
///
/// Returns a pooled target when dimensions exactly match, otherwise creates
/// a new target for the requested size.
pub fn acquire(
&mut self,
device: &wgpu::Device,
width: u32,
height: u32,
stats: Option<&FrameStats>,
) -> OffscreenTarget {
let width = width.min(self.max_texture_dim).max(1);
let height = height.min(self.max_texture_dim).max(1);
if let Some(idx) = self
.available
.iter()
.position(|t| t.matches_size(width, height))
{
if let Some(s) = stats {
s.record_offscreen_acquire(width, height, false);
}
self.available.swap_remove(idx)
} else {
if let Some(s) = stats {
s.record_offscreen_acquire(width, height, true);
}
OffscreenTarget::new(device, self.format, width, height)
}
}
/// Return a target to the pool for future reuse.
///
/// Drops the target instead of pooling if the pool is already at capacity.
pub fn release(&mut self, target: OffscreenTarget) {
if self.available.len() < MAX_POOLED_TARGETS {
self.available.push(target);
}
// else: target is dropped, freeing GPU memory
}
/// The bind group layout for sampling offscreen textures.
///
/// Provides: `@group(N) @binding(0) var input_texture: texture_2d<f32>`
/// `@group(N) @binding(1) var input_sampler: sampler`
pub fn texture_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Effect Texture Bind Group Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
})
}
/// The bind group layout for RuntimeShader uniforms.
///
/// Provides: `@group(N) @binding(0) var<uniform> u: array<vec4<f32>, 64>`
pub fn uniform_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Effect Uniform Bind Group Layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pool_starts_empty() {
let pool = OffscreenPool::new_with_limit(wgpu::TextureFormat::Bgra8Unorm, 8192);
assert!(pool.available.is_empty());
assert_eq!(pool.pool_size(), 0);
}
#[test]
fn max_texture_dimension_stored() {
let pool = OffscreenPool::new_with_limit(wgpu::TextureFormat::Bgra8Unorm, 2048);
assert_eq!(pool.max_texture_dim, 2048);
let pool = OffscreenPool::new_with_limit(wgpu::TextureFormat::Bgra8Unorm, 4096);
assert_eq!(pool.max_texture_dim, 4096);
}
}