Skip to main content

renderer_api/
renderer_api.rs

1//! Renderer helper API and two-pass offscreen rendering example.
2//!
3//! Demonstrates:
4//! - Using the `Renderer` helper for resource creation (shaders, buffers, textures)
5//! - Rendering to an offscreen `Framebuffer` (pass 1) and blitting it to the surface (pass 2)
6//! - `BlendMode::Alpha` (standard source-over blending for scene geometry)
7//!   vs `BlendMode::PremultipliedAlpha` (for compositing a pre-rendered framebuffer)
8
9use std::sync::Arc;
10use astrelis_core::logging;
11use astrelis_render::{
12    BlendMode, Color, Framebuffer, GraphicsContext, RenderTarget, RenderableWindow,
13    Renderer, WindowContextDescriptor, wgpu,
14};
15use astrelis_winit::{
16    FrameTime, WindowId,
17    app::{App, AppCtx, run_app},
18    event::EventBatch,
19    window::{WinitPhysicalSize, WindowBackend, WindowDescriptor},
20};
21
22struct RendererApp {
23    context: Arc<GraphicsContext>,
24    renderer: Renderer,
25    window: RenderableWindow,
26    window_id: WindowId,
27    pipeline: wgpu::RenderPipeline,
28    bind_group: wgpu::BindGroup,
29    vertex_buffer: wgpu::Buffer,
30    // Offscreen framebuffer for demonstrating framebuffer rendering
31    offscreen_fb: Framebuffer,
32    blit_pipeline: wgpu::RenderPipeline,
33    blit_bind_group: wgpu::BindGroup,
34    time: f32,
35}
36
37fn main() {
38    logging::init();
39
40    run_app(|ctx| {
41        let graphics_ctx = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
42        let renderer = Renderer::new(graphics_ctx.clone());
43
44        let window = ctx
45            .create_window(WindowDescriptor {
46                title: "Renderer API Example".to_string(),
47                size: Some(WinitPhysicalSize::new(800.0, 600.0)),
48                ..Default::default()
49            })
50            .expect("Failed to create window");
51
52        let window = RenderableWindow::new_with_descriptor(
53            window,
54            graphics_ctx.clone(),
55            WindowContextDescriptor {
56                format: Some(wgpu::TextureFormat::Bgra8UnormSrgb),
57                ..Default::default()
58            },
59        ).expect("Failed to create renderable window");
60
61        let window_id = window.id();
62
63        // Create shader using Renderer API
64        let shader = renderer.create_shader(Some("Color Shader"), SHADER_SOURCE);
65
66        // Create texture using Renderer helper
67        let texture_data = create_gradient_texture();
68        let texture = renderer.create_texture_2d(
69            Some("Gradient Texture"),
70            256,
71            256,
72            wgpu::TextureFormat::Rgba8UnormSrgb,
73            wgpu::TextureUsages::TEXTURE_BINDING,
74            &texture_data,
75        );
76
77        let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
78        let sampler = renderer.create_linear_sampler(Some("Linear Sampler"));
79
80        // Create bind group using Renderer API
81        let bind_group_layout = renderer.create_bind_group_layout(
82            Some("Texture Bind Group Layout"),
83            &[
84                wgpu::BindGroupLayoutEntry {
85                    binding: 0,
86                    visibility: wgpu::ShaderStages::FRAGMENT,
87                    ty: wgpu::BindingType::Texture {
88                        multisampled: false,
89                        view_dimension: wgpu::TextureViewDimension::D2,
90                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
91                    },
92                    count: None,
93                },
94                wgpu::BindGroupLayoutEntry {
95                    binding: 1,
96                    visibility: wgpu::ShaderStages::FRAGMENT,
97                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
98                    count: None,
99                },
100            ],
101        );
102
103        let bind_group = renderer.create_bind_group(
104            Some("Texture Bind Group"),
105            &bind_group_layout,
106            &[
107                wgpu::BindGroupEntry {
108                    binding: 0,
109                    resource: wgpu::BindingResource::TextureView(&texture_view),
110                },
111                wgpu::BindGroupEntry {
112                    binding: 1,
113                    resource: wgpu::BindingResource::Sampler(&sampler),
114                },
115            ],
116        );
117
118        let pipeline_layout = renderer.create_pipeline_layout(
119            Some("Render Pipeline Layout"),
120            &[&bind_group_layout],
121            &[],
122        );
123
124        // Create pipeline using Renderer API with BlendMode
125        let pipeline = renderer.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
126            label: Some("Render Pipeline"),
127            layout: Some(&pipeline_layout),
128            vertex: wgpu::VertexState {
129                module: &shader,
130                entry_point: Some("vs_main"),
131                buffers: &[wgpu::VertexBufferLayout {
132                    // 4 floats × 4 bytes = 16 bytes per vertex (2×f32 pos + 2×f32 UV)
133                    array_stride: 4 * 4,
134                    step_mode: wgpu::VertexStepMode::Vertex,
135                    attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2],
136                }],
137                compilation_options: wgpu::PipelineCompilationOptions::default(),
138            },
139            fragment: Some(wgpu::FragmentState {
140                module: &shader,
141                entry_point: Some("fs_main"),
142                // Use BlendMode for transparent rendering
143                targets: &[Some(
144                    BlendMode::Alpha.to_color_target_state(wgpu::TextureFormat::Rgba8UnormSrgb),
145                )],
146                compilation_options: wgpu::PipelineCompilationOptions::default(),
147            }),
148            primitive: wgpu::PrimitiveState {
149                topology: wgpu::PrimitiveTopology::TriangleList,
150                strip_index_format: None,
151                front_face: wgpu::FrontFace::Ccw,
152                cull_mode: Some(wgpu::Face::Back),
153                polygon_mode: wgpu::PolygonMode::Fill,
154                unclipped_depth: false,
155                conservative: false,
156            },
157            depth_stencil: None,
158            multisample: wgpu::MultisampleState {
159                count: 1,
160                mask: !0,
161                alpha_to_coverage_enabled: false,
162            },
163            multiview: None,
164            cache: None,
165        });
166
167        #[rustfmt::skip]
168        let vertices: &[f32] = &[
169            -0.8, -0.8,  0.0, 1.0,
170             0.8, -0.8,  1.0, 1.0,
171             0.8,  0.8,  1.0, 0.0,
172            -0.8, -0.8,  0.0, 1.0,
173             0.8,  0.8,  1.0, 0.0,
174            -0.8,  0.8,  0.0, 0.0,
175        ];
176
177        // Create vertex buffer using Renderer helper
178        let vertex_buffer = renderer.create_vertex_buffer(Some("Vertex Buffer"), vertices);
179
180        // Create offscreen framebuffer using the new Framebuffer abstraction
181        let offscreen_fb = Framebuffer::builder(400, 300)
182            .format(wgpu::TextureFormat::Rgba8UnormSrgb)
183            .label("Offscreen FB")
184            .build(&graphics_ctx);
185
186        // Create blit shader and pipeline for rendering framebuffer to surface
187        let blit_shader = renderer.create_shader(Some("Blit Shader"), BLIT_SHADER_SOURCE);
188
189        let blit_bind_group_layout = renderer.create_bind_group_layout(
190            Some("Blit Bind Group Layout"),
191            &[
192                wgpu::BindGroupLayoutEntry {
193                    binding: 0,
194                    visibility: wgpu::ShaderStages::FRAGMENT,
195                    ty: wgpu::BindingType::Texture {
196                        multisampled: false,
197                        view_dimension: wgpu::TextureViewDimension::D2,
198                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
199                    },
200                    count: None,
201                },
202                wgpu::BindGroupLayoutEntry {
203                    binding: 1,
204                    visibility: wgpu::ShaderStages::FRAGMENT,
205                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
206                    count: None,
207                },
208            ],
209        );
210
211        let blit_bind_group = renderer.create_bind_group(
212            Some("Blit Bind Group"),
213            &blit_bind_group_layout,
214            &[
215                wgpu::BindGroupEntry {
216                    binding: 0,
217                    resource: wgpu::BindingResource::TextureView(offscreen_fb.color_view()),
218                },
219                wgpu::BindGroupEntry {
220                    binding: 1,
221                    resource: wgpu::BindingResource::Sampler(&sampler),
222                },
223            ],
224        );
225
226        let blit_pipeline_layout = renderer.create_pipeline_layout(
227            Some("Blit Pipeline Layout"),
228            &[&blit_bind_group_layout],
229            &[],
230        );
231
232        let blit_pipeline = renderer.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
233            label: Some("Blit Pipeline"),
234            layout: Some(&blit_pipeline_layout),
235            vertex: wgpu::VertexState {
236                module: &blit_shader,
237                entry_point: Some("vs_main"),
238                buffers: &[],
239                compilation_options: wgpu::PipelineCompilationOptions::default(),
240            },
241            fragment: Some(wgpu::FragmentState {
242                module: &blit_shader,
243                entry_point: Some("fs_main"),
244                // Use PremultipliedAlpha for framebuffer blitting
245                targets: &[Some(
246                    BlendMode::PremultipliedAlpha
247                        .to_color_target_state(wgpu::TextureFormat::Bgra8UnormSrgb),
248                )],
249                compilation_options: wgpu::PipelineCompilationOptions::default(),
250            }),
251            primitive: wgpu::PrimitiveState {
252                topology: wgpu::PrimitiveTopology::TriangleList,
253                ..Default::default()
254            },
255            depth_stencil: None,
256            multisample: wgpu::MultisampleState::default(),
257            multiview: None,
258            cache: None,
259        });
260
261        tracing::info!("Renderer initialized successfully");
262        tracing::info!("Device: {:?}", renderer.context().info());
263
264        Box::new(RendererApp {
265            context: graphics_ctx,
266            renderer,
267            window,
268            window_id,
269            pipeline,
270            bind_group,
271            vertex_buffer,
272            offscreen_fb,
273            blit_pipeline,
274            blit_bind_group,
275            time: 0.0,
276        })
277    });
278}
279
280impl App for RendererApp {
281    fn update(&mut self, _ctx: &mut AppCtx, _time: &FrameTime) {
282        // Global logic - update animation time
283        self.time += 0.016;
284    }
285
286    fn render(&mut self, _ctx: &mut AppCtx, window_id: WindowId, events: &mut EventBatch) {
287        if window_id != self.window_id {
288            return;
289        }
290
291        // Handle window-specific resize events
292        events.dispatch(|event| {
293            if let astrelis_winit::event::Event::WindowResized(size) = event {
294                self.window.resized(*size);
295                astrelis_winit::event::HandleStatus::consumed()
296            } else {
297                astrelis_winit::event::HandleStatus::ignored()
298            }
299        });
300
301        let mut frame = self.window.begin_drawing();
302
303        // Pass 1: Render to offscreen framebuffer with automatic scoping
304        frame.clear_and_render(
305            RenderTarget::Framebuffer(&self.offscreen_fb),
306            Color::rgb(0.2, 0.1, 0.3),
307            |pass| {
308                let pass = pass.wgpu_pass();
309                pass.set_pipeline(&self.pipeline);
310                pass.set_bind_group(0, &self.bind_group, &[]);
311                pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
312                pass.draw(0..6, 0..1);
313            },
314        );
315
316        // Pass 2: Blit framebuffer to surface with automatic scoping
317        frame.clear_and_render(
318            RenderTarget::Surface,
319            Color::rgb(0.1, 0.2, 0.3),
320            |pass| {
321                let pass = pass.wgpu_pass();
322                pass.set_pipeline(&self.blit_pipeline);
323                pass.set_bind_group(0, &self.blit_bind_group, &[]);
324                // Draw fullscreen triangle
325                pass.draw(0..3, 0..1);
326            },
327        );
328
329        frame.finish();
330    }
331}
332
333fn create_gradient_texture() -> Vec<u8> {
334    let mut texture_data = vec![0u8; (256 * 256 * 4) as usize];
335    for y in 0..256 {
336        for x in 0..256 {
337            let idx = ((y * 256 + x) * 4) as usize;
338            texture_data[idx] = x as u8;
339            texture_data[idx + 1] = y as u8;
340            texture_data[idx + 2] = ((x + y) / 2) as u8;
341            texture_data[idx + 3] = 255;
342        }
343    }
344    texture_data
345}
346
347const SHADER_SOURCE: &str = r#"
348struct VertexInput {
349    @location(0) position: vec2<f32>,
350    @location(1) tex_coords: vec2<f32>,
351}
352
353struct VertexOutput {
354    @builtin(position) clip_position: vec4<f32>,
355    @location(0) tex_coords: vec2<f32>,
356}
357
358@vertex
359fn vs_main(in: VertexInput) -> VertexOutput {
360    var out: VertexOutput;
361    out.clip_position = vec4<f32>(in.position, 0.0, 1.0);
362    out.tex_coords = in.tex_coords;
363    return out;
364}
365
366@group(0) @binding(0)
367var t_diffuse: texture_2d<f32>;
368@group(0) @binding(1)
369var s_diffuse: sampler;
370
371@fragment
372fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
373    return textureSample(t_diffuse, s_diffuse, in.tex_coords);
374}
375"#;
376
377const BLIT_SHADER_SOURCE: &str = r#"
378struct VertexOutput {
379    @builtin(position) clip_position: vec4<f32>,
380    @location(0) tex_coords: vec2<f32>,
381}
382
383@vertex
384fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
385    // Fullscreen triangle
386    var positions = array<vec2<f32>, 3>(
387        vec2<f32>(-1.0, -1.0),
388        vec2<f32>(3.0, -1.0),
389        vec2<f32>(-1.0, 3.0)
390    );
391    var tex_coords = array<vec2<f32>, 3>(
392        vec2<f32>(0.0, 1.0),
393        vec2<f32>(2.0, 1.0),
394        vec2<f32>(0.0, -1.0)
395    );
396
397    var out: VertexOutput;
398    out.clip_position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
399    out.tex_coords = tex_coords[vertex_index];
400    return out;
401}
402
403@group(0) @binding(0)
404var t_source: texture_2d<f32>;
405@group(0) @binding(1)
406var s_source: sampler;
407
408@fragment
409fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
410    return textureSample(t_source, s_source, in.tex_coords);
411}
412"#;