Skip to main content

eframe/web/
web_painter_wgpu.rs

1use std::sync::Arc;
2
3use egui::{Event, UserData, ViewportId};
4use egui_wgpu::{
5    RenderState, SurfaceErrorAction,
6    capture::{CaptureReceiver, CaptureSender, CaptureState, capture_channel},
7};
8use wasm_bindgen::JsValue;
9use web_sys::HtmlCanvasElement;
10
11use super::web_painter::WebPainter;
12
13pub(crate) struct WebPainterWgpu {
14    canvas: HtmlCanvasElement,
15    instance: wgpu::Instance,
16    surface: wgpu::Surface<'static>,
17    surface_configuration: wgpu::SurfaceConfiguration,
18    render_state: Option<RenderState>,
19    on_surface_status: Arc<dyn Fn(&wgpu::CurrentSurfaceTexture) -> SurfaceErrorAction>,
20    depth_stencil_format: Option<wgpu::TextureFormat>,
21    depth_texture_view: Option<wgpu::TextureView>,
22    screen_capture_state: Option<CaptureState>,
23    capture_tx: CaptureSender,
24    capture_rx: CaptureReceiver,
25    ctx: egui::Context,
26    needs_reconfigure: bool,
27    needs_recreate: bool,
28}
29
30/// Owned web display handle that is `Send + Sync`.
31///
32/// `DisplayHandle` from `raw-window-handle` is `!Send`/`!Sync` because the enum
33/// contains platform variants with raw pointers. On web the handle is always empty,
34/// so this wrapper is safe.
35#[cfg(target_arch = "wasm32")]
36#[derive(Clone, Debug)]
37struct WebDisplay;
38
39#[cfg(target_arch = "wasm32")]
40impl egui_wgpu::wgpu::rwh::HasDisplayHandle for WebDisplay {
41    fn display_handle(
42        &self,
43    ) -> Result<egui_wgpu::wgpu::rwh::DisplayHandle<'_>, egui_wgpu::wgpu::rwh::HandleError> {
44        Ok(egui_wgpu::wgpu::rwh::DisplayHandle::web())
45    }
46}
47
48impl WebPainterWgpu {
49    pub fn render_state(&self) -> Option<RenderState> {
50        self.render_state.clone()
51    }
52
53    pub fn generate_depth_texture_view(
54        &self,
55        render_state: &RenderState,
56        width_in_pixels: u32,
57        height_in_pixels: u32,
58    ) -> Option<wgpu::TextureView> {
59        let device = &render_state.device;
60        self.depth_stencil_format.map(|depth_stencil_format| {
61            device
62                .create_texture(&wgpu::TextureDescriptor {
63                    label: Some("egui_depth_texture"),
64                    size: wgpu::Extent3d {
65                        width: width_in_pixels,
66                        height: height_in_pixels,
67                        depth_or_array_layers: 1,
68                    },
69                    mip_level_count: 1,
70                    sample_count: 1,
71                    dimension: wgpu::TextureDimension::D2,
72                    format: depth_stencil_format,
73                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
74                    view_formats: &[depth_stencil_format],
75                })
76                .create_view(&wgpu::TextureViewDescriptor::default())
77        })
78    }
79
80    pub async fn new(
81        ctx: egui::Context,
82        canvas: web_sys::HtmlCanvasElement,
83        options: &crate::WebOptions,
84    ) -> Result<Self, String> {
85        log::debug!("Creating wgpu painter");
86
87        // Inject the display handle into the wgpu setup so that wgpu can create surfaces on WebGL.
88        let mut wgpu_options = options.wgpu_options.clone();
89        if let egui_wgpu::WgpuSetup::CreateNew(ref mut create_new) = wgpu_options.wgpu_setup
90            && create_new.display_handle.is_none()
91        {
92            // Force WebGL, useful for quick & dirty testing:
93            // create_new.instance_descriptor.backends = wgpu::Backends::GL;
94            create_new.display_handle = Some(Box::new(WebDisplay));
95        }
96
97        let instance = wgpu_options.wgpu_setup.new_instance().await;
98        let surface = instance
99            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
100            .map_err(|err| format!("failed to create wgpu surface: {err}"))?;
101
102        let depth_stencil_format = egui_wgpu::depth_format_from_bits(options.depth_buffer, 0);
103
104        let render_state = RenderState::create(
105            &wgpu_options,
106            &instance,
107            Some(&surface),
108            egui_wgpu::RendererOptions {
109                dithering: options.dithering,
110                depth_stencil_format,
111                ..Default::default()
112            },
113        )
114        .await
115        .map_err(|err| err.to_string())?;
116
117        let default_configuration = surface
118            .get_default_config(&render_state.adapter, 0, 0) // Width/height is set later.
119            .ok_or("The surface isn't supported by this adapter")?;
120
121        let surface_configuration = wgpu::SurfaceConfiguration {
122            format: render_state.target_format,
123            present_mode: wgpu_options.surface.present_mode,
124            view_formats: vec![render_state.target_format],
125            ..default_configuration
126        };
127
128        log::debug!("wgpu painter initialized.");
129
130        let (capture_tx, capture_rx) = capture_channel();
131
132        Ok(Self {
133            canvas,
134            instance,
135            render_state: Some(render_state),
136            surface,
137            surface_configuration,
138            depth_stencil_format,
139            depth_texture_view: None,
140            on_surface_status: Arc::clone(&wgpu_options.on_surface_status) as _,
141            screen_capture_state: None,
142            capture_tx,
143            capture_rx,
144            ctx,
145            needs_reconfigure: false,
146            needs_recreate: false,
147        })
148    }
149}
150
151impl WebPainter for WebPainterWgpu {
152    fn canvas(&self) -> &HtmlCanvasElement {
153        &self.canvas
154    }
155
156    fn max_texture_side(&self) -> usize {
157        self.render_state.as_ref().map_or(0, |state| {
158            state.device.limits().max_texture_dimension_2d as _
159        })
160    }
161
162    fn paint_and_update_textures(
163        &mut self,
164        clear_color: [f32; 4],
165        clipped_primitives: &[egui::ClippedPrimitive],
166        pixels_per_point: f32,
167        textures_delta: &mut egui::TexturesDelta,
168        capture_data: Vec<UserData>,
169    ) -> Result<(), JsValue> {
170        let capture = !capture_data.is_empty();
171
172        let size_in_pixels = [self.canvas.width(), self.canvas.height()];
173
174        let Some(render_state) = &self.render_state else {
175            return Err(JsValue::from_str(
176                "Can't paint, wgpu renderer was already disposed",
177            ));
178        };
179
180        // If the previous frame produced `CurrentSurfaceTexture::Lost`, drop and recreate the
181        // surface from the canvas before re-borrowing `self.render_state` for the rest of paint.
182        if self.needs_recreate {
183            self.needs_recreate = false;
184            match self
185                .instance
186                .create_surface(wgpu::SurfaceTarget::Canvas(self.canvas.clone()))
187            {
188                Ok(new_surface) => {
189                    new_surface.configure(&render_state.device, &self.surface_configuration);
190                    self.surface = new_surface;
191                }
192                Err(err) => {
193                    log::error!("Failed to recreate wgpu surface for canvas: {err}");
194                }
195            }
196        }
197
198        let mut encoder =
199            render_state
200                .device
201                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
202                    label: Some("egui_webpainter_paint_and_update_textures"),
203                });
204
205        // Upload all resources for the GPU.
206        let screen_descriptor = egui_wgpu::ScreenDescriptor {
207            size_in_pixels,
208            pixels_per_point,
209        };
210
211        let user_cmd_bufs = {
212            let mut renderer = render_state.renderer.write();
213            #[expect(clippy::iter_over_hash_type)] // Order doesn't matter here
214            for (id, image_deltas) in textures_delta.set.drain() {
215                for image_delta in image_deltas {
216                    renderer.update_texture(
217                        &render_state.device,
218                        &render_state.queue,
219                        id,
220                        &image_delta,
221                    );
222                }
223            }
224
225            renderer.update_buffers(
226                &render_state.device,
227                &render_state.queue,
228                &mut encoder,
229                clipped_primitives,
230                &screen_descriptor,
231            )
232        };
233
234        // Resize surface if needed
235        let is_zero_sized_surface = size_in_pixels[0] == 0 || size_in_pixels[1] == 0;
236        let frame_and_capture_buffer = if is_zero_sized_surface {
237            None
238        } else {
239            if size_in_pixels[0] != self.surface_configuration.width
240                || size_in_pixels[1] != self.surface_configuration.height
241            {
242                self.surface_configuration.width = size_in_pixels[0];
243                self.surface_configuration.height = size_in_pixels[1];
244                self.surface
245                    .configure(&render_state.device, &self.surface_configuration);
246                self.depth_texture_view = self.generate_depth_texture_view(
247                    render_state,
248                    size_in_pixels[0],
249                    size_in_pixels[1],
250                );
251            }
252
253            if self.needs_reconfigure {
254                self.surface
255                    .configure(&render_state.device, &self.surface_configuration);
256                self.needs_reconfigure = false;
257            }
258
259            let output_frame = match self.surface.get_current_texture() {
260                wgpu::CurrentSurfaceTexture::Success(frame) => frame,
261                wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
262                    self.needs_reconfigure = true;
263                    frame
264                }
265                other => {
266                    match (*self.on_surface_status)(&other) {
267                        SurfaceErrorAction::Reconfigure => {
268                            self.surface
269                                .configure(&render_state.device, &self.surface_configuration);
270                        }
271                        SurfaceErrorAction::RecreateSurface => {
272                            // Full recovery needs `&mut self`, which conflicts with the live
273                            // `render_state` / `self.surface` borrows here. Defer to the top
274                            // of the next paint via the `needs_recreate` flag, and request a
275                            // repaint so the next frame actually invokes `paint` to consume it.
276                            self.needs_recreate = true;
277                            self.ctx.request_repaint();
278                        }
279                        SurfaceErrorAction::SkipFrame => {}
280                    }
281                    return Ok(());
282                }
283            };
284
285            {
286                let renderer = render_state.renderer.read();
287
288                let target_texture = if capture {
289                    let capture_state = self.screen_capture_state.get_or_insert_with(|| {
290                        CaptureState::new(&render_state.device, &output_frame.texture)
291                    });
292                    capture_state.update(&render_state.device, &output_frame.texture);
293
294                    &capture_state.texture
295                } else {
296                    &output_frame.texture
297                };
298                let target_view =
299                    target_texture.create_view(&wgpu::TextureViewDescriptor::default());
300
301                let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
302                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
303                        view: &target_view,
304                        resolve_target: None,
305                        ops: wgpu::Operations {
306                            load: wgpu::LoadOp::Clear(wgpu::Color {
307                                r: clear_color[0] as f64,
308                                g: clear_color[1] as f64,
309                                b: clear_color[2] as f64,
310                                a: clear_color[3] as f64,
311                            }),
312                            store: wgpu::StoreOp::Store,
313                        },
314                        depth_slice: None,
315                    })],
316                    depth_stencil_attachment: self.depth_texture_view.as_ref().map(|view| {
317                        wgpu::RenderPassDepthStencilAttachment {
318                            view,
319                            depth_ops: self
320                                .depth_stencil_format
321                                .is_some_and(|depth_stencil_format| {
322                                    depth_stencil_format.has_depth_aspect()
323                                })
324                                .then_some(wgpu::Operations {
325                                    load: wgpu::LoadOp::Clear(1.0),
326                                    // It is very unlikely that the depth buffer is needed after egui finished rendering
327                                    // so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon)
328                                    store: wgpu::StoreOp::Discard,
329                                }),
330                            stencil_ops: self
331                                .depth_stencil_format
332                                .is_some_and(|depth_stencil_format| {
333                                    depth_stencil_format.has_stencil_aspect()
334                                })
335                                .then_some(wgpu::Operations {
336                                    load: wgpu::LoadOp::Clear(0),
337                                    store: wgpu::StoreOp::Discard,
338                                }),
339                        }
340                    }),
341                    label: Some("egui_render"),
342                    occlusion_query_set: None,
343                    timestamp_writes: None,
344                    multiview_mask: None,
345                });
346
347                // Forgetting the pass' lifetime means that we are no longer compile-time protected from
348                // runtime errors caused by accessing the parent encoder before the render pass is dropped.
349                // Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here!
350                renderer.render(
351                    &mut render_pass.forget_lifetime(),
352                    clipped_primitives,
353                    &screen_descriptor,
354                );
355            }
356
357            let capture_buffer = if capture
358                && let Some(capture_state) = &mut self.screen_capture_state
359            {
360                Some(capture_state.copy_textures(&render_state.device, &output_frame, &mut encoder))
361            } else {
362                None
363            };
364
365            Some((output_frame, capture_buffer))
366        };
367
368        // Submit the commands: both the main buffer and user-defined ones.
369        render_state
370            .queue
371            .submit(core::iter::chain(user_cmd_bufs, [encoder.finish()]));
372
373        if let Some((frame, capture_buffer)) = frame_and_capture_buffer {
374            if let Some(capture_buffer) = capture_buffer
375                && let Some(capture_state) = &self.screen_capture_state
376            {
377                capture_state.read_screen_rgba(
378                    self.ctx.clone(),
379                    capture_buffer,
380                    capture_data,
381                    self.capture_tx.clone(),
382                    ViewportId::ROOT,
383                );
384            }
385
386            render_state.queue.present(frame);
387        }
388
389        // Free textures marked for destruction **after** queue submit since they might still be used in the current frame.
390        // Calling `wgpu::Texture::destroy` on a texture that is still in use would invalidate the command buffer(s) it is used in.
391        // However, once we called `wgpu::Queue::submit`, it is up for wgpu to determine how long the underlying gpu resource has to live.
392        {
393            let mut renderer = render_state.renderer.write();
394            #[expect(clippy::iter_over_hash_type)] // Order doesn't matter here
395            for id in textures_delta.free.drain() {
396                renderer.free_texture(&id);
397            }
398        }
399
400        Ok(())
401    }
402
403    fn handle_screenshots(&mut self, events: &mut Vec<Event>) {
404        for (viewport_id, user_data, screenshot) in self.capture_rx.try_iter() {
405            let screenshot = Arc::new(screenshot);
406            for data in user_data {
407                events.push(Event::Screenshot {
408                    viewport_id,
409                    user_data: data,
410                    image: Arc::clone(&screenshot),
411                });
412            }
413        }
414    }
415
416    fn destroy(&mut self) {
417        self.render_state = None;
418    }
419}