1use std::any::Any;
4use std::ops::Range;
5use std::sync::{Arc, OnceLock};
6
7use mln_gfx::gpu::validation::{
8 self, BindingsTags, BufferInfo, GeometryTags, LayoutTags, Lookup, PassTarget, PipelineTags, ShaderBinding,
9 TextureInfo,
10};
11use mln_gfx::gpu::{
12 BindGroupEntry, BindingsDesc, BindingsId, BufferDesc, BufferId, BufferUsage, Caps, ClipDepthRange, Draw,
13 DynamicState, GeometryDesc, GeometryId, Gpu, GpuError, LoadOp, PassDesc, PipelineDesc, PipelineId, ReadbackId,
14 ResourceId, SamplerId, Scissor, ShaderId, ShaderKey, SlotMap, TextureDesc, TextureFormat, TextureId, TextureRegion,
15 TextureUsage,
16};
17use mln_gfx::texture2d::SamplerState;
18use mln_gfx::types::{TextureFilterType, TextureWrapType};
19use mln_util::Color;
20use mln_util::size::Size;
21
22use crate::index_table::IndexTable;
23use crate::shaders::shader_program::{self, BindingType, ShaderProgram, validated};
24use crate::writes::Writes;
25use crate::{CustomLayerEncoder, CustomLayerPass, Device};
26
27const PAGE: u64 = 16 << 10;
30
31const UNIFORM_ALIGNMENT: u64 = 256;
35
36struct Buffer {
38 buffer: wgpu::Buffer,
39 usage: BufferUsage,
40 offset: u64,
42 size: u64,
45 written: Option<u64>,
49}
50
51struct Texture {
52 texture: wgpu::Texture,
53 view: wgpu::TextureView,
54}
55
56struct Shader {
58 program: ShaderProgram,
59 reads: Vec<ShaderBinding>,
60}
61
62struct Pipeline {
63 pipeline: wgpu::RenderPipeline,
64 tags: PipelineTags,
65}
66
67struct Bindings {
70 groups: Vec<(u32, wgpu::BindGroup)>,
71 index_slot: Option<u32>,
72 tags: BindingsTags,
73}
74
75struct Geometry {
79 vertex_buffers: Vec<(wgpu::Buffer, Range<u64>)>,
80 index_buffer: (wgpu::Buffer, Range<u64>),
81 vertex_ids: Vec<(BufferId, u64)>,
84 index_id: (BufferId, u64),
85 tags: GeometryTags,
86}
87
88struct Readback {
90 buffer: wgpu::Buffer,
91 padded_bytes_per_row: usize,
94 bytes_per_row: usize,
95 rows: usize,
96 #[cfg_attr(target_family = "wasm", expect(dead_code, reason = "a browser can't wait for a submission"))]
97 submission: wgpu::SubmissionIndex,
98 mapped: Arc<OnceLock<Result<(), wgpu::BufferAsyncError>>>,
100}
101
102struct OpenPass {
104 pass: wgpu::RenderPass<'static>,
105 target: PassTarget,
106 color_format: Option<wgpu::TextureFormat>,
109 depth_stencil_format: Option<wgpu::TextureFormat>,
110 pipeline: Option<PipelineId>,
113 bindings: Option<BindingsId>,
114 global_index: Option<u32>,
115 geometry: Option<GeometryId>,
116 vertex_buffers: Vec<(BufferId, u64)>,
120 index_buffer: Option<(BufferId, u64)>,
121 dynamic: Option<DynamicState>,
122}
123
124impl OpenPass {
125 fn forget_state(&mut self) {
127 self.pipeline = None;
128 self.bindings = None;
129 self.global_index = None;
130 self.geometry = None;
131 self.vertex_buffers.clear();
132 self.index_buffer = None;
133 self.dynamic = None;
134 }
135}
136
137pub struct WebGpu {
153 device: Device,
154 caps: Caps,
155 index_table: IndexTable,
156 buffers: SlotMap<BufferId, Buffer>,
157 uniform_page: Option<(wgpu::Buffer, u64)>,
160 geometry_page: Option<(wgpu::Buffer, u64)>,
163 writes: Writes,
164 textures: SlotMap<TextureId, Texture>,
165 samplers: SlotMap<SamplerId, wgpu::Sampler>,
166 shaders: SlotMap<ShaderId, Shader>,
167 layout_tags: LayoutTags,
168 pipelines: SlotMap<PipelineId, Pipeline>,
169 bindings: SlotMap<BindingsId, Bindings>,
170 geometries: SlotMap<GeometryId, Geometry>,
171 readbacks: SlotMap<ReadbackId, Readback>,
172 spare_readback: Option<wgpu::Buffer>,
175 encoder: Option<wgpu::CommandEncoder>,
177 pass: Option<OpenPass>,
178}
179
180impl WebGpu {
181 #[cfg(test)]
183 pub(crate) fn texture_count(&self) -> usize {
184 self.textures.len()
185 }
186
187 #[must_use]
188 pub fn new(device: &Device) -> WebGpu {
189 let limits = device.device().limits();
190 let caps = Caps {
191 buffer_offset_alignment: limits
192 .min_uniform_buffer_offset_alignment
193 .max(limits.min_storage_buffer_offset_alignment),
194 max_texture_size: limits.max_texture_dimension_2d,
195 half_float_render_targets: true,
196 clip_depth: ClipDepthRange::ZeroToOne,
197 render_target_depth: Some(TextureFormat::Depth32Float),
198 clear_stencil_with_pass: false,
199 line_expressions: false,
200 cpu_rasterizer: device.adapter_info().device_type == wgpu::DeviceType::Cpu,
201 max_line_width: 1.0,
202 };
203 WebGpu {
204 index_table: IndexTable::new(device.device()),
205 device: device.clone(),
206 caps,
207 buffers: SlotMap::with_key(),
208 uniform_page: None,
209 geometry_page: None,
210 writes: Writes::default(),
211 textures: SlotMap::with_key(),
212 samplers: SlotMap::with_key(),
213 shaders: SlotMap::with_key(),
214 layout_tags: LayoutTags::default(),
215 pipelines: SlotMap::with_key(),
216 bindings: SlotMap::with_key(),
217 geometries: SlotMap::with_key(),
218 readbacks: SlotMap::with_key(),
219 spare_readback: None,
220 encoder: None,
221 pass: None,
222 }
223 }
224
225 pub fn import_texture(&mut self, texture: &wgpu::Texture) -> TextureId {
229 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
230 self.textures.insert(Texture { texture: texture.clone(), view })
231 }
232
233 #[cfg(test)]
235 pub(crate) fn native_texture(&self, texture: TextureId) -> Option<&wgpu::Texture> {
236 self.textures.get(texture).map(|texture| &texture.texture)
237 }
238
239 #[cfg(test)]
241 pub(crate) fn readback_buffer(&self, readback: ReadbackId) -> Option<&wgpu::Buffer> {
242 self.readbacks.get(readback).map(|readback| &readback.buffer)
243 }
244
245 fn submit(&mut self, then: impl FnOnce(&mut wgpu::CommandEncoder)) -> Result<wgpu::SubmissionIndex, GpuError> {
248 let mut encoder = self.encoder.take().unwrap_or_else(|| {
249 self.device.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
250 });
251 then(&mut encoder);
252 let command_buffer = self.validated("flush", |_| encoder.finish())?;
255 let writes = self.writes.encode(self.device.device(), self.device.queue());
256 Ok(self.device.queue().submit(writes.into_iter().chain([command_buffer])))
257 }
258
259 fn info(&self) -> (impl Fn(BufferId) -> Option<BufferInfo> + '_, impl Fn(TextureId) -> Option<TextureInfo> + '_) {
260 let buffer =
261 |id| self.buffers.get(id).map(|buffer: &Buffer| BufferInfo { usage: buffer.usage, size: buffer.size });
262 let texture = |id| self.textures.get(id).map(|texture: &Texture| texture_info(&texture.texture));
263 (buffer, texture)
264 }
265
266 fn begin_render_pass(
270 &mut self,
271 desc: &PassDesc<'_>,
272 ) -> Result<(wgpu::RenderPass<'static>, Option<wgpu::TextureFormat>, Option<wgpu::TextureFormat>), GpuError> {
273 let texture = |id| self.textures.get(id).ok_or(GpuError::UnknownId("texture"));
274 let color = desc
275 .color
276 .map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment.load)))
277 .transpose()?;
278 let depth_stencil = desc
279 .depth_stencil
280 .map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment)))
281 .transpose()?;
282 let color_format = color.map(|(texture, _)| texture.texture.format());
283 let depth_stencil_format = depth_stencil.map(|(texture, _)| texture.texture.format());
284 let color_attachment = color.map(|(texture, load)| wgpu::RenderPassColorAttachment {
285 view: &texture.view,
286 depth_slice: None,
287 resolve_target: None,
288 ops: wgpu::Operations {
289 load: match load {
290 LoadOp::Load => wgpu::LoadOp::Load,
291 LoadOp::Clear(color) => wgpu::LoadOp::Clear(wgpu_color(color)),
292 },
293 store: wgpu::StoreOp::Store,
294 },
295 });
296 let depth_stencil_attachment =
297 depth_stencil.map(|(texture, attachment)| wgpu::RenderPassDepthStencilAttachment {
298 view: &texture.view,
299 depth_ops: Some(wgpu::Operations {
300 load: match attachment.depth {
301 LoadOp::Load => wgpu::LoadOp::Load,
302 LoadOp::Clear(depth) => wgpu::LoadOp::Clear(depth),
303 },
304 store: wgpu::StoreOp::Store,
305 }),
306 stencil_ops: texture.texture.format().has_stencil_aspect().then_some(wgpu::Operations {
307 load: match attachment.stencil {
308 LoadOp::Load => wgpu::LoadOp::Load,
309 LoadOp::Clear(stencil) => wgpu::LoadOp::Clear(stencil),
310 },
311 store: wgpu::StoreOp::Store,
312 }),
313 });
314 let device = self.device.device();
315 let encoder = self.encoder.get_or_insert_with(|| {
316 device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
317 });
318 let pass = encoder
319 .begin_render_pass(&wgpu::RenderPassDescriptor {
320 label: Some(desc.label),
321 color_attachments: &[color_attachment],
322 depth_stencil_attachment,
323 timestamp_writes: None,
324 occlusion_query_set: None,
325 multiview_mask: None,
326 })
327 .forget_lifetime();
328 Ok((pass, color_format, depth_stencil_format))
329 }
330
331 fn no_pass(what: &str) -> GpuError {
332 GpuError::Invalid(format!("{what} outside a pass"))
333 }
334
335 fn open_pass(what: &str) -> GpuError {
336 GpuError::Invalid(format!("{what} while a pass is open"))
337 }
338
339 #[cfg(not(target_family = "wasm"))]
342 fn wait_for(&self, submission: Option<&wgpu::SubmissionIndex>) -> Result<(), GpuError> {
343 const WAIT_AGAIN_LIMIT: std::time::Duration = std::time::Duration::from_secs(1);
346 let device = self.device.device();
347 let wait = || device.poll(wgpu::PollType::Wait { submission_index: submission.cloned(), timeout: None });
348 let start = mln_util::time::Instant::now();
353 let mut waited = wait();
354 while matches!(waited, Err(wgpu::PollError::Timeout)) && start.elapsed() < WAIT_AGAIN_LIMIT {
355 waited = wait();
356 }
357 waited.map(drop).map_err(|error| GpuError::Invalid(format!("waiting for the GPU: {error}")))
358 }
359
360 fn allocate_uniform(&mut self, size: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
363 let mut page = self.uniform_page.take();
364 let allocated = allocate_in_page(&mut page, size.next_multiple_of(UNIFORM_ALIGNMENT), || {
365 self.create_uniform_buffer("uniform page", PAGE)
366 });
367 self.uniform_page = page;
368 allocated
369 }
370
371 fn allocate_geometry(&mut self, size: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
374 let mut page = self.geometry_page.take();
375 let allocated = allocate_in_page(&mut page, size, || {
376 self.validated("geometry page", |device| {
377 device.create_buffer(&wgpu::BufferDescriptor {
378 label: Some("geometry page"),
379 size: PAGE,
380 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
381 mapped_at_creation: false,
382 })
383 })
384 });
385 self.geometry_page = page;
386 allocated
387 }
388
389 fn create_uniform_buffer(&self, label: &str, size: u64) -> Result<wgpu::Buffer, GpuError> {
391 self.validated(label, |device| {
392 device.create_buffer(&wgpu::BufferDescriptor {
393 label: Some(label),
394 size,
395 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
396 mapped_at_creation: false,
397 })
398 })
399 }
400
401 fn validated<T>(&self, what: &str, create: impl FnOnce(&wgpu::Device) -> T) -> Result<T, GpuError> {
404 let device = self.device.device();
405 validated(device, || create(device)).map_err(|error| GpuError::Invalid(format!("{what}: {error}")))
406 }
407}
408
409fn allocate_in_page(
412 page: &mut Option<(wgpu::Buffer, u64)>,
413 size: u64,
414 create: impl FnOnce() -> Result<wgpu::Buffer, GpuError>,
415) -> Result<(wgpu::Buffer, u64), GpuError> {
416 let (buffer, taken) = match page {
417 Some((buffer, taken)) if *taken + size <= PAGE => (buffer, taken),
418 _ => {
419 let (buffer, taken) = page.insert((create()?, 0));
420 (buffer, taken)
421 }
422 };
423 let offset = *taken;
424 *taken += size;
425 Ok((buffer.clone(), offset))
426}
427
428fn texture_info(texture: &wgpu::Texture) -> TextureInfo {
430 let usage = texture.usage();
431 TextureInfo {
432 format: from_wgpu_format(texture.format()),
433 size: Size { width: texture.width(), height: texture.height() },
434 usage: TextureUsage {
435 sampled: usage.contains(wgpu::TextureUsages::TEXTURE_BINDING),
436 render_target: usage.contains(wgpu::TextureUsages::RENDER_ATTACHMENT),
437 copy_src: usage.contains(wgpu::TextureUsages::COPY_SRC),
438 },
439 }
440}
441
442fn wgpu_color(color: Color) -> wgpu::Color {
443 wgpu::Color { r: f64::from(color.r), g: f64::from(color.g), b: f64::from(color.b), a: f64::from(color.a) }
444}
445
446fn texture_format(format: TextureFormat) -> wgpu::TextureFormat {
447 match format {
448 TextureFormat::R8Unorm | TextureFormat::A8Unorm => wgpu::TextureFormat::R8Unorm,
450 TextureFormat::R16Float => wgpu::TextureFormat::R16Float,
451 TextureFormat::R32Float => wgpu::TextureFormat::R32Float,
452 TextureFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
453 TextureFormat::Rgba8UnormSrgb => wgpu::TextureFormat::Rgba8UnormSrgb,
454 TextureFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
455 TextureFormat::Bgra8UnormSrgb => wgpu::TextureFormat::Bgra8UnormSrgb,
456 TextureFormat::Rgb10a2Unorm => wgpu::TextureFormat::Rgb10a2Unorm,
457 TextureFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
458 TextureFormat::Rgba32Float => wgpu::TextureFormat::Rgba32Float,
459 TextureFormat::Depth32Float => wgpu::TextureFormat::Depth32Float,
460 TextureFormat::Depth24PlusStencil8 => wgpu::TextureFormat::Depth24PlusStencil8,
461 TextureFormat::Depth32FloatStencil8 => wgpu::TextureFormat::Depth32FloatStencil8,
462 }
463}
464
465fn shader_bindings(shader: &ShaderProgram) -> Result<Vec<ShaderBinding>, GpuError> {
467 let mut bindings = Vec::new();
468 for &group in shader.bind_group_order() {
469 if Some(group) == shader.index_group() {
470 continue;
471 }
472 for info in shader.binding_infos(group) {
473 let binding = match info.type_ {
474 BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer | BindingType::StorageBuffer => {
475 ShaderBinding::Buffer { id: info.binding, min_size: shader.buffer_size(group, info.binding) }
476 }
477 BindingType::Sampler | BindingType::Texture | BindingType::UnfilterableTexture => {
478 let sampler = info.type_ == BindingType::Sampler;
479 let id = shader.texture_at(info.binding, sampler).ok_or_else(|| {
480 GpuError::Invalid(format!(
481 "{} reads binding {} with no texture id",
482 shader.name(),
483 info.binding
484 ))
485 })?;
486 ShaderBinding::Texture { id: id as u32 }
487 }
488 };
489 if !bindings.contains(&binding) {
490 bindings.push(binding);
491 }
492 }
493 }
494 Ok(bindings)
495}
496
497pub(crate) fn from_wgpu_format(format: wgpu::TextureFormat) -> Option<TextureFormat> {
500 Some(match format {
501 wgpu::TextureFormat::R8Unorm => TextureFormat::R8Unorm,
502 wgpu::TextureFormat::R16Float => TextureFormat::R16Float,
503 wgpu::TextureFormat::R32Float => TextureFormat::R32Float,
504 wgpu::TextureFormat::Rgba8Unorm => TextureFormat::Rgba8Unorm,
505 wgpu::TextureFormat::Rgba8UnormSrgb => TextureFormat::Rgba8UnormSrgb,
506 wgpu::TextureFormat::Bgra8Unorm => TextureFormat::Bgra8Unorm,
507 wgpu::TextureFormat::Bgra8UnormSrgb => TextureFormat::Bgra8UnormSrgb,
508 wgpu::TextureFormat::Rgb10a2Unorm => TextureFormat::Rgb10a2Unorm,
509 wgpu::TextureFormat::Rgba16Float => TextureFormat::Rgba16Float,
510 wgpu::TextureFormat::Rgba32Float => TextureFormat::Rgba32Float,
511 wgpu::TextureFormat::Depth32Float => TextureFormat::Depth32Float,
512 wgpu::TextureFormat::Depth24PlusStencil8 => TextureFormat::Depth24PlusStencil8,
513 wgpu::TextureFormat::Depth32FloatStencil8 => TextureFormat::Depth32FloatStencil8,
514 _ => return None,
515 })
516}
517
518impl Gpu for WebGpu {
519 fn caps(&self) -> &Caps {
520 &self.caps
521 }
522
523 fn create_buffer(&mut self, desc: &BufferDesc<'_>) -> Result<BufferId, GpuError> {
524 let size = desc.size.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
525 let usage = match desc.usage {
526 BufferUsage::Vertex | BufferUsage::Index if size <= PAGE / 4 => {
527 let (buffer, offset) = self.allocate_geometry(size)?;
528 let written = Some(0);
529 return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
530 }
531 BufferUsage::Vertex => wgpu::BufferUsages::VERTEX,
532 BufferUsage::Index => wgpu::BufferUsages::INDEX,
533 BufferUsage::Uniform | BufferUsage::Storage => {
534 let (buffer, offset, written) = if size <= PAGE / 4 {
535 let (page, offset) = self.allocate_uniform(size)?;
536 (page, offset, Some(0))
537 } else {
538 (self.create_uniform_buffer(desc.label, size)?, 0, None)
539 };
540 return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
541 }
542 };
543 let buffer = self.validated(desc.label, |device| {
544 device.create_buffer(&wgpu::BufferDescriptor {
545 label: Some(desc.label),
546 size,
547 usage: usage | wgpu::BufferUsages::COPY_DST,
548 mapped_at_creation: false,
549 })
550 })?;
551 Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset: 0, size, written: None }))
552 }
553
554 fn write_buffer(&mut self, buffer: BufferId, offset: u64, data: &[u8]) -> Result<(), GpuError> {
555 let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
556 validation::check_write(offset, data.len(), entry.size)?;
557 let end = offset + data.len() as u64;
558 let padded = match &mut entry.written {
562 Some(written) if end >= *written => {
563 *written = end;
564 entry.size - offset
565 }
566 _ => data.len() as u64,
567 };
568 let (device, queue) = (self.device.device(), self.device.queue());
569 self.writes.write_padded(device, queue, &entry.buffer, entry.offset + offset, data, padded);
570 Ok(())
571 }
572
573 #[cfg(target_family = "wasm")]
576 fn write_buffer_from_host(
577 &mut self,
578 buffer: BufferId,
579 offset: u64,
580 data: &mln_util::host_bytes::HostBytes,
581 ) -> Result<(), GpuError> {
582 let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
583 validation::check_write(offset, data.len().next_multiple_of(4), entry.size)?;
584 let len = data.len() as u64;
585 if let Some(written) = &mut entry.written {
587 *written = (*written).max(offset + len);
588 }
589 let (device, queue) = (self.device.device(), self.device.queue());
590 let at = entry.offset + offset;
591 let aligned = len & !(wgpu::COPY_BUFFER_ALIGNMENT - 1);
592 self.writes.write_from_host(device, queue, &entry.buffer, at, data, aligned);
593 if aligned < len
594 && let Some(array) = data.array()
595 {
596 let mut tail = [0u8; wgpu::COPY_BUFFER_ALIGNMENT as usize];
598 array.subarray(aligned as u32, len as u32).copy_to(&mut tail[..(len - aligned) as usize]);
599 self.writes.write_padded(device, queue, &entry.buffer, at + aligned, &tail, wgpu::COPY_BUFFER_ALIGNMENT);
600 }
601 Ok(())
602 }
603
604 fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError> {
605 let mut usage = wgpu::TextureUsages::empty();
606 if desc.usage.sampled {
607 usage |= wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
608 }
609 if desc.usage.render_target {
610 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
611 }
612 if desc.usage.copy_src {
613 usage |= wgpu::TextureUsages::COPY_SRC;
614 }
615 let format = texture_format(desc.format);
616 let required = format.required_features();
617 if !self.device.device().features().contains(required) {
618 return Err(GpuError::Unsupported(format!("{:?} textures need {required:?}", desc.format)));
619 }
620 let texture = self.validated(desc.label, |device| {
621 device.create_texture(&wgpu::TextureDescriptor {
622 label: Some(desc.label),
623 size: wgpu::Extent3d { width: desc.size.width, height: desc.size.height, depth_or_array_layers: 1 },
624 mip_level_count: 1,
625 sample_count: 1,
626 dimension: wgpu::TextureDimension::D2,
627 format,
628 usage,
629 view_formats: &[],
630 })
631 })?;
632 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
633 Ok(self.textures.insert(Texture { texture, view }))
634 }
635
636 fn write_texture(&mut self, texture: TextureId, region: TextureRegion, data: &[u8]) -> Result<(), GpuError> {
637 let texture = &self.textures.get(texture).ok_or(GpuError::UnknownId("texture"))?.texture;
638 if !texture.usage().contains(wgpu::TextureUsages::COPY_DST) {
639 return Err(GpuError::Invalid("a write to a texture that isn't sampled".to_owned()));
640 }
641 let format = from_wgpu_format(texture.format())
642 .ok_or_else(|| GpuError::Invalid(format!("{:?} textures take no writes", texture.format())))?;
643 let size = Size::new(texture.width(), texture.height());
644 let bytes_per_row = region.write_bytes_per_row(size, format, data)?;
645 self.device.queue().write_texture(
646 wgpu::TexelCopyTextureInfo {
647 texture,
648 mip_level: 0,
649 origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
650 aspect: wgpu::TextureAspect::All,
651 },
652 data,
653 wgpu::TexelCopyBufferLayout {
654 offset: 0,
655 bytes_per_row: Some(bytes_per_row as u32),
656 rows_per_image: Some(region.size.height),
657 },
658 wgpu::Extent3d { width: region.size.width, height: region.size.height, depth_or_array_layers: 1 },
659 );
660 Ok(())
661 }
662
663 fn create_sampler(&mut self, state: &SamplerState) -> Result<SamplerId, GpuError> {
664 let filter = match state.filter {
665 TextureFilterType::Linear => wgpu::FilterMode::Linear,
666 TextureFilterType::Nearest => wgpu::FilterMode::Nearest,
667 };
668 let address_mode = |wrap| match wrap {
669 TextureWrapType::Repeat => wgpu::AddressMode::Repeat,
670 TextureWrapType::Clamp => wgpu::AddressMode::ClampToEdge,
671 };
672 let sampler = self.validated("sampler", |device| {
673 device.create_sampler(&wgpu::SamplerDescriptor {
674 label: None,
675 address_mode_u: address_mode(state.wrap_u),
676 address_mode_v: address_mode(state.wrap_v),
677 address_mode_w: wgpu::AddressMode::ClampToEdge,
678 mag_filter: filter,
679 min_filter: filter,
680 mipmap_filter: if state.mipmapped {
681 wgpu::MipmapFilterMode::Linear
682 } else {
683 wgpu::MipmapFilterMode::Nearest
684 },
685 anisotropy_clamp: u16::from(state.max_anisotropy.max(1)),
686 ..Default::default()
687 })
688 })?;
689 Ok(self.samplers.insert(sampler))
690 }
691
692 fn create_shader(&mut self, key: &ShaderKey) -> Result<ShaderId, GpuError> {
693 let program = shader_program::compile(self.device.device(), self.index_table.layout(), key)?;
694 let reads = shader_bindings(&program)?;
695 Ok(self.shaders.insert(Shader { program, reads }))
696 }
697
698 fn create_pipeline(&mut self, desc: &PipelineDesc<'_>) -> Result<PipelineId, GpuError> {
699 let shader = self.shaders.get(desc.shader).ok_or(GpuError::UnknownId("shader"))?;
700 let pipeline = shader.program.render_pipeline(
701 desc.vertex_buffers,
702 &desc.state,
703 desc.targets.color.map(texture_format),
704 desc.targets.depth_stencil.map(texture_format),
705 )?;
706 let layout = self.layout_tags.tag(desc.shader, desc.vertex_buffers);
707 let tags = PipelineTags { shader: desc.shader, layout, targets: desc.targets };
708 Ok(self.pipelines.insert(Pipeline { pipeline, tags }))
709 }
710
711 fn create_bindings(&mut self, desc: &BindingsDesc<'_>) -> Result<BindingsId, GpuError> {
712 let shader = self.shaders.get(desc.shader).ok_or(GpuError::UnknownId("shader"))?;
713 let elements = {
714 let (buffer, texture) = self.info();
715 let sampler = |id| self.samplers.contains_key(id);
716 let lookup = Lookup { buffer: &buffer, texture: &texture, sampler: &sampler };
717 validation::check_bindings(desc, &shader.reads, self.caps.buffer_offset_alignment, &lookup)?
718 };
719 let program = &shader.program;
720 let mut groups = Vec::new();
721 let mut index_slot = None;
722 for (slot, &group) in program.bind_group_order().iter().enumerate() {
723 if Some(group) == program.index_group() {
724 index_slot = Some(slot as u32);
725 continue;
726 }
727 let layout = program.bind_group_layout(group).ok_or(GpuError::UnknownId("bind group layout"))?;
728 let mut entries = Vec::new();
729 for info in program.binding_infos(group) {
730 let missing = || {
731 GpuError::Invalid(format!(
732 "{} reads binding {} of group {}, which no entry binds",
733 program.name(),
734 info.binding,
735 info.group
736 ))
737 };
738 let resource = match info.type_ {
739 BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer | BindingType::StorageBuffer => {
740 let (buffer, offset, size) = desc
741 .entries
742 .iter()
743 .find_map(|entry| match *entry {
744 BindGroupEntry::Buffer { id, buffer, offset, size } if id == info.binding => {
745 Some((buffer, offset, size))
746 }
747 _ => None,
748 })
749 .ok_or_else(missing)?;
750 let buffer = self.buffers.get(buffer).ok_or(GpuError::UnknownId("buffer"))?;
751 wgpu::BindingResource::Buffer(wgpu::BufferBinding {
752 buffer: &buffer.buffer,
753 offset: buffer.offset + offset,
754 size: wgpu::BufferSize::new(size),
755 })
756 }
757 BindingType::Sampler | BindingType::Texture | BindingType::UnfilterableTexture => {
758 let sampler = info.type_ == BindingType::Sampler;
759 let texture_id = program.texture_at(info.binding, sampler).ok_or_else(missing)? as u32;
760 let (texture, texture_sampler) = desc
761 .entries
762 .iter()
763 .find_map(|entry| match *entry {
764 BindGroupEntry::Texture { id, texture, sampler } if id == texture_id => {
765 Some((texture, sampler))
766 }
767 _ => None,
768 })
769 .ok_or_else(missing)?;
770 if sampler {
771 wgpu::BindingResource::Sampler(
772 self.samplers.get(texture_sampler).ok_or(GpuError::UnknownId("sampler"))?,
773 )
774 } else {
775 wgpu::BindingResource::TextureView(
776 &self.textures.get(texture).ok_or(GpuError::UnknownId("texture"))?.view,
777 )
778 }
779 }
780 };
781 entries.push(wgpu::BindGroupEntry { binding: info.binding, resource });
782 }
783 let group = self.validated(desc.label, |device| {
784 device.create_bind_group(&wgpu::BindGroupDescriptor {
785 label: Some(desc.label),
786 layout,
787 entries: &entries,
788 })
789 })?;
790 groups.push((slot as u32, group));
791 }
792 let tags = BindingsTags { shader: desc.shader, elements };
793 Ok(self.bindings.insert(Bindings { groups, index_slot, tags }))
794 }
795
796 fn create_geometry(&mut self, desc: &GeometryDesc<'_>) -> Result<GeometryId, GpuError> {
797 if !self.shaders.contains_key(desc.shader) {
798 return Err(GpuError::UnknownId("shader"));
799 }
800 let ranges = {
801 let (buffer, texture) = self.info();
802 let lookup = Lookup { buffer: &buffer, texture: &texture, sampler: &|_| false };
803 validation::check_geometry(desc, &lookup)?
804 };
805 let native = |id: BufferId, offset: u64| {
806 let buffer = self.buffers.get(id).ok_or(GpuError::UnknownId("buffer"))?;
807 Ok::<_, GpuError>((buffer.buffer.clone(), buffer.offset + offset..buffer.offset + buffer.size))
808 };
809 let vertex_buffers =
810 desc.vertex_buffers.iter().map(|&(id, offset)| native(id, offset)).collect::<Result<Vec<_>, _>>()?;
811 let index_buffer = native(desc.index_buffer, 0)?;
812 let tags = GeometryTags { layout: self.layout_tags.tag(desc.shader, desc.layouts), ranges };
813 Ok(self.geometries.insert(Geometry {
814 vertex_buffers,
815 index_buffer,
816 vertex_ids: desc.vertex_buffers.to_vec(),
817 index_id: (desc.index_buffer, 0),
818 tags,
819 }))
820 }
821
822 fn destroy(&mut self, resource: ResourceId) {
825 match resource {
826 ResourceId::Buffer(id) => drop(self.buffers.remove(id)),
827 ResourceId::Texture(id) => drop(self.textures.remove(id)),
828 ResourceId::Sampler(id) => drop(self.samplers.remove(id)),
829 ResourceId::Shader(id) => drop(self.shaders.remove(id)),
830 ResourceId::Pipeline(id) => drop(self.pipelines.remove(id)),
831 ResourceId::Bindings(id) => drop(self.bindings.remove(id)),
832 ResourceId::Geometry(id) => drop(self.geometries.remove(id)),
833 ResourceId::Readback(id) => drop(self.readbacks.remove(id)),
834 }
835 }
836
837 fn begin_pass(&mut self, desc: &PassDesc<'_>) -> Result<(), GpuError> {
838 if self.pass.is_some() {
839 return Err(Self::open_pass("a pass"));
840 }
841 let target = {
842 let (_, texture) = self.info();
843 validation::check_pass(desc, &texture)?
844 };
845 let (pass, color_format, depth_stencil_format) = self.begin_render_pass(desc)?;
846 self.pass = Some(OpenPass {
847 pass,
848 target,
849 color_format,
850 depth_stencil_format,
851 pipeline: None,
852 bindings: None,
853 global_index: None,
854 geometry: None,
855 vertex_buffers: Vec::new(),
856 index_buffer: None,
857 dynamic: Some(DynamicState {
858 depth_range: (0.0, 1.0),
859 scissor: Scissor { x: 0, y: 0, width: target.size.width, height: target.size.height },
860 stencil_reference: 0,
861 blend_constant: Color::new_unchecked(0.0, 0.0, 0.0, 0.0),
862 line_width: 1.0,
863 }),
864 });
865 Ok(())
866 }
867
868 fn draw(&mut self, draw: &Draw) -> Result<(), GpuError> {
869 let open = self.pass.as_mut().ok_or_else(|| Self::no_pass("a draw"))?;
870 let pipeline = self.pipelines.get(draw.pipeline).ok_or(GpuError::UnknownId("pipeline"))?;
871 let bindings = self.bindings.get(draw.bindings).ok_or(GpuError::UnknownId("bindings"))?;
872 let geometry = self.geometries.get(draw.geometry).ok_or(GpuError::UnknownId("geometry"))?;
873 validation::check_draw(draw, open.target.targets, &pipeline.tags, &bindings.tags, &geometry.tags)?;
874 let pass = &mut open.pass;
875 if open.pipeline != Some(draw.pipeline) {
876 pass.set_pipeline(&pipeline.pipeline);
877 open.pipeline = Some(draw.pipeline);
878 }
879 let bindings_changed = open.bindings != Some(draw.bindings);
880 if bindings_changed {
881 for (slot, group) in &bindings.groups {
882 pass.set_bind_group(*slot, group, &[]);
883 }
884 open.bindings = Some(draw.bindings);
885 }
886 if let Some(slot) = bindings.index_slot
887 && (bindings_changed || open.global_index != Some(draw.global_index))
888 {
889 self.index_table.reserve(self.device.device(), self.device.queue(), draw.global_index);
890 let (group, offset) = self
891 .index_table
892 .get(draw.global_index)
893 .ok_or_else(|| GpuError::Invalid(format!("global index {}", draw.global_index)))?;
894 pass.set_bind_group(slot, group, &[offset]);
895 open.global_index = Some(draw.global_index);
896 }
897 if open.geometry != Some(draw.geometry) {
898 for (slot, ((buffer, range), id)) in geometry.vertex_buffers.iter().zip(&geometry.vertex_ids).enumerate() {
899 if open.vertex_buffers.get(slot) != Some(id) {
900 pass.set_vertex_buffer(slot as u32, buffer.slice(range.clone()));
901 match open.vertex_buffers.get_mut(slot) {
902 Some(bound) => *bound = *id,
903 None => open.vertex_buffers.push(*id),
904 }
905 }
906 }
907 if open.index_buffer != Some(geometry.index_id) {
908 let (buffer, range) = &geometry.index_buffer;
909 pass.set_index_buffer(buffer.slice(range.clone()), wgpu::IndexFormat::Uint16);
910 open.index_buffer = Some(geometry.index_id);
911 }
912 open.geometry = Some(draw.geometry);
913 }
914 let dynamic = draw.dynamic;
915 let last = open.dynamic.replace(dynamic);
916 let changed = |same: fn(&DynamicState, &DynamicState) -> bool| last.is_none_or(|last| !same(&last, &dynamic));
917 if changed(|a, b| a.depth_range == b.depth_range) {
918 let size = open.target.size;
919 let (min, max) = dynamic.depth_range;
920 pass.set_viewport(0.0, 0.0, size.width as f32, size.height as f32, min, max);
921 }
922 if changed(|a, b| a.scissor == b.scissor) {
923 let Scissor { x, y, width, height } = dynamic.scissor;
924 pass.set_scissor_rect(x, y, width, height);
925 }
926 if changed(|a, b| a.stencil_reference == b.stencil_reference) {
927 pass.set_stencil_reference(dynamic.stencil_reference);
928 }
929 if changed(|a, b| a.blend_constant == b.blend_constant) {
930 pass.set_blend_constant(wgpu_color(dynamic.blend_constant));
931 }
932 let indices = draw.first_index..draw.first_index + draw.index_count;
934 let instances = draw.first_instance..draw.first_instance + draw.instance_count;
935 pass.draw_indexed(indices, draw.base_vertex, instances);
936 Ok(())
937 }
938
939 fn lend(&mut self, f: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError> {
942 let (device, queue) = (self.device.device().clone(), self.device.queue().clone());
943 if let Some(mut open) = self.pass.take() {
944 let Some(color_format) = open.color_format else {
945 self.pass = Some(open);
946 return Err(GpuError::Unsupported("a custom layer's pass without a color attachment".to_owned()));
947 };
948 let depth_stencil_format = open.depth_stencil_format;
949 let mut lent =
950 CustomLayerPass { device, queue, pass: open.pass, color_format, depth_stencil_format, sample_count: 1 };
951 f(&mut lent);
952 open.pass = lent.pass;
953 open.forget_state();
954 self.pass = Some(open);
955 return Ok(());
956 }
957 let encoder = self
958 .encoder
959 .take()
960 .unwrap_or_else(|| device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }));
961 let mut lent = CustomLayerEncoder { device, queue, encoder };
962 f(&mut lent);
963 self.encoder = Some(lent.encoder);
964 Ok(())
965 }
966
967 fn end_pass(&mut self) -> Result<(), GpuError> {
968 self.pass.take().map(drop).ok_or_else(|| Self::no_pass("the end of a pass"))
969 }
970
971 fn flush(&mut self, wait: bool) -> Result<(), GpuError> {
972 if self.pass.is_some() {
973 return Err(Self::open_pass("a flush"));
974 }
975 let submission = self.submit(|_| {})?;
976 #[cfg(not(target_family = "wasm"))]
977 if wait {
978 return self.wait_for(Some(&submission));
979 }
980 let _ = (wait, submission);
981 Ok(())
982 }
983
984 fn read_texture(&mut self, texture: TextureId, region: TextureRegion) -> Result<ReadbackId, GpuError> {
987 if self.pass.is_some() {
988 return Err(Self::open_pass("a readback"));
989 }
990 let texture = self.textures.get(texture).map(|texture| texture.texture.clone());
991 let readback = validation::check_readback(texture.as_ref().map(texture_info), region)?;
992 let texture = texture.ok_or(GpuError::UnknownId("texture"))?;
993 let padded_bytes_per_row = readback.bytes_per_row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize);
994 let (width, rows) = (region.size.width, region.size.height);
995 let size = (padded_bytes_per_row * rows as usize) as u64;
996 let buffer = match self.spare_readback.take() {
997 Some(buffer) if buffer.size() == size => buffer,
998 _ => self.validated("readback", |device| {
999 device.create_buffer(&wgpu::BufferDescriptor {
1000 label: Some("readback"),
1001 size,
1002 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1003 mapped_at_creation: false,
1004 })
1005 })?,
1006 };
1007 let submission = self.submit(|encoder| {
1008 encoder.copy_texture_to_buffer(
1009 wgpu::TexelCopyTextureInfo {
1010 texture: &texture,
1011 mip_level: 0,
1012 origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
1013 aspect: wgpu::TextureAspect::All,
1014 },
1015 wgpu::TexelCopyBufferInfo {
1016 buffer: &buffer,
1017 layout: wgpu::TexelCopyBufferLayout {
1018 offset: 0,
1019 bytes_per_row: Some(padded_bytes_per_row as u32),
1020 rows_per_image: Some(rows),
1021 },
1022 },
1023 wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 },
1024 );
1025 })?;
1026 let mapped = Arc::new(OnceLock::new());
1027 let map_ended = Arc::clone(&mapped);
1028 buffer.map_async(wgpu::MapMode::Read, .., move |result| {
1029 let _ = map_ended.set(result);
1030 });
1031 Ok(self.readbacks.insert(Readback {
1032 buffer,
1033 padded_bytes_per_row,
1034 bytes_per_row: readback.bytes_per_row,
1035 rows: rows as usize,
1036 submission,
1037 mapped,
1038 }))
1039 }
1040
1041 fn take_readback(&mut self, readback: ReadbackId, wait: bool) -> Result<Option<Vec<u8>>, GpuError> {
1044 let entry = self.readbacks.get(readback).ok_or(GpuError::UnknownId("readback"))?;
1045 let mapped = Arc::clone(&entry.mapped);
1046 if mapped.get().is_none() {
1047 #[cfg(not(target_family = "wasm"))]
1048 if wait {
1049 if let Err(error) = self.wait_for(Some(&entry.submission)) {
1050 self.readbacks.remove(readback);
1051 return Err(error);
1052 }
1053 } else {
1054 let _ = self.device.device().poll(wgpu::PollType::Poll);
1055 }
1056 #[cfg(target_family = "wasm")]
1057 let _ = wait;
1058 }
1059 let Some(mapped) = mapped.get() else {
1060 return Ok(None);
1061 };
1062 let Readback { buffer, padded_bytes_per_row, bytes_per_row, rows, .. } =
1063 self.readbacks.remove(readback).ok_or(GpuError::UnknownId("readback"))?;
1064 if let Err(error) = mapped {
1065 return Err(GpuError::Invalid(format!("mapping a readback: {error}")));
1066 }
1067 let texels = {
1068 let range = buffer
1069 .get_mapped_range(..)
1070 .map_err(|error| GpuError::Invalid(format!("a readback's range: {error}")))?;
1071 if padded_bytes_per_row == bytes_per_row {
1072 range[..bytes_per_row * rows].to_vec()
1073 } else {
1074 let mut texels = Vec::with_capacity(bytes_per_row * rows);
1075 for row in range.chunks(padded_bytes_per_row).take(rows) {
1076 texels.extend_from_slice(&row[..bytes_per_row]);
1077 }
1078 texels
1079 }
1080 };
1081 buffer.unmap();
1082 self.spare_readback = Some(buffer);
1083 Ok(Some(texels))
1084 }
1085}