Skip to main content

strata_render/
shared_target.rs

1//! Shared Render Target: Hybrid 2D/3D Viewport Compositing Bridge.
2//!
3//! Provides offscreen 3D rendering buffers with dirty-rect caching and zero-desync
4//! 2D HUD telemetry overlay compositing.
5
6use crate::compositor::DisplayList;
7use crate::rasterizer::FrameBuffer;
8use crate::rasterizer3d::render_scene_3d;
9use crate::scene3d::Scene3D;
10use strata_layout::Rect;
11use strata_style::types::Color;
12
13/// Offscreen Shared Render Target for 3D Viewports.
14#[derive(Debug, Clone, PartialEq)]
15pub struct SharedRenderTarget {
16    pub bounds: Rect,
17    pub width: usize,
18    pub height: usize,
19    pub color_buffer: FrameBuffer,
20    pub depth_buffer: Vec<f32>,
21    pub dirty: bool,
22    pub background_color: Color,
23}
24
25impl SharedRenderTarget {
26    /// Creates a new offscreen render target with specified bounds.
27    pub fn new(bounds: Rect) -> Self {
28        let width = bounds.width.ceil().max(1.0) as usize;
29        let height = bounds.height.ceil().max(1.0) as usize;
30
31        Self {
32            bounds,
33            width,
34            height,
35            color_buffer: FrameBuffer::new(width, height),
36            depth_buffer: vec![1.0; width * height],
37            dirty: true,
38            background_color: Color::rgb(10, 15, 25), // Dark space / infrastructure backdrop
39        }
40    }
41
42    /// Resizes the shared render target if the viewport dimensions change.
43    pub fn resize(&mut self, bounds: Rect) {
44        let width = bounds.width.ceil().max(1.0) as usize;
45        let height = bounds.height.ceil().max(1.0) as usize;
46
47        if width != self.width || height != self.height {
48            self.bounds = bounds;
49            self.width = width;
50            self.height = height;
51            self.color_buffer = FrameBuffer::new(width, height);
52            self.depth_buffer = vec![1.0; width * height];
53            self.dirty = true;
54        } else {
55            self.bounds = bounds;
56        }
57    }
58
59    /// Marks the 3D target as dirty, forcing re-rendering on the next frame.
60    #[inline]
61    pub fn mark_dirty(&mut self) {
62        self.dirty = true;
63    }
64
65    /// Clears the color buffer to background color and resets the depth buffer.
66    pub fn clear(&mut self) {
67        self.color_buffer.clear(self.background_color);
68        self.depth_buffer.fill(1.0);
69    }
70
71    /// Renders the 3D scene into this offscreen buffer if marked dirty.
72    pub fn render_if_dirty(&mut self, scene: &Scene3D) {
73        if !self.dirty {
74            return;
75        }
76
77        self.clear();
78        let local_viewport = Rect::new(0.0, 0.0, self.width as f32, self.height as f32);
79        render_scene_3d(&mut self.color_buffer, local_viewport, scene, None);
80        self.dirty = false;
81    }
82
83    /// Forces rendering of the 3D scene into this offscreen buffer.
84    pub fn render_scene(&mut self, scene: &Scene3D) {
85        self.clear();
86        let local_viewport = Rect::new(0.0, 0.0, self.width as f32, self.height as f32);
87        render_scene_3d(&mut self.color_buffer, local_viewport, scene, None);
88        self.dirty = false;
89    }
90
91    /// Composites (blits) the rendered 3D viewport into a target 2D FrameBuffer.
92    pub fn composite_to_surface(&self, dst: &mut FrameBuffer, clip: Option<Rect>) {
93        let start_x = self.bounds.x.max(0.0) as usize;
94        let start_y = self.bounds.y.max(0.0) as usize;
95
96        let end_x = ((self.bounds.x + self.width as f32).min(dst.width as f32)) as usize;
97        let end_y = ((self.bounds.y + self.height as f32).min(dst.height as f32)) as usize;
98
99        for y in start_y..end_y {
100            let src_y = y - start_y;
101            if src_y >= self.height {
102                continue;
103            }
104
105            for x in start_x..end_x {
106                let src_x = x - start_x;
107                if src_x >= self.width {
108                    continue;
109                }
110
111                // Check optional scissor clip
112                if let Some(c) = clip {
113                    let fx = x as f32;
114                    let fy = y as f32;
115                    if fx < c.x || fx >= c.max_x() || fy < c.y || fy >= c.max_y() {
116                        continue;
117                    }
118                }
119
120                let pixel = self.color_buffer.get_pixel(src_x, src_y);
121                dst.set_pixel(x, y, pixel);
122            }
123        }
124    }
125
126    /// Safe zero-copy byte slice view of color buffer pixels.
127    #[inline]
128    pub fn as_raw_bytes(&self) -> &[u8] {
129        self.color_buffer.as_raw_bytes()
130    }
131}
132
133/// Executes a complete hybrid 2D/3D presentation frame:
134/// 1. Renders 3D scene into the offscreen SharedRenderTarget.
135/// 2. Blits the 3D buffer to the destination FrameBuffer at `target.bounds`.
136/// 3. Executes the 2D DisplayList (telemetry badges, HUD cards, buttons) directly over the 3D surface.
137pub fn render_hybrid_frame(
138    target: &mut SharedRenderTarget,
139    scene: &Scene3D,
140    overlay_display_list: &DisplayList,
141    dst_frame_buffer: &mut FrameBuffer,
142    clip: Option<Rect>,
143) {
144    // 1. Render 3D Scene to offscreen buffer
145    target.render_if_dirty(scene);
146
147    // 2. Blit 3D Viewport to target frame buffer
148    target.composite_to_surface(dst_frame_buffer, clip);
149
150    // 3. Render 2D UI Overlay on top
151    if let Some(damage) = clip {
152        dst_frame_buffer.execute_display_list_damaged(overlay_display_list, damage);
153    } else {
154        dst_frame_buffer.execute_display_list(overlay_display_list);
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::compositor::DrawCommand;
162    use crate::scene3d::{Camera3D, Geometry3D, Material3D, Mesh3D};
163
164    #[test]
165    fn test_shared_render_target_lifecycle() {
166        let bounds = Rect::new(50.0, 50.0, 200.0, 150.0);
167        let mut target = SharedRenderTarget::new(bounds);
168        assert_eq!(target.width, 200);
169        assert_eq!(target.height, 150);
170        assert!(target.dirty);
171
172        let mut scene = Scene3D::new();
173        scene.camera = Camera3D::Perspective {
174            fov_horizontal_deg: 60.0,
175            near: 0.1,
176            far: 100.0,
177            position: [0.0, 0.0, 5.0],
178            target: [0.0, 0.0, 0.0],
179        };
180        scene.add_mesh(Mesh3D::new(
181            Geometry3D::Box {
182                width: 1.0,
183                height: 1.0,
184                depth: 1.0,
185            },
186            Material3D::Basic {
187                color: Color::rgb(34, 197, 94),
188            },
189        ));
190
191        target.render_if_dirty(&scene);
192        assert!(!target.dirty);
193
194        // Blit to main surface (400x300)
195        let mut main_surface = FrameBuffer::new(400, 300);
196        target.composite_to_surface(&mut main_surface, None);
197
198        // Outside 3D viewport (10, 10) must be transparent
199        assert_eq!(main_surface.get_pixel(10, 10), Color::TRANSPARENT);
200
201        // Inside 3D viewport (e.g. 50+100, 50+75 = 150, 125) center should have rendered color
202        let center_pixel = main_surface.get_pixel(150, 125);
203        assert_ne!(center_pixel, Color::TRANSPARENT);
204    }
205
206    #[test]
207    fn test_hybrid_frame_2d_overlay_over_3d() {
208        let bounds = Rect::new(0.0, 0.0, 300.0, 300.0);
209        let mut target = SharedRenderTarget::new(bounds);
210        let scene = Scene3D::new();
211
212        // 2D Overlay DisplayList with a solid red telemetry badge at (20, 20, 80, 40)
213        let mut overlay_dl = DisplayList::new();
214        overlay_dl.push(DrawCommand::DrawRect {
215            bounds: Rect::new(20.0, 20.0, 80.0, 40.0),
216            color: Color::rgb(239, 68, 68), // Red-500
217        });
218
219        let mut main_surface = FrameBuffer::new(300, 300);
220        render_hybrid_frame(&mut target, &scene, &overlay_dl, &mut main_surface, None);
221
222        // Pixel inside 2D badge (30, 30) MUST be exact overlay color Red-500
223        let badge_pixel = main_surface.get_pixel(30, 30);
224        assert_eq!(badge_pixel, Color::rgb(239, 68, 68));
225
226        // Pixel outside badge (200, 200) should be 3D background color
227        let bg_pixel = main_surface.get_pixel(200, 200);
228        assert_eq!(bg_pixel, target.background_color);
229    }
230}