-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
79 lines (71 loc) · 2.04 KB
/
index.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
const vertexShader = /* language=WGSL */ `
struct VSOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec4<f32>
};
const positions = array<vec2<f32>,3>(
vec2( 0.0, 0.5),
vec2(-0.5, -0.5),
vec2( 0.5, -0.5)
);
const colors = array<vec3<f32>,3>(
vec3(0.0, 1.0, 1.0),
vec3(0.0, 0.0, 1.0),
vec3(1.0, 0.0, 1.0)
);
@vertex
fn main(@builtin(vertex_index) vertexIndex: u32) -> VSOutput {
return VSOutput(
vec4(positions[vertexIndex], 0.0, 1.0),
vec4(colors[vertexIndex], 1.0)
);
}`
const fragmentShader = /* language=WGSL */ `
@fragment
fn main(@location(0) color: vec4<f32>) -> @location(0) vec4<f32> {
return color;
}`
const render = async (gpu, canvasContext) => {
// canvas independent part
const device = await (await gpu.requestAdapter()).requestDevice()
const format = gpu.getPreferredCanvasFormat() // 'bgra8unorm'
const commandEncoder = device.createCommandEncoder()
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: device.createShaderModule({ code: vertexShader }),
entryPoint: 'main',
},
fragment: {
module: device.createShaderModule({ code: fragmentShader }),
entryPoint: 'main',
targets: [{ format }],
},
primitive: { topology: 'triangle-list' },
})
// canvas dependent part
canvasContext.configure({ device, format, alphaMode: 'premultiplied' })
const passEncoder = commandEncoder.beginRenderPass({
colorAttachments: [
{
view: canvasContext.getCurrentTexture().createView(),
clearValue: { r: 0, g: 0.05, b: 0, a: 1 },
loadOp: 'clear',
storeOp: 'store',
},
],
})
passEncoder.setPipeline(pipeline)
passEncoder.draw(3, 1, 0, 0)
passEncoder.end()
// draw
device.queue.submit([commandEncoder.finish()])
}
if (navigator.gpu) {
render(
navigator.gpu,
document.getElementById('canvas').getContext('webgpu')
).then()
} else {
alert('WebGPU is not supported or is not enabled, see https://webgpu.io')
}