-
-
Notifications
You must be signed in to change notification settings - Fork 829
/
Copy pathwebgpu.rs
557 lines (509 loc) · 19.3 KB
/
webgpu.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use crate::quad::Vertex;
use anyhow::anyhow;
use config::{ConfigHandle, GpuInfo, WebGpuPowerPreference};
use std::cell::RefCell;
use std::sync::Arc;
use wgpu::util::DeviceExt;
use window::bitmaps::Texture2d;
use window::raw_window_handle::{
DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
RawWindowHandle, WindowHandle,
};
use window::{BitmapImage, Dimensions, Rect, Window};
#[repr(C)]
#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ShaderUniform {
pub foreground_text_hsb: [f32; 3],
pub milliseconds: u32,
pub projection: [[f32; 4]; 4],
// sampler2D atlas_nearest_sampler;
// sampler2D atlas_linear_sampler;
}
pub struct WebGpuState {
pub adapter_info: wgpu::AdapterInfo,
pub downlevel_caps: wgpu::DownlevelCapabilities,
pub surface: wgpu::Surface<'static>,
pub device: wgpu::Device,
pub queue: Arc<wgpu::Queue>,
pub config: RefCell<wgpu::SurfaceConfiguration>,
pub dimensions: RefCell<Dimensions>,
pub render_pipeline: wgpu::RenderPipeline,
shader_uniform_bind_group_layout: wgpu::BindGroupLayout,
pub texture_bind_group_layout: wgpu::BindGroupLayout,
pub texture_nearest_sampler: wgpu::Sampler,
pub texture_linear_sampler: wgpu::Sampler,
pub handle: RawHandlePair,
}
pub struct RawHandlePair {
window: RawWindowHandle,
display: RawDisplayHandle,
}
impl RawHandlePair {
fn new(window: &Window) -> Self {
Self {
window: window.window_handle().expect("window handle").as_raw(),
display: window.display_handle().expect("display handle").as_raw(),
}
}
}
impl HasWindowHandle for RawHandlePair {
fn window_handle(&self) -> Result<WindowHandle, HandleError> {
unsafe { Ok(WindowHandle::borrow_raw(self.window)) }
}
}
impl HasDisplayHandle for RawHandlePair {
fn display_handle(&self) -> Result<DisplayHandle, HandleError> {
unsafe { Ok(DisplayHandle::borrow_raw(self.display)) }
}
}
pub struct WebGpuTexture {
texture: wgpu::Texture,
width: u32,
height: u32,
queue: Arc<wgpu::Queue>,
}
impl std::ops::Deref for WebGpuTexture {
type Target = wgpu::Texture;
fn deref(&self) -> &Self::Target {
&self.texture
}
}
impl Texture2d for WebGpuTexture {
fn write(&self, rect: Rect, im: &dyn BitmapImage) {
let (im_width, im_height) = im.image_dimensions();
self.queue.write_texture(
wgpu::ImageCopyTexture {
texture: &self.texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: rect.min_x() as u32,
y: rect.min_y() as u32,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
im.pixel_data_slice(),
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(im_width as u32 * 4),
rows_per_image: Some(im_height as u32),
},
wgpu::Extent3d {
width: im_width as u32,
height: im_height as u32,
depth_or_array_layers: 1,
},
);
}
fn read(&self, _rect: Rect, _im: &mut dyn BitmapImage) {
unimplemented!();
}
fn width(&self) -> usize {
self.width as usize
}
fn height(&self) -> usize {
self.height as usize
}
}
impl WebGpuTexture {
pub fn new(width: u32, height: u32, state: &WebGpuState) -> anyhow::Result<Self> {
let limit = state.device.limits().max_texture_dimension_2d;
if width > limit || height > limit {
// Ideally, wgpu would have a fallible create_texture method,
// but it doesn't: instead it will panic if the requested
// dimension is too large.
// So we check the limit ourselves here.
// <https://github.com/wez/wezterm/issues/3713>
anyhow::bail!(
"texture dimensions {width}x{height} exceeed the \
max dimension {limit} supported by your GPU"
);
}
let format = wgpu::TextureFormat::Rgba8UnormSrgb;
let view_formats = if state
.downlevel_caps
.flags
.contains(wgpu::DownlevelFlags::SURFACE_VIEW_FORMATS)
{
vec![format, format.remove_srgb_suffix()]
} else {
vec![]
};
let texture = state.device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some("Texture Atlas"),
view_formats: &view_formats,
});
Ok(Self {
texture,
width,
height,
queue: Arc::clone(&state.queue),
})
}
}
pub fn adapter_info_to_gpu_info(info: wgpu::AdapterInfo) -> GpuInfo {
GpuInfo {
name: info.name,
vendor: Some(info.vendor),
device: Some(info.device),
device_type: format!("{:?}", info.device_type),
driver: if info.driver.is_empty() {
None
} else {
Some(info.driver)
},
driver_info: if info.driver_info.is_empty() {
None
} else {
Some(info.driver_info)
},
backend: format!("{:?}", info.backend),
}
}
fn compute_compatibility_list(
instance: &wgpu::Instance,
backends: wgpu::Backends,
surface: &wgpu::Surface,
) -> Vec<String> {
instance
.enumerate_adapters(backends)
.into_iter()
.map(|a| {
let info = adapter_info_to_gpu_info(a.get_info());
let compatible = a.is_surface_supported(&surface);
format!(
"{}, compatible={}",
info.to_string(),
if compatible { "yes" } else { "NO" }
)
})
.collect()
}
impl WebGpuState {
pub async fn new(
window: &Window,
dimensions: Dimensions,
config: &ConfigHandle,
) -> anyhow::Result<Self> {
let handle = RawHandlePair::new(window);
Self::new_impl(handle, dimensions, config).await
}
pub async fn new_impl(
handle: RawHandlePair,
dimensions: Dimensions,
config: &ConfigHandle,
) -> anyhow::Result<Self> {
let backends = wgpu::Backends::all();
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends,
..Default::default()
});
let surface = unsafe {
instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::from_window(&handle)?)?
};
let mut adapter: Option<wgpu::Adapter> = None;
if let Some(preference) = &config.webgpu_preferred_adapter {
for a in instance.enumerate_adapters(backends) {
if !a.is_surface_supported(&surface) {
let info = adapter_info_to_gpu_info(a.get_info());
log::warn!("{} is not compatible with surface", info.to_string());
continue;
}
let info = a.get_info();
if preference.name != info.name {
continue;
}
if preference.device_type != format!("{:?}", info.device_type) {
continue;
}
if preference.backend != format!("{:?}", info.backend) {
continue;
}
if let Some(driver) = &preference.driver {
if *driver != info.driver {
continue;
}
}
if let Some(vendor) = &preference.vendor {
if *vendor != info.vendor {
continue;
}
}
if let Some(device) = &preference.device {
if *device != info.device {
continue;
}
}
adapter.replace(a);
break;
}
if adapter.is_none() {
let adapters = compute_compatibility_list(&instance, backends, &surface);
log::warn!(
"Your webgpu preferred adapter '{}' was either not \
found or is not compatible with your display. Available:\n{}",
preference.to_string(),
adapters.join("\n")
);
}
}
if adapter.is_none() {
adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: match config.webgpu_power_preference {
WebGpuPowerPreference::HighPerformance => {
wgpu::PowerPreference::HighPerformance
}
WebGpuPowerPreference::LowPower => wgpu::PowerPreference::LowPower,
},
compatible_surface: Some(&surface),
force_fallback_adapter: config.webgpu_force_fallback_adapter,
})
.await;
}
let adapter = adapter.ok_or_else(|| {
let adapters = compute_compatibility_list(&instance, backends, &surface);
anyhow!(
"no compatible adapter found. Available:\n{}",
adapters.join("\n")
)
})?;
let adapter_info = adapter.get_info();
log::trace!("Using adapter: {adapter_info:?}");
let caps = surface.get_capabilities(&adapter);
log::trace!("caps: {caps:?}");
let downlevel_caps = adapter.get_downlevel_capabilities();
log::trace!("downlevel_caps: {downlevel_caps:?}");
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
required_features: wgpu::Features::empty(),
// WebGL doesn't support all of wgpu's features, so if
// we're building for the web we'll have to disable some.
required_limits: if cfg!(target_arch = "wasm32") {
wgpu::Limits::downlevel_webgl2_defaults()
} else {
wgpu::Limits::downlevel_defaults()
}
.using_resolution(adapter.limits()),
label: None,
},
None, // Trace path
)
.await?;
let queue = Arc::new(queue);
// Explicitly request an SRGB format, if available
let pref_format_srgb = caps.formats[0].add_srgb_suffix();
let format = if caps.formats.contains(&pref_format_srgb) {
pref_format_srgb
} else {
caps.formats[0]
};
// Need to check that this is supported, as trying to set
// view_formats without it will cause surface.configure
// to panic
// <https://github.com/wez/wezterm/issues/3565>
let view_formats = if downlevel_caps
.flags
.contains(wgpu::DownlevelFlags::SURFACE_VIEW_FORMATS)
{
vec![format.add_srgb_suffix(), format.remove_srgb_suffix()]
} else {
vec![]
};
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
width: dimensions.pixel_width as u32,
height: dimensions.pixel_height as u32,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: if caps
.alpha_modes
.contains(&wgpu::CompositeAlphaMode::PostMultiplied)
{
wgpu::CompositeAlphaMode::PostMultiplied
} else if caps
.alpha_modes
.contains(&wgpu::CompositeAlphaMode::PreMultiplied)
{
wgpu::CompositeAlphaMode::PreMultiplied
} else {
wgpu::CompositeAlphaMode::Auto
},
view_formats,
desired_maximum_frame_latency: 2,
};
surface.configure(&device, &config);
let shader = device.create_shader_module(wgpu::include_wgsl!("../shader.wgsl"));
let shader_uniform_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some("ShaderUniform bind group layout"),
});
let texture_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
let texture_linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let texture_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
label: Some("texture bind group layout"),
});
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[
&shader_uniform_bind_group_layout,
&texture_bind_group_layout,
&texture_bind_group_layout,
],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[Vertex::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
});
Ok(Self {
adapter_info,
downlevel_caps,
surface,
device,
queue,
config: RefCell::new(config),
dimensions: RefCell::new(dimensions),
render_pipeline,
handle,
shader_uniform_bind_group_layout,
texture_bind_group_layout,
texture_nearest_sampler,
texture_linear_sampler,
})
}
pub fn create_uniform(&self, uniform: ShaderUniform) -> wgpu::BindGroup {
let buffer = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("ShaderUniform Buffer"),
contents: bytemuck::cast_slice(&[uniform]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.shader_uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
label: Some("ShaderUniform Bind Group"),
})
}
#[allow(unused_mut)]
pub fn resize(&self, mut dims: Dimensions) {
// During a live resize on Windows, the Dimensions that we're processing may be
// lagging behind the true client size. We have to take the very latest value
// from the window or else the underlying driver will raise an error about
// the mismatch, so we need to sneakily read through the handle
match self.handle.window {
#[cfg(windows)]
RawWindowHandle::Win32(h) => {
let mut rect = unsafe { std::mem::zeroed() };
unsafe { winapi::um::winuser::GetClientRect(h.hwnd.get() as _, &mut rect) };
dims.pixel_width = (rect.right - rect.left) as usize;
dims.pixel_height = (rect.bottom - rect.top) as usize;
}
_ => {}
}
if dims == *self.dimensions.borrow() {
return;
}
*self.dimensions.borrow_mut() = dims;
let mut config = self.config.borrow_mut();
config.width = dims.pixel_width as u32;
config.height = dims.pixel_height as u32;
if config.width > 0 && config.height > 0 {
// Avoid reconfiguring with a 0 sized surface, as webgpu will
// panic in that case
// <https://github.com/wez/wezterm/issues/2881>
self.surface.configure(&self.device, &config);
}
}
}