-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
639 lines (581 loc) · 22.4 KB
/
lib.rs
File metadata and controls
639 lines (581 loc) · 22.4 KB
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::mem;
use wasm_bindgen::prelude::*;
use wgpu::util::DeviceExt;
use winit::{
dpi::PhysicalSize, event_loop::EventLoop, platform::web::WindowBuilderExtWebSys,
window::WindowBuilder,
};
use std::borrow::Cow;
macro_rules! log {
($($t:tt)*) => {
web_sys::console::log_1(&format!($($t)*).into());
}
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
pos: [f32; 3],
color: [f32; 3],
}
impl Vertex {
fn layout() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
// pos
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
// color
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
],
}
}
}
const VERTICES: &[Vertex] = &[
Vertex {
pos: [-1.0, 1.0, 0.0], // Top-left
color: [1.0, 0.0, 1.0], // Magenta
},
Vertex {
pos: [-1.0, -1.0, 0.0], // Bottom-left
color: [0.0, 0.0, 1.0], // Blue
},
Vertex {
pos: [1.0, 1.0, 0.0], // Top-right
color: [1.0, 1.0, 0.0], // Yellow
},
Vertex {
pos: [1.0, -1.0, 0.0], // Bottom-right
color: [0.0, 1.0, 0.0], // Green
},
];
const INDICES: &[u32] = &[0, 1, 2, 2, 1, 3]; // CCW, quad
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable, Debug, Default)]
struct UniformData {
mouse_move: [f32; 2],
mouse_click: [f32; 2],
resolution: [f32; 2],
time: f32,
_padding: f32,
}
#[derive(Debug)]
struct State {
window: web_sys::Window,
canvas: web_sys::HtmlCanvasElement,
winit_window: winit::window::Window,
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
surface_config: wgpu::SurfaceConfiguration,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
index_num: u32,
uniform_data: UniformData,
uniform_buffer: wgpu::Buffer,
uniform_bind_group: wgpu::BindGroup,
render_pipeline: wgpu::RenderPipeline,
animation_cb: Closure<dyn FnMut(f32)>,
}
static mut STATE: Option<State> = None;
impl State {
async fn new() -> Self {
// window
let window = get_window();
// canvas
let canvas = State::init_canvas(&window).expect_throw("Failed to get the canvas");
// winit window
let winit_window = State::create_window(&canvas).expect_throw("Failed to create a window");
// wgpu instance
let instance = State::create_instance();
// wgpu surface
let surface = State::create_surface(&instance, &winit_window)
.expect_throw("Failed to create a surface");
// wgpu adapter
let adapter = State::create_adapter(&instance, &surface)
.await
.expect_throw("Failed to create an adapter");
// wgpu device and queue
let (device, queue) = State::create_device_and_queue(&adapter)
.await
.expect_throw("Failed to create a device and a queue");
// wgpu surface configuration
let surface_config = State::create_surface_configuration(
&surface,
&adapter,
&device,
canvas.width(),
canvas.height(),
);
// wgpu vertex buffer
let vertex_buffer = State::create_vertex_buffer(&device, bytemuck::cast_slice(VERTICES));
// wgpu index buffer
let index_buffer = State::create_index_buffer(&device, bytemuck::cast_slice(INDICES));
// wgpu uniform buffer
let uniform_data = UniformData {
resolution: [canvas.width() as f32, canvas.height() as f32],
mouse_move: [std::f32::MIN, std::f32::MIN],
mouse_click: [std::f32::MIN, std::f32::MIN],
..Default::default()
};
let (uniform_buffer, uniform_layout, uniform_bind_group) =
State::create_uniform_buffer(&device, bytemuck::cast_slice(&[uniform_data][..]));
// wgpu shader module
let shader_module = State::create_shader_module(&device);
// wgpu render pipeline
let render_pipeline = State::create_render_pipeline(
&device,
&[&uniform_layout],
&shader_module,
&surface_config,
);
// animation_loop
let animation_cb = State::create_animation_loop();
Self {
window,
canvas,
winit_window,
surface,
device,
queue,
surface_config,
vertex_buffer,
index_buffer,
index_num: INDICES.len() as u32,
uniform_data,
uniform_buffer,
uniform_bind_group,
render_pipeline,
animation_cb,
}
}
fn init_canvas(window: &web_sys::Window) -> Option<web_sys::HtmlCanvasElement> {
let element = window.document()?.get_element_by_id("canvas0")?;
let canvas = element.dyn_into::<web_sys::HtmlCanvasElement>().ok()?;
let (width, height) = (canvas.client_width() as u32, canvas.client_height() as u32);
canvas.set_width(width);
canvas.set_height(height);
log!("Canvas size: ({}, {})", canvas.width(), canvas.height());
Some(canvas)
}
fn create_window(canvas: &web_sys::HtmlCanvasElement) -> Option<winit::window::Window> {
// winit's window writes its physical and logical sizes in the HTML element
// as attributes and inner style respectively
// So, we should put "!important" in CSS to overwrite the inner style
let window = WindowBuilder::new()
.with_inner_size(PhysicalSize::new(
canvas.client_width(),
canvas.client_height(),
))
.with_canvas(Some(canvas.clone()))
.build(&EventLoop::new())
.ok()?;
log!(
"Window size: ({}, {})",
window.inner_size().width,
window.inner_size().height
);
Some(window)
}
fn create_instance() -> wgpu::Instance {
wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::BROWSER_WEBGPU,
..Default::default()
})
}
fn create_surface(
instance: &wgpu::Instance,
winit_window: &winit::window::Window,
) -> Option<wgpu::Surface> {
unsafe { instance.create_surface(winit_window).ok() }
}
async fn create_adapter(
instance: &wgpu::Instance,
surface: &wgpu::Surface,
) -> Option<wgpu::Adapter> {
instance
.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(surface),
force_fallback_adapter: false,
..Default::default()
})
.await
}
async fn create_device_and_queue(
adapter: &wgpu::Adapter,
) -> Option<(wgpu::Device, wgpu::Queue)> {
adapter
.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::empty(),
limits: wgpu::Limits::downlevel_webgl2_defaults(),
label: None,
},
None,
)
.await
.ok()
}
fn create_surface_configuration(
surface: &wgpu::Surface,
adapter: &wgpu::Adapter,
device: &wgpu::Device,
width: u32,
height: u32,
) -> wgpu::SurfaceConfiguration {
let surface_caps = surface.get_capabilities(adapter);
let surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_caps.formats[0],
width,
height,
present_mode: surface_caps.present_modes[0],
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
};
surface.configure(device, &surface_config);
surface_config
}
fn create_vertex_buffer(device: &wgpu::Device, contents: &[u8]) -> wgpu::Buffer {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex buffer"),
contents,
usage: wgpu::BufferUsages::VERTEX,
})
}
fn create_index_buffer(device: &wgpu::Device, contents: &[u8]) -> wgpu::Buffer {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index buffer"),
contents,
usage: wgpu::BufferUsages::INDEX,
})
}
fn create_uniform_buffer(
device: &wgpu::Device,
contents: &[u8],
) -> (wgpu::Buffer, wgpu::BindGroupLayout, wgpu::BindGroup) {
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Uniform buffer"),
contents,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Uniform bind group layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Uniform bind group"),
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
});
(buffer, bind_group_layout, bind_group)
}
fn create_shader_module(device: &wgpu::Device) -> wgpu::ShaderModule {
// Creates shader module from a single file.
let by_single_file = || -> wgpu::ShaderModule {
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader module"),
source: wgpu::ShaderSource::Wgsl(include_str!("monolithic.wgsl").into()),
})
};
// Composes shader module using naga_oil composition.
let by_naga_oil = || -> wgpu::ShaderModule {
use naga_oil::compose::{Composer, ComposableModuleDescriptor, NagaModuleDescriptor};
let mut composer = Composer::default();
composer.add_composable_module(ComposableModuleDescriptor {
source: include_str!("uniform.wgsl"), // Path to the file relative to the current file
file_path: "uniform.wgsl", // Path to the file relative to the Cargo.toml
..Default::default()
}).unwrap();
let naga_module = composer.make_naga_module(NagaModuleDescriptor {
source: include_str!("top.wgsl"), // Path to the file relative to the current file
file_path: "example.wgsl", // Path to the file relative to the Cargo.toml
shader_defs: [("UNIFORM".to_owned(), Default::default())].into(),
..Default::default()
}).unwrap();
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader module"),
source: wgpu::ShaderSource::Naga(Cow::Owned(naga_module)),
})
};
let by_my_wgsl = || -> wgpu::ShaderModule {
use my_wgsl::*;
#[wgsl_decl_struct]
struct UniformData {
mouse_move: vec2<f32>,
mouse_click: vec2<f32>,
resolution: vec2<f32>,
time: f32,
}
#[wgsl_decl_struct]
struct VertexInput {
#[location(0)] pos: vec3<f32>,
#[location(1)] color: vec3<f32>
}
#[wgsl_decl_struct]
struct VertexOutput {
#[builtin(position)] pos: vec4<f32>,
#[location(1)] color: vec3<f32>
}
let mut builder = Builder::new();
wgsl_structs!(builder, UniformData, VertexInput, VertexOutput);
wgsl_bind!(builder, group(0) binding(0) var<uniform> uni: UniformData);
wgsl_fn!(builder,
#[vertex]
fn v_main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.pos = vec4<f32>(input.pos, 1.0);
output.color = input.color;
return output;
}
);
wgsl_fn!(builder,
#[fragment]
fn f_main(input: VertexOutput) -> #[location(0)] vec4<f32> {
let x = select(0.0, 0.3, distance(input.pos.xy, uni.mouse_move) < 25.0);
let y = select(0.0, 0.3, distance(input.pos.xy, uni.mouse_click) < 25.0);
return vec4f(input.color + x - y, 1.0);
}
);
let wgsl = builder.build();
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader module"),
source: wgpu::ShaderSource::Wgsl(wgsl.into()),
})
};
// With measurement.
fn with_measure (title: &str, id: &str, f: impl FnOnce() -> wgpu::ShaderModule) -> wgpu::ShaderModule {
let s = now();
let res = f();
let e = now();
let msg = format!("[{title}] took {} ms", (e - s).floor());
set_inner_html(id, &msg);
res
}
// Let's try all of them.
with_measure("Creating shader module from a single file", "measure_single_file", by_single_file);
with_measure("Compositing shader module using naga_oil", "measure_naga_oil", by_naga_oil);
with_measure("Compositing shader module using my_wgsl", "measure_my_wgsl", by_my_wgsl)
}
fn create_render_pipeline(
device: &wgpu::Device,
bind_group_layouts: &[&wgpu::BindGroupLayout],
shader_module: &wgpu::ShaderModule,
surface_config: &wgpu::SurfaceConfiguration,
) -> wgpu::RenderPipeline {
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render pipeline layout"),
bind_group_layouts,
push_constant_ranges: &[],
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: shader_module,
entry_point: "v_main",
buffers: &[Vertex::layout()],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
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,
},
fragment: Some(wgpu::FragmentState {
module: shader_module,
entry_point: "f_main",
targets: &[Some(wgpu::ColorTargetState {
format: surface_config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview: None,
})
}
fn create_animation_loop() -> Closure<dyn FnMut(f32)> {
Closure::<dyn FnMut(f32)>::new(|time: f32| unsafe {
let state = STATE.as_mut().unwrap_unchecked();
state.render(time);
state.request_animation_frame();
})
}
#[inline(always)]
fn request_animation_frame(&self) {
self.window
.request_animation_frame(self.animation_cb.as_ref().unchecked_ref())
.expect_throw("Failed to request an animation frame");
}
fn resize(&mut self) {
let new_width = self.canvas.client_width() as u32;
let new_height = self.canvas.client_height() as u32;
if new_width != self.canvas.width() || new_height != self.canvas.height() {
// Synchronize manually
self.canvas.set_width(new_width);
self.canvas.set_height(new_height);
self.winit_window
.set_inner_size(PhysicalSize::new(new_width, new_height));
self.surface_config.width = new_width;
self.surface_config.height = new_height;
self.surface.configure(&self.device, &self.surface_config);
// Update uniform data
self.uniform_data.resolution = [new_width as f32, new_height as f32];
log!("Resized: ({}, {})", new_width, new_height);
}
}
fn mousemove(&mut self, event: web_sys::MouseEvent) {
// Update uniform data
self.uniform_data.mouse_move = [event.offset_x() as f32, event.offset_y() as f32];
}
fn click(&mut self, event: web_sys::MouseEvent) {
// Update uniform data
self.uniform_data.mouse_click = [event.offset_x() as f32, event.offset_y() as f32];
}
fn render(&mut self, time: f32) {
// Write uniform data to its buffer
self.uniform_data.time = time * 0.001;
self.queue.write_buffer(
&self.uniform_buffer,
0,
bytemuck::cast_slice(&[self.uniform_data][..]),
);
let surface_texture = self.surface.get_current_texture().unwrap();
let texture_view = surface_texture.texture.create_view(&Default::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render command encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &texture_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
render_pass.draw_indexed(0..self.index_num, 0, 0..1);
}
self.queue.submit(std::iter::once(encoder.finish()));
surface_texture.present();
}
}
#[wasm_bindgen(start)]
pub fn main() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init_with_level(log::Level::Warn).expect("Couldn't initialize logger");
}
#[wasm_bindgen]
pub async fn run() {
unsafe {
STATE = Some(State::new().await);
let state = STATE.as_mut().unwrap_unchecked();
// Sets resize event listener on window.
add_event_listener("", "resize", || STATE.as_mut().unwrap_unchecked().resize());
// Sets mousemove/click event listener on canvas
add_event_listener_with_mouseevent("canvas0", "mousemove", |event: web_sys::MouseEvent| {
STATE.as_mut().unwrap_unchecked().mousemove(event)
});
add_event_listener_with_mouseevent("canvas0", "click", |event: web_sys::MouseEvent| {
STATE.as_mut().unwrap_unchecked().click(event)
});
state.request_animation_frame();
};
}
fn get_window() -> web_sys::Window {
web_sys::window().expect_throw("Failed to get window")
}
fn get_document() -> web_sys::Document {
get_window().document().expect_throw("Failed to get document")
}
fn get_element_by_id(id: &str) -> web_sys::Element {
get_document()
.get_element_by_id(id)
.expect_throw("Failed to get element")
}
fn set_inner_html(id: &str, value: &str) {
get_element_by_id(id).set_inner_html(value)
}
fn add_event_listener(id: &str, type_: &str, f: impl Fn() + 'static) {
let listener = Closure::<dyn Fn()>::new(f);
if id.is_empty() {
get_window()
.add_event_listener_with_callback(type_, listener.as_ref().unchecked_ref())
.expect("Failed to add an event listener");
} else {
get_element_by_id(id)
.add_event_listener_with_callback(type_, listener.as_ref().unchecked_ref())
.expect("Failed to add an event listener");
}
listener.forget(); // Leak, but it occurs just once
}
fn add_event_listener_with_mouseevent(
id: &str,
type_: &str,
f: impl Fn(web_sys::MouseEvent) + 'static,
) {
let listener = Closure::<dyn Fn(_)>::new(f);
if id.is_empty() {
get_window()
.add_event_listener_with_callback(type_, listener.as_ref().unchecked_ref())
.expect("Failed to add an event listener");
} else {
get_element_by_id(id)
.add_event_listener_with_callback(type_, listener.as_ref().unchecked_ref())
.expect("Failed to add an event listener");
}
listener.forget(); // Leak, but it occurs just once
}
fn get_performance() -> web_sys::Performance {
get_window().performance().expect_throw("Failed to get performance")
}
fn now() -> f64 {
get_performance().now()
}