-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-hardcoded-color-triangle.js
More file actions
91 lines (79 loc) · 2.48 KB
/
Copy path02-hardcoded-color-triangle.js
File metadata and controls
91 lines (79 loc) · 2.48 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
async function main()
{
// get webgpu adapter and device
const adaptor = await navigator.gpu?.requestAdapter();
const device = await adaptor?.requestDevice();
if (!device) {
fail('your browser does not support WebGPU');
return;
}
// create a webgpu context with the canvas
const canvas = document.getElementById("webgpu-canvas");
const context = canvas.getContext("webgpu");
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({device, format});
// vertex and fragment shaders in one single module
const module = device.createShaderModule({
label: 'hardcoded color triangle',
code: `
struct VSOut {
@builtin(position) pos : vec4f,
@location(0) color : vec4f,
};
@vertex fn vs(@builtin(vertex_index) vertexIndex: u32)
-> VSOut
{
var pos : vec4f;
var color : vec4f;
if (vertexIndex == 0) {
pos = vec4f(0.0, 0.0, 0.0, 1.0);
color = vec4f(1.0, 0.0, 0.0, 1.0);
} else if (vertexIndex == 1) {
pos = vec4f(0.5, 0.0, 0.0, 1.0);
color = vec4f(0.0, 1.0, 0.0, 1.0);
} else if (vertexIndex == 2) {
pos = vec4f(0.0, 0.5, 0.0, 1.0);
color = vec4f(0.0, 0.0, 1.0, 1.0);
}
return VSOut(pos, color);
}
@fragment fn fs(in : VSOut)
-> @location(0) vec4f
{
return in.color;
}
`,
});
// the rendering pipeline
const pipeline = device.createRenderPipeline({
label: 'hardcoded triangle pipeline',
layout: 'auto',
vertex: {
module: module
},
fragment: {
module: module,
targets: [{ format: format }],
},
});
const render = () => {
const textureView = context.getCurrentTexture().createView(); // the output is a texture, and we are getting a "view" of texture as the output of the render pass
const renderPassDescriptor = {
colorAttachments: [{
view: textureView,
clearValue: [1.0, 1.0, 1.0, 1.0], // an arbitrary color you prefer
storeOp: 'store',
loadOp: 'clear',
}],
};
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.draw(3); // draw three vertices
passEncoder.end();
// fire up the GPU to render the load value to the output texture
device.queue.submit([commandEncoder.finish()]);
};
render();
}
main();