-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathHelloTriangle.tsx
More file actions
97 lines (82 loc) · 2.53 KB
/
HelloTriangle.tsx
File metadata and controls
97 lines (82 loc) · 2.53 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
import React, { useEffect, useRef } from "react";
import { StyleSheet, View, PixelRatio } from "react-native";
import type { CanvasRef } from "react-native-webgpu";
import { Canvas } from "react-native-webgpu";
import { redFragWGSL, triangleVertWGSL } from "./triangle";
export function HelloTriangle() {
const ref = useRef<CanvasRef>(null);
useEffect(() => {
(async () => {
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw new Error("No adapter");
}
const device = await adapter.requestDevice();
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
const context = ref.current!.getContext("webgpu")!;
const canvas = context.canvas as HTMLCanvasElement;
canvas.width = canvas.clientWidth * PixelRatio.get();
canvas.height = canvas.clientHeight * PixelRatio.get();
if (!context) {
throw new Error("No context");
}
context.configure({
device,
format: presentationFormat,
alphaMode: "premultiplied",
});
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: device.createShaderModule({
code: triangleVertWGSL,
}),
entryPoint: "main",
},
fragment: {
module: device.createShaderModule({
code: redFragWGSL,
}),
entryPoint: "main",
targets: [
{
format: presentationFormat,
},
],
},
primitive: {
topology: "triangle-list",
},
});
const commandEncoder = device.createCommandEncoder();
const textureView = context.getCurrentTexture().createView();
const renderPassDescriptor: GPURenderPassDescriptor = {
colorAttachments: [
{
view: textureView,
clearValue: [0, 0, 0, 0],
loadOp: "clear",
storeOp: "store",
},
],
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.draw(3);
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
context.present();
})();
}, [ref]);
return (
<View style={style.container}>
<View style={{ flex: 1, backgroundColor: "#3498db" }} />
<Canvas ref={ref} style={StyleSheet.absoluteFill} transparent />
</View>
);
}
const style = StyleSheet.create({
container: {
flex: 1,
},
});