Skip to main content

sim_engine/renderer/
targets.rs

1//! Offscreen target ownership, presentation and temporal trail accumulation.
2
3use super::{
4    Arc, BlendMode, Color, CompositeUniform, Duration, Error, Instant, RenderReport, RenderStatus,
5    RendererFrameError, RendererSurfaceStatus, TessellationStats, WgpuRenderer, fmt,
6    premultiplied_wgpu_color, prepared_scene_belongs_to, render_report,
7    render_target_allocation_bytes,
8};
9
10/// A renderer-owned offscreen color target in physical texture pixels.
11///
12/// Targets preserve GPU pixels only; a host must redraw them after device
13/// recreation. Use the renderer's physical [`WgpuRenderer::size`] when a
14/// target should match the presentation surface exactly.
15pub struct RenderTarget2d {
16    pub(super) renderer_identity: Arc<()>,
17    pub(super) resource_identity: Arc<()>,
18    pub(super) _texture: wgpu::Texture,
19    pub(super) view: wgpu::TextureView,
20    pub(super) width: u32,
21    pub(super) height: u32,
22    pub(super) allocation_bytes: usize,
23}
24
25/// A pair of offscreen targets used for bounded temporal accumulation.
26///
27/// Each accumulation retains a caller-selected amount of the previous frame
28/// and then composites a distinct source target over it. The buffer owns no
29/// domain state and can therefore serve particles, scalar fields, or any later
30/// target-rendering producer.
31pub struct TrailBuffer2d {
32    renderer_identity: Arc<()>,
33    front: RenderTarget2d,
34    back: RenderTarget2d,
35}
36
37impl TrailBuffer2d {
38    /// Returns trail-buffer width in physical texture pixels.
39    pub fn width(&self) -> u32 {
40        self.front.width()
41    }
42
43    /// Returns trail-buffer height in physical texture pixels.
44    pub fn height(&self) -> u32 {
45        self.front.height()
46    }
47
48    /// Returns trail-buffer physical dimensions.
49    pub fn size(&self) -> (u32, u32) {
50        self.front.size()
51    }
52
53    /// Returns nominal texel-storage bytes for both ping-pong textures.
54    pub fn allocation_bytes(&self) -> usize {
55        self.front
56            .allocation_bytes()
57            .saturating_add(self.back.allocation_bytes())
58    }
59}
60
61impl RenderTarget2d {
62    /// Returns target width in physical texture pixels.
63    pub fn width(&self) -> u32 {
64        self.width
65    }
66
67    /// Returns target height in physical texture pixels.
68    pub fn height(&self) -> u32 {
69        self.height
70    }
71
72    /// Returns the physical texture dimensions.
73    pub fn size(&self) -> (u32, u32) {
74        (self.width, self.height)
75    }
76
77    /// Returns nominal single-level texel-storage bytes implied by its format.
78    /// Backend row/tile/page alignment and resource metadata are not observable
79    /// through wgpu and are therefore excluded.
80    pub fn allocation_bytes(&self) -> usize {
81        self.allocation_bytes
82    }
83}
84
85/// Failure while creating or composing a [`RenderTarget2d`].
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub enum RenderTargetError {
88    /// Target dimensions must both be non-zero.
89    ZeroDimension,
90    /// Dimensions exceed the current device's supported target size or allocation range.
91    DimensionsTooLarge,
92    /// The target belongs to another renderer and GPU device.
93    RendererMismatch,
94    /// Opacity must be finite and within `0.0..=1.0`.
95    InvalidOpacity,
96    /// A temporal source must not be one of its destination ping-pong targets.
97    SourceAliasesDestination,
98    /// The destination clear color was not normalized linear RGBA.
99    InvalidBackground,
100    /// Surface acquisition or presentation failed.
101    Frame(RendererFrameError),
102}
103
104impl fmt::Display for RenderTargetError {
105    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            Self::ZeroDimension => write!(formatter, "render target dimensions must be non-zero"),
108            Self::DimensionsTooLarge => {
109                write!(formatter, "render target dimensions exceed device limits")
110            }
111            Self::RendererMismatch => {
112                write!(formatter, "render target belongs to a different renderer")
113            }
114            Self::InvalidOpacity => write!(
115                formatter,
116                "render target opacity must be finite and in 0.0..=1.0"
117            ),
118            Self::SourceAliasesDestination => {
119                write!(
120                    formatter,
121                    "trail source must be distinct from its destination targets"
122                )
123            }
124            Self::InvalidBackground => {
125                write!(formatter, "render target background must be normalized")
126            }
127            Self::Frame(error) => write!(formatter, "render target frame failed: {error}"),
128        }
129    }
130}
131
132impl Error for RenderTargetError {}
133
134impl WgpuRenderer {
135    /// Creates an offscreen target with physical texture dimensions.
136    pub fn create_render_target(
137        &self,
138        width: u32,
139        height: u32,
140    ) -> Result<RenderTarget2d, RenderTargetError> {
141        if width == 0 || height == 0 {
142            return Err(RenderTargetError::ZeroDimension);
143        }
144        if width > self.device.limits().max_texture_dimension_2d
145            || height > self.device.limits().max_texture_dimension_2d
146        {
147            return Err(RenderTargetError::DimensionsTooLarge);
148        }
149        let allocation_bytes = render_target_allocation_bytes(self.config.format, width, height)
150            .ok_or(RenderTargetError::DimensionsTooLarge)?;
151        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
152            label: Some("sim-engine render target"),
153            size: wgpu::Extent3d {
154                width,
155                height,
156                depth_or_array_layers: 1,
157            },
158            mip_level_count: 1,
159            sample_count: 1,
160            dimension: wgpu::TextureDimension::D2,
161            format: self.config.format,
162            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
163                | wgpu::TextureUsages::TEXTURE_BINDING
164                | wgpu::TextureUsages::COPY_SRC,
165            view_formats: &[],
166        });
167        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
168        Ok(RenderTarget2d {
169            renderer_identity: Arc::clone(&self.renderer_identity),
170            resource_identity: Arc::new(()),
171            _texture: texture,
172            view,
173            width,
174            height,
175            allocation_bytes,
176        })
177    }
178
179    /// Creates an empty ping-pong target pair for temporal accumulation.
180    pub fn create_trail_buffer(
181        &mut self,
182        width: u32,
183        height: u32,
184    ) -> Result<TrailBuffer2d, RenderTargetError> {
185        let front = self.create_render_target(width, height)?;
186        let back = self.create_render_target(width, height)?;
187        let trails = TrailBuffer2d {
188            renderer_identity: Arc::clone(&self.renderer_identity),
189            front,
190            back,
191        };
192        self.draw_clear_trail_buffer(&trails, Color::rgba(0.0, 0.0, 0.0, 0.0), Instant::now());
193        Ok(trails)
194    }
195
196    /// Recreates an empty target with the source dimensions after device recovery.
197    ///
198    /// GPU pixels are deliberately not retained; callers redraw their source
199    /// state into the restored target.
200    pub fn restore_render_target(
201        &self,
202        source: &RenderTarget2d,
203    ) -> Result<RenderTarget2d, RenderTargetError> {
204        self.create_render_target(source.width(), source.height())
205    }
206
207    /// Recreates an empty, deterministically cleared trail buffer after recovery.
208    pub fn restore_trail_buffer(
209        &mut self,
210        source: &TrailBuffer2d,
211    ) -> Result<TrailBuffer2d, RenderTargetError> {
212        self.create_trail_buffer(source.width(), source.height())
213    }
214
215    /// Retains one bounded frame of history and composites a fresh source target.
216    ///
217    /// `retention` and `source_opacity` must be finite values in `0.0..=1.0`.
218    /// The source must be a distinct target; use [`WgpuRenderer::clear_trail_buffer`]
219    /// to discard accumulated history deterministically.
220    pub fn accumulate_trail_buffer(
221        &mut self,
222        trails: &mut TrailBuffer2d,
223        source: &RenderTarget2d,
224        retention: f32,
225        source_opacity: f32,
226        source_blend: BlendMode,
227    ) -> Result<RenderReport, RenderTargetError> {
228        self.validate_trail_buffer(trails)?;
229        self.validate_render_target(source)?;
230        if Arc::ptr_eq(&source.resource_identity, &trails.front.resource_identity)
231            || Arc::ptr_eq(&source.resource_identity, &trails.back.resource_identity)
232        {
233            return Err(RenderTargetError::SourceAliasesDestination);
234        }
235        if !retention.is_finite()
236            || !(0.0..=1.0).contains(&retention)
237            || !source_opacity.is_finite()
238            || !(0.0..=1.0).contains(&source_opacity)
239        {
240            return Err(RenderTargetError::InvalidOpacity);
241        }
242        Ok(self.draw_trail_accumulation(
243            trails,
244            source,
245            retention,
246            source_opacity,
247            source_blend,
248            Instant::now(),
249        ))
250    }
251
252    /// Clears both ping-pong targets, resetting all retained temporal history.
253    pub fn clear_trail_buffer(
254        &mut self,
255        trails: &mut TrailBuffer2d,
256        color: Color,
257    ) -> Result<RenderReport, RenderTargetError> {
258        self.validate_trail_buffer(trails)?;
259        if !color.is_normalized() {
260            return Err(RenderTargetError::InvalidBackground);
261        }
262        Ok(self.draw_clear_trail_buffer(trails, color, Instant::now()))
263    }
264
265    /// Presents the most recently accumulated temporal target.
266    pub fn compose_trail_buffer(
267        &mut self,
268        trails: &TrailBuffer2d,
269        blend_mode: BlendMode,
270        opacity: f32,
271        background: Color,
272    ) -> Result<RenderReport, RenderTargetError> {
273        self.validate_trail_buffer(trails)?;
274        self.compose_render_target(&trails.front, blend_mode, opacity, background)
275    }
276
277    /// Composes a previously rendered target over the presentation surface.
278    pub fn compose_render_target(
279        &mut self,
280        target: &RenderTarget2d,
281        blend_mode: BlendMode,
282        opacity: f32,
283        background: Color,
284    ) -> Result<RenderReport, RenderTargetError> {
285        self.validate_render_target(target)?;
286        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
287            return Err(RenderTargetError::InvalidOpacity);
288        }
289        if !background.is_normalized() {
290            return Err(RenderTargetError::InvalidBackground);
291        }
292        self.draw_composed_render_target(target, blend_mode, opacity, background, Instant::now())
293            .map_err(RenderTargetError::Frame)
294    }
295
296    fn draw_composed_render_target(
297        &mut self,
298        target: &RenderTarget2d,
299        blend_mode: BlendMode,
300        opacity: f32,
301        background: Color,
302        frame_started_at: Instant,
303    ) -> Result<RenderReport, RendererFrameError> {
304        let acquire_started_at = Instant::now();
305        let surface_texture = match self.surface.get_current_texture() {
306            wgpu::CurrentSurfaceTexture::Success(texture)
307            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
308            wgpu::CurrentSurfaceTexture::Timeout => {
309                return Ok(render_report(
310                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
311                    Duration::ZERO,
312                    Duration::ZERO,
313                    Duration::ZERO,
314                    acquire_started_at.elapsed(),
315                    Duration::ZERO,
316                    frame_started_at.elapsed(),
317                    false,
318                    true,
319                    TessellationStats::default(),
320                ));
321            }
322            wgpu::CurrentSurfaceTexture::Occluded => {
323                return Ok(render_report(
324                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
325                    Duration::ZERO,
326                    Duration::ZERO,
327                    Duration::ZERO,
328                    acquire_started_at.elapsed(),
329                    Duration::ZERO,
330                    frame_started_at.elapsed(),
331                    false,
332                    true,
333                    TessellationStats::default(),
334                ));
335            }
336            wgpu::CurrentSurfaceTexture::Outdated => {
337                let _ = self.resize(self.config.width, self.config.height);
338                return Ok(render_report(
339                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
340                    Duration::ZERO,
341                    Duration::ZERO,
342                    Duration::ZERO,
343                    acquire_started_at.elapsed(),
344                    Duration::ZERO,
345                    frame_started_at.elapsed(),
346                    false,
347                    true,
348                    TessellationStats::default(),
349                ));
350            }
351            wgpu::CurrentSurfaceTexture::Lost => {
352                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
353            }
354            wgpu::CurrentSurfaceTexture::Validation => {
355                return Err(RendererFrameError::Surface(
356                    RendererSurfaceStatus::Validation,
357                ));
358            }
359        };
360        let surface_acquire = acquire_started_at.elapsed();
361        let upload_started_at = Instant::now();
362        self.queue.write_buffer(
363            &self.composition_pipelines.uniform_buffer,
364            0,
365            bytemuck::bytes_of(&CompositeUniform::full_surface(opacity)),
366        );
367        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
368            label: Some("sim-engine composition bind group"),
369            layout: &self.composition_pipelines.bind_group_layout,
370            entries: &[
371                wgpu::BindGroupEntry {
372                    binding: 0,
373                    resource: wgpu::BindingResource::TextureView(&target.view),
374                },
375                wgpu::BindGroupEntry {
376                    binding: 1,
377                    resource: self
378                        .composition_pipelines
379                        .uniform_buffer
380                        .as_entire_binding(),
381                },
382            ],
383        });
384        let upload = upload_started_at.elapsed();
385        let encode_started_at = Instant::now();
386        let surface_view = surface_texture
387            .texture
388            .create_view(&wgpu::TextureViewDescriptor::default());
389        let (view, resolve_target) = match &self.multisample_target {
390            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
391            None => (&surface_view, None),
392        };
393        let mut encoder = self
394            .device
395            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
396                label: Some("sim-engine composition encoder"),
397            });
398        {
399            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
400                label: Some("sim-engine composition pass"),
401                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
402                    view,
403                    depth_slice: None,
404                    resolve_target,
405                    ops: wgpu::Operations {
406                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
407                        store: wgpu::StoreOp::Store,
408                    },
409                })],
410                depth_stencil_attachment: None,
411                timestamp_writes: None,
412                occlusion_query_set: None,
413                multiview_mask: None,
414            });
415            pass.set_pipeline(self.composition_pipelines.pipeline(blend_mode));
416            pass.set_bind_group(0, &bind_group, &[]);
417            pass.draw(0..6, 0..1);
418        }
419        self.queue.submit([encoder.finish()]);
420        self.notify_before_present();
421        self.queue.present(surface_texture);
422        Ok(render_report(
423            RenderStatus::Drawn,
424            Duration::ZERO,
425            upload,
426            Duration::ZERO,
427            surface_acquire,
428            encode_started_at.elapsed(),
429            frame_started_at.elapsed(),
430            false,
431            true,
432            TessellationStats::default(),
433        ))
434    }
435
436    #[allow(clippy::too_many_arguments)]
437    fn draw_trail_accumulation(
438        &mut self,
439        trails: &mut TrailBuffer2d,
440        source: &RenderTarget2d,
441        retention: f32,
442        source_opacity: f32,
443        source_blend: BlendMode,
444        frame_started_at: Instant,
445    ) -> RenderReport {
446        let upload_started_at = Instant::now();
447        self.queue.write_buffer(
448            &self.target_composition_pipelines.secondary_uniform_buffer,
449            0,
450            bytemuck::bytes_of(&CompositeUniform::full_surface(retention)),
451        );
452        self.queue.write_buffer(
453            &self.target_composition_pipelines.uniform_buffer,
454            0,
455            bytemuck::bytes_of(&CompositeUniform::full_surface(source_opacity)),
456        );
457        let history_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
458            label: Some("sim-engine trail history bind group"),
459            layout: &self.target_composition_pipelines.bind_group_layout,
460            entries: &[
461                wgpu::BindGroupEntry {
462                    binding: 0,
463                    resource: wgpu::BindingResource::TextureView(&trails.front.view),
464                },
465                wgpu::BindGroupEntry {
466                    binding: 1,
467                    resource: self
468                        .target_composition_pipelines
469                        .secondary_uniform_buffer
470                        .as_entire_binding(),
471                },
472            ],
473        });
474        let source_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
475            label: Some("sim-engine trail source bind group"),
476            layout: &self.target_composition_pipelines.bind_group_layout,
477            entries: &[
478                wgpu::BindGroupEntry {
479                    binding: 0,
480                    resource: wgpu::BindingResource::TextureView(&source.view),
481                },
482                wgpu::BindGroupEntry {
483                    binding: 1,
484                    resource: self
485                        .target_composition_pipelines
486                        .uniform_buffer
487                        .as_entire_binding(),
488                },
489            ],
490        });
491        let upload = upload_started_at.elapsed();
492        let encode_started_at = Instant::now();
493        let mut encoder = self
494            .device
495            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
496                label: Some("sim-engine trail accumulation encoder"),
497            });
498        {
499            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
500                label: Some("sim-engine trail history pass"),
501                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
502                    view: &trails.back.view,
503                    depth_slice: None,
504                    resolve_target: None,
505                    ops: wgpu::Operations {
506                        load: wgpu::LoadOp::Clear(Color::rgba(0.0, 0.0, 0.0, 0.0).to_wgpu()),
507                        store: wgpu::StoreOp::Store,
508                    },
509                })],
510                depth_stencil_attachment: None,
511                timestamp_writes: None,
512                occlusion_query_set: None,
513                multiview_mask: None,
514            });
515            pass.set_pipeline(&self.target_composition_pipelines.alpha);
516            pass.set_bind_group(0, &history_bind_group, &[]);
517            pass.draw(0..6, 0..1);
518        }
519        {
520            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
521                label: Some("sim-engine trail source pass"),
522                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
523                    view: &trails.back.view,
524                    depth_slice: None,
525                    resolve_target: None,
526                    ops: wgpu::Operations {
527                        load: wgpu::LoadOp::Load,
528                        store: wgpu::StoreOp::Store,
529                    },
530                })],
531                depth_stencil_attachment: None,
532                timestamp_writes: None,
533                occlusion_query_set: None,
534                multiview_mask: None,
535            });
536            pass.set_pipeline(self.target_composition_pipelines.pipeline(source_blend));
537            pass.set_bind_group(0, &source_bind_group, &[]);
538            pass.draw(0..6, 0..1);
539        }
540        self.queue.submit([encoder.finish()]);
541        std::mem::swap(&mut trails.front, &mut trails.back);
542        render_report(
543            RenderStatus::Drawn,
544            Duration::ZERO,
545            upload,
546            Duration::ZERO,
547            Duration::ZERO,
548            encode_started_at.elapsed(),
549            frame_started_at.elapsed(),
550            false,
551            true,
552            TessellationStats::default(),
553        )
554    }
555
556    fn draw_clear_trail_buffer(
557        &self,
558        trails: &TrailBuffer2d,
559        color: Color,
560        frame_started_at: Instant,
561    ) -> RenderReport {
562        let encode_started_at = Instant::now();
563        let mut encoder = self
564            .device
565            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
566                label: Some("sim-engine trail clear encoder"),
567            });
568        for view in [&trails.front.view, &trails.back.view] {
569            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
570                label: Some("sim-engine trail clear pass"),
571                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
572                    view,
573                    depth_slice: None,
574                    resolve_target: None,
575                    ops: wgpu::Operations {
576                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(color)),
577                        store: wgpu::StoreOp::Store,
578                    },
579                })],
580                depth_stencil_attachment: None,
581                timestamp_writes: None,
582                occlusion_query_set: None,
583                multiview_mask: None,
584            });
585        }
586        self.queue.submit([encoder.finish()]);
587        render_report(
588            RenderStatus::Drawn,
589            Duration::ZERO,
590            Duration::ZERO,
591            Duration::ZERO,
592            Duration::ZERO,
593            encode_started_at.elapsed(),
594            frame_started_at.elapsed(),
595            false,
596            true,
597            TessellationStats::default(),
598        )
599    }
600
601    pub(super) fn validate_render_target(
602        &self,
603        target: &RenderTarget2d,
604    ) -> Result<(), RenderTargetError> {
605        prepared_scene_belongs_to(&self.renderer_identity, &target.renderer_identity)
606            .then_some(())
607            .ok_or(RenderTargetError::RendererMismatch)
608    }
609
610    fn validate_trail_buffer(&self, trails: &TrailBuffer2d) -> Result<(), RenderTargetError> {
611        prepared_scene_belongs_to(&self.renderer_identity, &trails.renderer_identity)
612            .then_some(())
613            .ok_or(RenderTargetError::RendererMismatch)
614    }
615}