1use std::borrow::Cow;
6use std::cell::{Cell, RefCell};
7use std::rc::Rc;
8
9use arrayvec::ArrayVec;
10use dom_struct::dom_struct;
11use js::context::JSContext;
12use pixels::Snapshot;
13use script_bindings::cformat;
14use script_bindings::codegen::GenericBindings::WebGPUBinding::{
15 GPUDeviceMethods, GPUTextureFormat, GPUTextureUsageConstants,
16};
17use script_bindings::reflector::{Reflector, reflect_weak_referenceable_dom_object};
18use script_bindings::trace::RootedTraceableBox;
19use script_webgpu::gpuconvert::convert_texture_descriptor;
20use servo_base::{Epoch, generic_channel};
21use webgpu_traits::{
22 ContextConfiguration, PRESENTATION_BUFFER_COUNT, PendingTexture, WebGPU, WebGPUContextId,
23 WebGPURequest, id,
24};
25use webrender_api::{ImageFormat, ImageKey};
26
27use super::gputexture::GPUTexture;
28use crate::canvas_context::{CanvasContext, CanvasHelpers, HTMLCanvasElementOrOffscreenCanvas};
29use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUTexture_Binding::GPUTextureMethods;
30use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{
31 GPUCanvasAlphaMode, GPUCanvasConfiguration, GPUCanvasContextMethods, GPUExtent3D,
32 GPUExtent3DDict, GPUObjectDescriptorBase, GPUTextureDescriptor, GPUTextureDimension,
33};
34use crate::dom::bindings::codegen::UnionTypes::HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas;
35use crate::dom::bindings::error::{Error, Fallible};
36use crate::dom::bindings::reflector::DomGlobal;
37use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
38use crate::dom::bindings::str::USVString;
39use crate::dom::globalscope::GlobalScope;
40use crate::dom::htmlcanvaselement::HTMLCanvasElement;
41
42fn supported_context_format(format: GPUTextureFormat) -> bool {
44 matches!(
46 format,
47 GPUTextureFormat::Bgra8unorm | GPUTextureFormat::Rgba8unorm
48 )
49}
50
51#[derive(JSTraceable, MallocSizeOf)]
52struct DroppableGPUCanvasContext {
53 #[no_trace]
54 context_id: WebGPUContextId,
55 #[no_trace]
56 channel: WebGPU,
57}
58
59impl Drop for DroppableGPUCanvasContext {
60 fn drop(&mut self) {
61 if let Err(error) = self.channel.0.send(WebGPURequest::DestroyContext {
62 context_id: self.context_id,
63 }) {
64 warn!(
65 "Failed to send DestroyContext({:?}): {error}",
66 self.context_id,
67 );
68 }
69 }
70}
71
72#[dom_struct]
73pub(crate) struct GPUCanvasContext {
74 reflector_: Reflector,
75 canvas: HTMLCanvasElementOrOffscreenCanvas,
77 configuration: RefCell<Option<GPUCanvasConfiguration>>,
79 texture_descriptor: RefCell<Option<GPUTextureDescriptor>>,
81 current_texture: MutNullableDom<GPUTexture>,
83 cleared: Cell<bool>,
86 droppable: DroppableGPUCanvasContext,
87}
88
89impl GPUCanvasContext {
90 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
91 fn new_inherited(
92 global: &GlobalScope,
93 canvas: HTMLCanvasElementOrOffscreenCanvas,
94 channel: WebGPU,
95 ) -> Self {
96 let (sender, receiver) = generic_channel::channel().unwrap();
97 let size = canvas.size().cast().cast_unit();
98 let mut buffer_ids = ArrayVec::<id::BufferId, PRESENTATION_BUFFER_COUNT>::new();
99 for _ in 0..PRESENTATION_BUFFER_COUNT {
100 buffer_ids.push(global.wgpu_id_hub().create_buffer_id());
101 }
102 if let Err(error) = channel.0.send(WebGPURequest::CreateContext {
103 buffer_ids,
104 size,
105 sender,
106 }) {
107 warn!("Failed to send CreateContext ({error:?})");
108 }
109 let context_id = receiver.recv().unwrap();
110
111 Self {
112 reflector_: Reflector::new(),
113 canvas,
114 configuration: RefCell::new(None),
115 texture_descriptor: RefCell::new(None),
116 current_texture: MutNullableDom::default(),
117 cleared: Cell::new(true),
118 droppable: DroppableGPUCanvasContext {
119 context_id,
120 channel,
121 },
122 }
123 }
124
125 pub(crate) fn new(
126 cx: &mut JSContext,
127 global: &GlobalScope,
128 canvas: &HTMLCanvasElement,
129 channel: WebGPU,
130 ) -> DomRoot<Self> {
131 reflect_weak_referenceable_dom_object(
132 cx,
133 Rc::new(GPUCanvasContext::new_inherited(
134 global,
135 HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(Dom::from_ref(canvas)),
136 channel,
137 )),
138 global,
139 )
140 }
141}
142
143impl GPUCanvasContext {
145 pub(crate) fn set_image_key(&self, image_key: ImageKey) {
146 if let Err(error) = self.droppable.channel.0.send(WebGPURequest::SetImageKey {
147 context_id: self.context_id(),
148 image_key,
149 }) {
150 warn!(
151 "Failed to send WebGPURequest::Present({:?}) ({error})",
152 self.context_id()
153 );
154 }
155 }
156
157 pub(crate) fn update_rendering(&self, canvas_epoch: Epoch) -> bool {
159 if let Err(error) = self.droppable.channel.0.send(WebGPURequest::Present {
162 context_id: self.context_id(),
163 pending_texture: self.pending_texture(),
164 size: self.size(),
165 canvas_epoch,
166 }) {
167 warn!(
168 "Failed to send WebGPURequest::Present({:?}) ({error})",
169 self.context_id()
170 );
171 }
172
173 self.expire_current_texture(true);
175
176 true
177 }
178
179 fn texture_descriptor_for_canvas_and_configuration(
181 &self,
182 configuration: &GPUCanvasConfiguration,
183 ) -> GPUTextureDescriptor {
184 let size = self.size();
185 GPUTextureDescriptor {
186 size: GPUExtent3D::GPUExtent3DDict(GPUExtent3DDict {
187 width: size.width,
188 height: size.height,
189 depthOrArrayLayers: 1,
190 }),
191 format: configuration.format,
192 usage: configuration.usage | GPUTextureUsageConstants::COPY_SRC,
195 viewFormats: configuration.viewFormats.clone(),
196 mipLevelCount: 1,
198 sampleCount: 1,
199 parent: GPUObjectDescriptorBase {
200 label: USVString::default(),
201 },
202 dimension: GPUTextureDimension::_2d,
203 }
204 }
205
206 fn expire_current_texture(&self, skip_dirty: bool) {
208 if let Some(current_texture) = self.current_texture.take() {
211 current_texture.Destroy()
217 }
221 if !skip_dirty {
224 self.mark_as_dirty();
226 }
227 }
228
229 fn replace_drawing_buffer(&self) {
231 self.expire_current_texture(false);
233 self.cleared.set(true);
237 }
238}
239
240impl GPUCanvasContext {
242 fn context_configuration(&self) -> Option<ContextConfiguration> {
243 let configuration = self.configuration.borrow();
244 let configuration = configuration.as_ref()?;
245 Some(ContextConfiguration {
246 device_id: configuration.device.id().0,
247 queue_id: configuration.device.queue_id().0,
248 format: match configuration.format {
249 GPUTextureFormat::Bgra8unorm => ImageFormat::BGRA8,
250 GPUTextureFormat::Rgba8unorm => ImageFormat::RGBA8,
251 _ => unreachable!("Configure method should set valid texture format"),
252 },
253 is_opaque: matches!(configuration.alphaMode, GPUCanvasAlphaMode::Opaque),
254 size: self.size(),
255 })
256 }
257
258 fn pending_texture(&self) -> Option<PendingTexture> {
259 self.current_texture.get().map(|texture| PendingTexture {
260 texture_id: texture.id().0,
261 encoder_id: self.global().wgpu_id_hub().create_command_encoder_id(),
262 command_buffer_id: self.global().wgpu_id_hub().create_command_buffer_id(),
263 configuration: self
264 .context_configuration()
265 .expect("Context should be configured if there is a texture."),
266 })
267 }
268}
269
270impl CanvasContext for GPUCanvasContext {
271 type ID = WebGPUContextId;
272
273 fn context_id(&self) -> WebGPUContextId {
274 self.droppable.context_id
275 }
276
277 fn resize(&self) {
279 self.replace_drawing_buffer();
281 let configuration = self.configuration.borrow();
283 if let Some(configuration) = configuration.as_ref() {
285 self.texture_descriptor.replace(Some(
288 self.texture_descriptor_for_canvas_and_configuration(configuration),
289 ));
290 }
291 }
292
293 fn reset_bitmap(&self) {
294 warn!("The GPUCanvasContext 'reset_bitmap' is not implemented yet");
295 }
296
297 fn get_image_data(&self) -> Option<Snapshot> {
299 Some(if self.cleared.get() {
301 Snapshot::cleared(self.size())
302 } else {
303 let (sender, receiver) = generic_channel::channel().unwrap();
304 self.droppable
305 .channel
306 .0
307 .send(WebGPURequest::GetImage {
308 context_id: self.context_id(),
309 pending_texture: self.pending_texture(),
311 sender,
312 })
313 .ok()?;
314 receiver.recv().ok()?.to_owned()
315 })
316 }
317
318 fn canvas(&self) -> Option<RootedHTMLCanvasElementOrOffscreenCanvas> {
319 Some(RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas))
320 }
321
322 fn mark_as_dirty(&self) {
323 self.canvas.mark_as_dirty();
324 }
325}
326
327impl GPUCanvasContextMethods<crate::DomTypeHolder> for GPUCanvasContext {
328 fn Canvas(&self) -> RootedHTMLCanvasElementOrOffscreenCanvas {
330 RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas)
331 }
332
333 fn Configure(&self, configuration: &GPUCanvasConfiguration) -> Fallible<()> {
335 let device = &configuration.device;
337
338 let descriptor = self.texture_descriptor_for_canvas_and_configuration(configuration);
340
341 let (mut wgpu_descriptor, _) =
344 convert_texture_descriptor::<crate::DomTypeHolder>(&descriptor, device)?;
345 wgpu_descriptor.label = Some(Cow::Borrowed(
346 "dummy texture for texture descriptor validation",
347 ));
348
349 if !supported_context_format(configuration.format) {
351 return Err(Error::Type(cformat!(
352 "Unsupported context format: {:?}",
353 configuration.format
354 )));
355 }
356
357 if configuration.usage & GPUTextureUsageConstants::TRANSIENT_ATTACHMENT != 0 {
359 return Err(Error::Type(
360 c"configuration.usage includes the TRANSIENT_ATTACHMENT bit".into(),
361 ));
362 }
363
364 self.configuration.replace(Some(configuration.clone()));
366
367 self.texture_descriptor.replace(Some(descriptor));
369
370 self.replace_drawing_buffer();
372
373 let texture_id = self.global().wgpu_id_hub().create_texture_id();
376 self.droppable
377 .channel
378 .0
379 .send(WebGPURequest::ValidateTextureDescriptor {
380 device_id: device.id().0,
381 texture_id,
382 descriptor: wgpu_descriptor,
383 })
384 .expect("Failed to create WebGPU SwapChain");
385
386 Ok(())
387 }
388
389 fn Unconfigure(&self) {
391 self.configuration.take();
393 self.current_texture.take();
395 self.replace_drawing_buffer();
397 }
398
399 fn GetConfiguration(&self) -> Option<RootedTraceableBox<GPUCanvasConfiguration>> {
401 self.configuration
402 .borrow()
403 .clone()
404 .map(RootedTraceableBox::new)
405 }
406
407 fn GetCurrentTexture(&self, cx: &mut JSContext) -> Fallible<DomRoot<GPUTexture>> {
409 let configuration = self.configuration.borrow();
411 let Some(configuration) = configuration.as_ref() else {
412 return Err(Error::InvalidState(Some(
413 "GPUCanvasContext is not configured".into(),
414 )));
415 };
416 let texture_descriptor = self.texture_descriptor.borrow();
418 let texture_descriptor = texture_descriptor.as_ref().unwrap();
419 let device = &configuration.device;
421 let current_texture = if let Some(current_texture) = self.current_texture.get() {
422 current_texture
423 } else {
424 self.replace_drawing_buffer();
427 let current_texture = device.CreateTexture(cx, texture_descriptor)?;
430 self.current_texture.set(Some(¤t_texture));
431
432 self.cleared.set(false);
434
435 current_texture
436 };
437 Ok(current_texture)
439 }
440}