This repository has been archived by the owner on May 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
85 lines (71 loc) · 2.31 KB
/
script.js
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
(async () => {
if (!navigator.gpu) {
alert('Your browser does not support WebGPU or it is not enabled. More info: https://webgpu.io');
return;
}
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const canvas = document.getElementById('canvas')
const context = canvas.getContext('gpupresent');
const swapChainFormat = 'bgra8unorm';
const swapChain = context.configureSwapChain({
device,
format: swapChainFormat
});
const vertexShaderWgslCode =
`
const pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
vec2<f32>(0.0, 0.5),
vec2<f32>(-0.5, -0.5),
vec2<f32>(0.5, -0.5));
[[builtin(position)]] var<out> Position : vec4<f32>;
[[builtin(vertex_idx)]] var<in> VertexIndex : i32;
[[stage(vertex)]]
fn main() -> void {
Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);
return;
}
`;
const fragmentShaderWgslCode =
`
[[location(0)]] var<out> outColor : vec4<f32>;
[[stage(fragment)]]
fn main() -> void {
outColor = vec4<f32>(0.0, 1.0, 0.0, 1.0);
return;
}
`;
const pipeline = device.createRenderPipeline({
vertex: {
module: device.createShaderModule({
code: vertexShaderWgslCode
}),
entryPoint: 'main'
},
fragment: {
module: device.createShaderModule({
code: fragmentShaderWgslCode
}),
entryPoint: 'main',
targets: [{
format: swapChainFormat,
}]
},
primitive: {
topology: 'triangle-list',
}
});
const commandEncoder = device.createCommandEncoder();
const textureView = swapChain.getCurrentTexture().createView();
const renderPassDescriptor = {
colorAttachments: [{
attachment: textureView,
loadValue: { r: 0.5, g: 0.5, b: 0.5, a: 1.0 },
}]
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.draw(3, 1, 0, 0);
passEncoder.endPass();
device.queue.submit([commandEncoder.finish()]);
})();