-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathDebug.tsx
86 lines (74 loc) · 2.42 KB
/
Debug.tsx
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
import { useFrame } from '@react-three/fiber'
import cannonDebugger from 'cannon-es-debugger'
import { useContext, useState, useRef, useMemo } from 'react'
import { Vector3, Quaternion, Scene } from 'three'
import { context, debugContext } from './setup'
import propsToBody from './propsToBody'
import type { Body, Quaternion as CQuaternion, Vec3 } from 'cannon-es'
import type { DebugOptions } from 'cannon-es-debugger'
import type { PropsWithChildren } from 'react'
import type { Color } from 'three'
import type { BodyProps, BodyShapeType } from './hooks'
type DebugApi = {
update: () => void
}
export type DebuggerInterface = (scene: Scene, bodies: Body[], props?: DebugOptions) => DebugApi
export type DebugInfo = { bodies: Body[]; refs: { [uuid: string]: Body } }
export type DebugProps = PropsWithChildren<{
color?: string | number | Color
impl?: DebuggerInterface
scale?: number
}>
const v = new Vector3()
const s = new Vector3(1, 1, 1)
const q = new Quaternion()
export function Debug({
color = 'black',
scale = 1,
children,
impl = cannonDebugger,
}: DebugProps): JSX.Element {
const [debugInfo] = useState<DebugInfo>({ bodies: [], refs: {} })
const { refs } = useContext(context)
const [scene] = useState(() => new Scene())
const instance = useRef<DebugApi>()
let lastBodies = 0
useFrame(() => {
if (!instance.current || lastBodies !== debugInfo.bodies.length) {
lastBodies = debugInfo.bodies.length
scene.children = []
instance.current = impl(scene, debugInfo.bodies, {
color,
scale,
autoUpdate: false,
})
}
for (const uuid in debugInfo.refs) {
refs[uuid].matrix.decompose(v, q, s)
debugInfo.refs[uuid].position.copy(v as unknown as Vec3)
debugInfo.refs[uuid].quaternion.copy(q as unknown as CQuaternion)
}
instance.current.update()
})
const api = useMemo(
() => ({
add(id: string, props: BodyProps, type: BodyShapeType) {
const body = propsToBody(id, props, type)
debugInfo.bodies.push(body)
debugInfo.refs[id] = body
},
remove(id: string) {
const debugBodyIndex = debugInfo.bodies.indexOf(debugInfo.refs[id])
if (debugBodyIndex > -1) debugInfo.bodies.splice(debugBodyIndex, 1)
delete debugInfo.refs[id]
},
}),
[],
)
return (
<debugContext.Provider value={api}>
<primitive object={scene} />
{children}
</debugContext.Provider>
)
}