-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathFiberCanvas.tsx
More file actions
101 lines (91 loc) · 2.73 KB
/
Copy pathFiberCanvas.tsx
File metadata and controls
101 lines (91 loc) · 2.73 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
import * as THREE from "three";
import React, { useRef, useState } from "react";
import type { ReconcilerRoot, RootState } from "@react-three/fiber";
import {
extend,
createRoot,
unmountComponentAtNode,
events,
} from "@react-three/fiber";
import type { ViewProps } from "react-native";
import { PixelRatio } from "react-native";
import { Canvas, useCanvasEffect } from "react-native-wgpu";
import { ReactNativeCanvas } from "./makeWebGPURenderer";
//global.THREE = global.THREE || THREE;
interface FiberCanvasProps {
children: React.ReactNode;
style?: ViewProps["style"];
camera?: THREE.PerspectiveCamera;
scene?: THREE.Scene;
}
export const FiberCanvas = ({
children,
style,
scene,
camera,
}: FiberCanvasProps) => {
const root = useRef<ReconcilerRoot<OffscreenCanvas>>(null!);
const [frameloop, setFrameloop] = useState<"always" | "never">("never");
React.useMemo(() => extend(THREE), []);
const canvasRef = useCanvasEffect(async () => {
const context = canvasRef.current!.getContext("webgpu")!;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const canvas = new ReactNativeCanvas(context.canvas) as HTMLCanvasElement;
canvas.width = canvas.clientWidth * PixelRatio.get();
canvas.height = canvas.clientHeight * PixelRatio.get();
const size = {
top: 0,
left: 0,
width: canvas.clientWidth,
height: canvas.clientHeight,
};
if (!root.current) {
root.current = createRoot(canvas);
}
root.current.configure({
size,
events,
scene,
camera,
gl: () => {
const renderer = new THREE.WebGPURenderer({
antialias: true,
canvas,
context,
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
renderer.xr = { addEventListener: () => {} };
// Initialize the renderer asynchronously
renderer.init().then(() => {
setFrameloop("always");
});
return renderer;
},
frameloop,
dpr: 1, //PixelRatio.get(),
onCreated: (state: RootState) => {
// Renderer is already initialized in the gl function
const renderFrame = state.gl.render.bind(state.gl);
state.gl.render = (s: THREE.Scene, c: THREE.Camera) => {
renderFrame(s, c);
context?.present();
};
},
});
root.current.render(children);
return () => {
if (canvas != null) {
unmountComponentAtNode(canvas!);
}
};
});
// Update the frameloop when it changes
React.useEffect(() => {
if (root.current) {
root.current.configure({ frameloop });
}
}, [frameloop]);
return <Canvas ref={canvasRef} style={style} />;
};