diff --git a/src/core/AccumulativeShadows.tsx b/src/core/AccumulativeShadows.tsx index a91f2fe1a..84a76a196 100644 --- a/src/core/AccumulativeShadows.tsx +++ b/src/core/AccumulativeShadows.tsx @@ -4,6 +4,7 @@ import { extend, ReactThreeFiber, useFrame, useThree } from '@react-three/fiber' import { shaderMaterial } from './shaderMaterial' import { DiscardMaterial } from '../materials/DiscardMaterial' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' function isLight(object: any): object is THREE.Light { return object.isLight @@ -72,11 +73,13 @@ declare global { } } -export const accumulativeContext = React.createContext(null as unknown as AccumulativeContext) +export const accumulativeContext = /* @__PURE__ */ React.createContext( + null as unknown as AccumulativeContext +) -const SoftShadowMaterial = shaderMaterial( +const SoftShadowMaterial = /* @__PURE__ */ shaderMaterial( { - color: new THREE.Color(), + color: /* @__PURE__ */ new THREE.Color(), blend: 2.0, alphaTest: 0.75, opacity: 0, @@ -97,14 +100,14 @@ const SoftShadowMaterial = shaderMaterial( vec4 sampledDiffuseColor = texture2D(map, vUv); gl_FragColor = vec4(color * sampledDiffuseColor.r * blend, max(0.0, (1.0 - (sampledDiffuseColor.r + sampledDiffuseColor.g + sampledDiffuseColor.b) / alphaTest)) * opacity); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }` ) export const AccumulativeShadows: ForwardRefComponent< JSX.IntrinsicElements['group'] & AccumulativeShadowsProps, AccumulativeContext -> = React.forwardRef( +> = /* @__PURE__ */ React.forwardRef( ( { children, @@ -253,7 +256,7 @@ export type RandomizedLightProps = { export const RandomizedLight: ForwardRefComponent< JSX.IntrinsicElements['group'] & RandomizedLightProps, AccumulativeLightContext -> = React.forwardRef( +> = /* @__PURE__ */ React.forwardRef( ( { castShadow = true, @@ -266,7 +269,7 @@ export const RandomizedLight: ForwardRefComponent< position = [0, 0, 0], radius = 1, amount = 8, - intensity = parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 155 ? Math.PI : 1, + intensity = version >= 155 ? Math.PI : 1, ambient = 0.5, ...props }: JSX.IntrinsicElements['group'] & RandomizedLightProps, diff --git a/src/core/ArcballControls.tsx b/src/core/ArcballControls.tsx index 4c0e79daa..3c8c3eb38 100644 --- a/src/core/ArcballControls.tsx +++ b/src/core/ArcballControls.tsx @@ -23,55 +23,55 @@ export type ArcballControlsProps = Omit< 'ref' > -export const ArcballControls: ForwardRefComponent = forwardRef< - ArcballControlsImpl, - ArcballControlsProps ->(({ camera, makeDefault, regress, domElement, onChange, onStart, onEnd, ...restProps }, ref) => { - const invalidate = useThree((state) => state.invalidate) - const defaultCamera = useThree((state) => state.camera) - const gl = useThree((state) => state.gl) - const events = useThree((state) => state.events) as EventManager - const set = useThree((state) => state.set) - const get = useThree((state) => state.get) - const performance = useThree((state) => state.performance) - const explCamera = camera || defaultCamera - const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement - const controls = useMemo(() => new ArcballControlsImpl(explCamera), [explCamera]) +export const ArcballControls: ForwardRefComponent = + /* @__PURE__ */ forwardRef( + ({ camera, makeDefault, regress, domElement, onChange, onStart, onEnd, ...restProps }, ref) => { + const invalidate = useThree((state) => state.invalidate) + const defaultCamera = useThree((state) => state.camera) + const gl = useThree((state) => state.gl) + const events = useThree((state) => state.events) as EventManager + const set = useThree((state) => state.set) + const get = useThree((state) => state.get) + const performance = useThree((state) => state.performance) + const explCamera = camera || defaultCamera + const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement + const controls = useMemo(() => new ArcballControlsImpl(explCamera), [explCamera]) - useFrame(() => { - if (controls.enabled) controls.update() - }, -1) + useFrame(() => { + if (controls.enabled) controls.update() + }, -1) - useEffect(() => { - controls.connect(explDomElement) - return () => void controls.dispose() - }, [explDomElement, regress, controls, invalidate]) + useEffect(() => { + controls.connect(explDomElement) + return () => void controls.dispose() + }, [explDomElement, regress, controls, invalidate]) - useEffect(() => { - const callback = (e: Event) => { - invalidate() - if (regress) performance.regress() - if (onChange) onChange(e) - } + useEffect(() => { + const callback = (e: Event) => { + invalidate() + if (regress) performance.regress() + if (onChange) onChange(e) + } - controls.addEventListener('change', callback) - if (onStart) controls.addEventListener('start', onStart) - if (onEnd) controls.addEventListener('end', onEnd) + controls.addEventListener('change', callback) + if (onStart) controls.addEventListener('start', onStart) + if (onEnd) controls.addEventListener('end', onEnd) - return () => { - controls.removeEventListener('change', callback) - if (onStart) controls.removeEventListener('start', onStart) - if (onEnd) controls.removeEventListener('end', onEnd) - } - }, [onChange, onStart, onEnd]) + return () => { + controls.removeEventListener('change', callback) + if (onStart) controls.removeEventListener('start', onStart) + if (onEnd) controls.removeEventListener('end', onEnd) + } + }, [onChange, onStart, onEnd]) - useEffect(() => { - if (makeDefault) { - const old = get().controls - set({ controls }) - return () => set({ controls: old }) - } - }, [makeDefault, controls]) + useEffect(() => { + if (makeDefault) { + const old = get().controls + set({ controls }) + return () => set({ controls: old }) + } + }, [makeDefault, controls]) - return -}) + return + } + ) diff --git a/src/core/BBAnchor.tsx b/src/core/BBAnchor.tsx index 116fb33ad..a1bcb6e42 100644 --- a/src/core/BBAnchor.tsx +++ b/src/core/BBAnchor.tsx @@ -2,8 +2,8 @@ import * as React from 'react' import * as THREE from 'three' import { useFrame, GroupProps } from '@react-three/fiber' -const boundingBox = new THREE.Box3() -const boundingBoxSize = new THREE.Vector3() +const boundingBox = /* @__PURE__ */ new THREE.Box3() +const boundingBoxSize = /* @__PURE__ */ new THREE.Vector3() export interface BBAnchorProps extends GroupProps { anchor: THREE.Vector3 | [number, number, number] diff --git a/src/core/Billboard.tsx b/src/core/Billboard.tsx index 140bc28aa..8b862fe13 100644 --- a/src/core/Billboard.tsx +++ b/src/core/Billboard.tsx @@ -20,23 +20,24 @@ export type BillboardProps = { * * ``` */ -export const Billboard: ForwardRefComponent = React.forwardRef( - function Billboard({ follow = true, lockX = false, lockY = false, lockZ = false, ...props }, ref) { - const localRef = React.useRef() - useFrame(({ camera }) => { - if (!follow || !localRef.current) return +export const Billboard: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + Group, + BillboardProps +>(function Billboard({ follow = true, lockX = false, lockY = false, lockZ = false, ...props }, ref) { + const localRef = React.useRef() + useFrame(({ camera }) => { + if (!follow || !localRef.current) return - // save previous rotation in case we're locking an axis - const prevRotation = localRef.current.rotation.clone() + // save previous rotation in case we're locking an axis + const prevRotation = localRef.current.rotation.clone() - // always face the camera - camera.getWorldQuaternion(localRef.current.quaternion) + // always face the camera + camera.getWorldQuaternion(localRef.current.quaternion) - // readjust any axis that is locked - if (lockX) localRef.current.rotation.x = prevRotation.x - if (lockY) localRef.current.rotation.y = prevRotation.y - if (lockZ) localRef.current.rotation.z = prevRotation.z - }) - return - } -) + // readjust any axis that is locked + if (lockX) localRef.current.rotation.x = prevRotation.x + if (lockY) localRef.current.rotation.y = prevRotation.y + if (lockZ) localRef.current.rotation.z = prevRotation.z + }) + return +}) diff --git a/src/core/Bounds.tsx b/src/core/Bounds.tsx index 96b7399c3..1967abc4a 100644 --- a/src/core/Bounds.tsx +++ b/src/core/Bounds.tsx @@ -39,7 +39,7 @@ const isOrthographic = (def: THREE.Camera): def is THREE.OrthographicCamera => def && (def as THREE.OrthographicCamera).isOrthographicCamera const isBox3 = (def: any): def is THREE.Box3 => def && (def as THREE.Box3).isBox3 -const context = React.createContext(null!) +const context = /* @__PURE__ */ React.createContext(null!) export function Bounds({ children, damping = 6, fit, clip, observe, margin = 1.2, eps = 0.01, onFit }: BoundsProps) { const ref = React.useRef(null!) const { camera, invalidate, size, controls: controlsImpl } = useThree() diff --git a/src/core/CameraControls.tsx b/src/core/CameraControls.tsx index cc3375de9..f1bfdc5f7 100644 --- a/src/core/CameraControls.tsx +++ b/src/core/CameraControls.tsx @@ -38,7 +38,7 @@ export type CameraControlsProps = Omit< 'ref' > -export const CameraControls: ForwardRefComponent = forwardRef< +export const CameraControls: ForwardRefComponent = /* @__PURE__ */ forwardRef< CameraControlsImpl, CameraControlsProps >((props, ref) => { diff --git a/src/core/CameraShake.tsx b/src/core/CameraShake.tsx index f356ab3f8..37d23cf48 100644 --- a/src/core/CameraShake.tsx +++ b/src/core/CameraShake.tsx @@ -28,77 +28,75 @@ export interface CameraShakeProps { rollFrequency?: number } -export const CameraShake: ForwardRefComponent = React.forwardRef< - ShakeController | undefined, - CameraShakeProps ->( - ( - { - intensity = 1, - decay, - decayRate = 0.65, - maxYaw = 0.1, - maxPitch = 0.1, - maxRoll = 0.1, - yawFrequency = 0.1, - pitchFrequency = 0.1, - rollFrequency = 0.1, - }, - ref - ) => { - const camera = useThree((state) => state.camera) - const defaultControls = useThree((state) => state.controls) as unknown as ControlsProto - const intensityRef = React.useRef(intensity) - const initialRotation = React.useRef(camera.rotation.clone()) - const [yawNoise] = React.useState(() => new SimplexNoise()) - const [pitchNoise] = React.useState(() => new SimplexNoise()) - const [rollNoise] = React.useState(() => new SimplexNoise()) +export const CameraShake: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ( + { + intensity = 1, + decay, + decayRate = 0.65, + maxYaw = 0.1, + maxPitch = 0.1, + maxRoll = 0.1, + yawFrequency = 0.1, + pitchFrequency = 0.1, + rollFrequency = 0.1, + }, + ref + ) => { + const camera = useThree((state) => state.camera) + const defaultControls = useThree((state) => state.controls) as unknown as ControlsProto + const intensityRef = React.useRef(intensity) + const initialRotation = React.useRef(camera.rotation.clone()) + const [yawNoise] = React.useState(() => new SimplexNoise()) + const [pitchNoise] = React.useState(() => new SimplexNoise()) + const [rollNoise] = React.useState(() => new SimplexNoise()) - const constrainIntensity = () => { - if (intensityRef.current < 0 || intensityRef.current > 1) { - intensityRef.current = intensityRef.current < 0 ? 0 : 1 + const constrainIntensity = () => { + if (intensityRef.current < 0 || intensityRef.current > 1) { + intensityRef.current = intensityRef.current < 0 ? 0 : 1 + } } - } - React.useImperativeHandle( - ref, - () => ({ - getIntensity: (): number => intensityRef.current, - setIntensity: (val: number): void => { - intensityRef.current = val - constrainIntensity() - }, - }), - [] - ) + React.useImperativeHandle( + ref, + () => ({ + getIntensity: (): number => intensityRef.current, + setIntensity: (val: number): void => { + intensityRef.current = val + constrainIntensity() + }, + }), + [] + ) - React.useEffect(() => { - if (defaultControls) { - const callback = () => void (initialRotation.current = camera.rotation.clone()) - defaultControls.addEventListener('change', callback) - callback() - return () => void defaultControls.removeEventListener('change', callback) - } - }, [camera, defaultControls]) + React.useEffect(() => { + if (defaultControls) { + const callback = () => void (initialRotation.current = camera.rotation.clone()) + defaultControls.addEventListener('change', callback) + callback() + return () => void defaultControls.removeEventListener('change', callback) + } + }, [camera, defaultControls]) - useFrame((state, delta) => { - const shake = Math.pow(intensityRef.current, 2) - const yaw = maxYaw * shake * yawNoise.noise(state.clock.elapsedTime * yawFrequency, 1) - const pitch = maxPitch * shake * pitchNoise.noise(state.clock.elapsedTime * pitchFrequency, 1) - const roll = maxRoll * shake * rollNoise.noise(state.clock.elapsedTime * rollFrequency, 1) + useFrame((state, delta) => { + const shake = Math.pow(intensityRef.current, 2) + const yaw = maxYaw * shake * yawNoise.noise(state.clock.elapsedTime * yawFrequency, 1) + const pitch = maxPitch * shake * pitchNoise.noise(state.clock.elapsedTime * pitchFrequency, 1) + const roll = maxRoll * shake * rollNoise.noise(state.clock.elapsedTime * rollFrequency, 1) - camera.rotation.set( - initialRotation.current.x + pitch, - initialRotation.current.y + yaw, - initialRotation.current.z + roll - ) + camera.rotation.set( + initialRotation.current.x + pitch, + initialRotation.current.y + yaw, + initialRotation.current.z + roll + ) - if (decay && intensityRef.current > 0) { - intensityRef.current -= decayRate * delta - constrainIntensity() - } - }) + if (decay && intensityRef.current > 0) { + intensityRef.current -= decayRate * delta + constrainIntensity() + } + }) - return null - } -) + return null + } + ) diff --git a/src/core/CatmullRomLine.tsx b/src/core/CatmullRomLine.tsx index 0d44f41cb..1c3040327 100644 --- a/src/core/CatmullRomLine.tsx +++ b/src/core/CatmullRomLine.tsx @@ -11,41 +11,43 @@ type Props = Omit & { segments?: number } -export const CatmullRomLine: ForwardRefComponent = React.forwardRef(function CatmullRomLine( - { points, closed = false, curveType = 'centripetal', tension = 0.5, segments = 20, vertexColors, ...rest }, - ref -) { - const curve = React.useMemo(() => { - const mappedPoints = points.map((pt) => - pt instanceof Vector3 ? pt : new Vector3(...(pt as [number, number, number])) - ) - - return new CatmullRomCurve3(mappedPoints, closed, curveType, tension) - }, [points, closed, curveType, tension]) - - const segmentedPoints = React.useMemo(() => curve.getPoints(segments), [curve, segments]) - - const interpolatedVertexColors = React.useMemo(() => { - if (!vertexColors || vertexColors.length < 2) return undefined - - if (vertexColors.length === segments + 1) return vertexColors - - const mappedColors = vertexColors.map((color) => - color instanceof Color ? color : new Color(...(color as [number, number, number])) - ) - if (closed) mappedColors.push(mappedColors[0].clone()) - - const iColors: Color[] = [mappedColors[0]] - const divisions = segments / (mappedColors.length - 1) - for (let i = 1; i < segments; i++) { - const alpha = (i % divisions) / divisions - const colorIndex = Math.floor(i / divisions) - iColors.push(mappedColors[colorIndex].clone().lerp(mappedColors[colorIndex + 1], alpha)) - } - iColors.push(mappedColors[mappedColors.length - 1]) - - return iColors - }, [vertexColors, segments]) - - return -}) +export const CatmullRomLine: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( + function CatmullRomLine( + { points, closed = false, curveType = 'centripetal', tension = 0.5, segments = 20, vertexColors, ...rest }, + ref + ) { + const curve = React.useMemo(() => { + const mappedPoints = points.map((pt) => + pt instanceof Vector3 ? pt : new Vector3(...(pt as [number, number, number])) + ) + + return new CatmullRomCurve3(mappedPoints, closed, curveType, tension) + }, [points, closed, curveType, tension]) + + const segmentedPoints = React.useMemo(() => curve.getPoints(segments), [curve, segments]) + + const interpolatedVertexColors = React.useMemo(() => { + if (!vertexColors || vertexColors.length < 2) return undefined + + if (vertexColors.length === segments + 1) return vertexColors + + const mappedColors = vertexColors.map((color) => + color instanceof Color ? color : new Color(...(color as [number, number, number])) + ) + if (closed) mappedColors.push(mappedColors[0].clone()) + + const iColors: Color[] = [mappedColors[0]] + const divisions = segments / (mappedColors.length - 1) + for (let i = 1; i < segments; i++) { + const alpha = (i % divisions) / divisions + const colorIndex = Math.floor(i / divisions) + iColors.push(mappedColors[colorIndex].clone().lerp(mappedColors[colorIndex + 1], alpha)) + } + iColors.push(mappedColors[mappedColors.length - 1]) + + return iColors + }, [vertexColors, segments]) + + return + } +) diff --git a/src/core/Caustics.tsx b/src/core/Caustics.tsx index fdea4d809..e75b36c10 100644 --- a/src/core/Caustics.tsx +++ b/src/core/Caustics.tsx @@ -11,6 +11,7 @@ import { shaderMaterial } from './shaderMaterial' import { Edges } from './Edges' import { FullScreenQuad } from 'three-stdlib' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' type CausticsMaterialType = THREE.ShaderMaterial & { cameraMatrixWorld?: THREE.Matrix4 @@ -99,13 +100,13 @@ function createNormalMaterial(side = THREE.FrontSide) { }) } -const CausticsProjectionMaterial = shaderMaterial( +const CausticsProjectionMaterial = /* @__PURE__ */ shaderMaterial( { causticsTexture: null, causticsTextureB: null, - color: new THREE.Color(), - lightProjMatrix: new THREE.Matrix4(), - lightViewMatrix: new THREE.Matrix4(), + color: /* @__PURE__ */ new THREE.Color(), + lightProjMatrix: /* @__PURE__ */ new THREE.Matrix4(), + lightViewMatrix: /* @__PURE__ */ new THREE.Matrix4(), }, `varying vec3 vWorldPosition; void main() { @@ -128,22 +129,22 @@ const CausticsProjectionMaterial = shaderMaterial( vec3 back = texture2D(causticsTextureB, lightSpacePos.xy).rgb; gl_FragColor = vec4((front + back) * color, 1.0); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }` ) -const CausticsMaterial = shaderMaterial( +const CausticsMaterial = /* @__PURE__ */ shaderMaterial( { - cameraMatrixWorld: new THREE.Matrix4(), - cameraProjectionMatrixInv: new THREE.Matrix4(), + cameraMatrixWorld: /* @__PURE__ */ new THREE.Matrix4(), + cameraProjectionMatrixInv: /* @__PURE__ */ new THREE.Matrix4(), normalTexture: null, depthTexture: null, - lightDir: new THREE.Vector3(0, 1, 0), - lightPlaneNormal: new THREE.Vector3(0, 1, 0), + lightDir: /* @__PURE__ */ new THREE.Vector3(0, 1, 0), + lightPlaneNormal: /* @__PURE__ */ new THREE.Vector3(0, 1, 0), lightPlaneConstant: 0, near: 0.1, far: 100, - modelMatrix: new THREE.Matrix4(), + modelMatrix: /* @__PURE__ */ new THREE.Matrix4(), worldRadius: 1 / 40, ior: 1.1, bounces: 0, @@ -276,9 +277,9 @@ const CAUSTICPROPS = { generateMipmaps: true, } -const causticsContext = React.createContext(null) +const causticsContext = /* @__PURE__ */ React.createContext(null) -export const Caustics: ForwardRefComponent = React.forwardRef( +export const Caustics: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { debug, diff --git a/src/core/Center.tsx b/src/core/Center.tsx index 654bdb496..cf160816b 100644 --- a/src/core/Center.tsx +++ b/src/core/Center.tsx @@ -42,77 +42,75 @@ export type CenterProps = { cacheKey?: any } -export const Center: ForwardRefComponent = React.forwardRef< - Group, - JSX.IntrinsicElements['group'] & CenterProps ->(function Center( - { - children, - disable, - disableX, - disableY, - disableZ, - left, - right, - top, - bottom, - front, - back, - onCentered, - precise = true, - cacheKey = 0, - ...props - }, - fRef -) { - const ref = React.useRef(null!) - const outer = React.useRef(null!) - const inner = React.useRef(null!) - React.useLayoutEffect(() => { - outer.current.matrixWorld.identity() - const box3 = new Box3().setFromObject(inner.current, precise) - const center = new Vector3() - const sphere = new Sphere() - const width = box3.max.x - box3.min.x - const height = box3.max.y - box3.min.y - const depth = box3.max.z - box3.min.z - box3.getCenter(center) - box3.getBoundingSphere(sphere) - const vAlign = top ? height / 2 : bottom ? -height / 2 : 0 - const hAlign = left ? -width / 2 : right ? width / 2 : 0 - const dAlign = front ? depth / 2 : back ? -depth / 2 : 0 +export const Center: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef(function Center( + { + children, + disable, + disableX, + disableY, + disableZ, + left, + right, + top, + bottom, + front, + back, + onCentered, + precise = true, + cacheKey = 0, + ...props + }, + fRef + ) { + const ref = React.useRef(null!) + const outer = React.useRef(null!) + const inner = React.useRef(null!) + React.useLayoutEffect(() => { + outer.current.matrixWorld.identity() + const box3 = new Box3().setFromObject(inner.current, precise) + const center = new Vector3() + const sphere = new Sphere() + const width = box3.max.x - box3.min.x + const height = box3.max.y - box3.min.y + const depth = box3.max.z - box3.min.z + box3.getCenter(center) + box3.getBoundingSphere(sphere) + const vAlign = top ? height / 2 : bottom ? -height / 2 : 0 + const hAlign = left ? -width / 2 : right ? width / 2 : 0 + const dAlign = front ? depth / 2 : back ? -depth / 2 : 0 - outer.current.position.set( - disable || disableX ? 0 : -center.x + hAlign, - disable || disableY ? 0 : -center.y + vAlign, - disable || disableZ ? 0 : -center.z + dAlign - ) + outer.current.position.set( + disable || disableX ? 0 : -center.x + hAlign, + disable || disableY ? 0 : -center.y + vAlign, + disable || disableZ ? 0 : -center.z + dAlign + ) - // Only fire onCentered if the bounding box has changed - if (typeof onCentered !== 'undefined') { - onCentered({ - parent: ref.current.parent!, - container: ref.current, - width, - height, - depth, - boundingBox: box3, - boundingSphere: sphere, - center: center, - verticalAlignment: vAlign, - horizontalAlignment: hAlign, - depthAlignment: dAlign, - }) - } - }, [cacheKey, onCentered, top, left, front, disable, disableX, disableY, disableZ, precise, right, bottom, back]) + // Only fire onCentered if the bounding box has changed + if (typeof onCentered !== 'undefined') { + onCentered({ + parent: ref.current.parent!, + container: ref.current, + width, + height, + depth, + boundingBox: box3, + boundingSphere: sphere, + center: center, + verticalAlignment: vAlign, + horizontalAlignment: hAlign, + depthAlignment: dAlign, + }) + } + }, [cacheKey, onCentered, top, left, front, disable, disableX, disableY, disableZ, precise, right, bottom, back]) - React.useImperativeHandle(fRef, () => ref.current, []) + React.useImperativeHandle(fRef, () => ref.current, []) - return ( - - - {children} + return ( + + + {children} + - - ) -}) + ) + }) diff --git a/src/core/Clone.tsx b/src/core/Clone.tsx index 6e07c25fd..853d39e61 100644 --- a/src/core/Clone.tsx +++ b/src/core/Clone.tsx @@ -79,7 +79,7 @@ function createSpread( } export const Clone: ForwardRefComponent & CloneProps, THREE.Group> = - React.forwardRef( + /* @__PURE__ */ React.forwardRef( ( { isChild = false, diff --git a/src/core/Cloud.tsx b/src/core/Cloud.tsx index 402fb7b0a..c71c3dd39 100644 --- a/src/core/Cloud.tsx +++ b/src/core/Cloud.tsx @@ -88,15 +88,15 @@ type CloudProps = JSX.IntrinsicElements['group'] & { color?: ReactThreeFiber.Color } -const parentMatrix = /*@__PURE__*/ new Matrix4() -const translation = /*@__PURE__*/ new Vector3() -const rotation = /*@__PURE__*/ new Quaternion() -const cpos = /*@__PURE__*/ new Vector3() -const cquat = /*@__PURE__*/ new Quaternion() -const scale = /*@__PURE__*/ new Vector3() +const parentMatrix = /* @__PURE__ */ new Matrix4() +const translation = /* @__PURE__ */ new Vector3() +const rotation = /* @__PURE__ */ new Quaternion() +const cpos = /* @__PURE__ */ new Vector3() +const cquat = /* @__PURE__ */ new Quaternion() +const scale = /* @__PURE__ */ new Vector3() -const context = React.createContext>(null!) -export const Clouds = React.forwardRef( +const context = /* @__PURE__ */ React.createContext>(null!) +export const Clouds = /* @__PURE__ */ React.forwardRef( ({ children, material = MeshLambertMaterial, texture = CLOUD_URL, range, limit = 200, ...props }, fref) => { const CloudMaterial = React.useMemo(() => { return class extends (material as typeof Material) { @@ -201,7 +201,7 @@ export const Clouds = React.forwardRef( } ) -export const CloudInstance = React.forwardRef( +export const CloudInstance = /* @__PURE__ */ React.forwardRef( ( { opacity = 1, @@ -303,7 +303,7 @@ export const CloudInstance = React.forwardRef( } ) -export const Cloud = React.forwardRef((props, fref) => { +export const Cloud = /* @__PURE__ */ React.forwardRef((props, fref) => { const parent = React.useContext(context) if (parent) return else diff --git a/src/core/ContactShadows.tsx b/src/core/ContactShadows.tsx index e546d01d3..c6d789879 100644 --- a/src/core/ContactShadows.tsx +++ b/src/core/ContactShadows.tsx @@ -25,7 +25,7 @@ export type ContactShadowsProps = { export const ContactShadows: ForwardRefComponent< Omit & ContactShadowsProps, THREE.Group -> = React.forwardRef( +> = /* @__PURE__ */ React.forwardRef( ( { scale = 10, diff --git a/src/core/CubicBezierLine.tsx b/src/core/CubicBezierLine.tsx index 143eb34d3..db1da4c1a 100644 --- a/src/core/CubicBezierLine.tsx +++ b/src/core/CubicBezierLine.tsx @@ -12,7 +12,7 @@ type Props = Omit & { segments?: number } -export const CubicBezierLine: ForwardRefComponent = React.forwardRef( +export const CubicBezierLine: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( function CubicBezierLine({ start, end, midA, midB, segments = 20, ...rest }, ref) { const points = React.useMemo(() => { const startV = start instanceof Vector3 ? start : new Vector3(...start) diff --git a/src/core/CurveModifier.tsx b/src/core/CurveModifier.tsx index d9ca33c08..b6012113d 100644 --- a/src/core/CurveModifier.tsx +++ b/src/core/CurveModifier.tsx @@ -11,8 +11,8 @@ export interface CurveModifierProps { export type CurveModifierRef = Pick -export const CurveModifier: ForwardRefComponent = React.forwardRef( - ({ children, curve }: CurveModifierProps, ref) => { +export const CurveModifier: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef(({ children, curve }: CurveModifierProps, ref) => { const [scene] = React.useState(() => new THREE.Scene()) const [obj, set] = React.useState() const modifier = React.useRef() @@ -40,5 +40,4 @@ export const CurveModifier: ForwardRefComponent} ) - } -) + }) diff --git a/src/core/Decal.tsx b/src/core/Decal.tsx index bd6f60655..77ec4039a 100644 --- a/src/core/Decal.tsx +++ b/src/core/Decal.tsx @@ -31,81 +31,82 @@ function vecToArray(vec: number[] | FIBER.Vector3 | FIBER.Euler | number = [0, 0 } } -export const Decal: ForwardRefComponent = React.forwardRef( - function Decal( - { debug, depthTest = false, polygonOffsetFactor = -10, map, mesh, children, position, rotation, scale, ...props }, - forwardRef - ) { - const ref = React.useRef(null!) - React.useImperativeHandle(forwardRef, () => ref.current) - const helper = React.useRef(null!) +export const Decal: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + THREE.Mesh, + DecalProps +>(function Decal( + { debug, depthTest = false, polygonOffsetFactor = -10, map, mesh, children, position, rotation, scale, ...props }, + forwardRef +) { + const ref = React.useRef(null!) + React.useImperativeHandle(forwardRef, () => ref.current) + const helper = React.useRef(null!) - React.useLayoutEffect(() => { - const parent = mesh?.current || ref.current.parent - const target = ref.current - if (!(parent instanceof THREE.Mesh)) { - throw new Error('Decal must have a Mesh as parent or specify its "mesh" prop') - } + React.useLayoutEffect(() => { + const parent = mesh?.current || ref.current.parent + const target = ref.current + if (!(parent instanceof THREE.Mesh)) { + throw new Error('Decal must have a Mesh as parent or specify its "mesh" prop') + } - const state = { - position: new THREE.Vector3(), - rotation: new THREE.Euler(), - scale: new THREE.Vector3(1, 1, 1), - } + const state = { + position: new THREE.Vector3(), + rotation: new THREE.Euler(), + scale: new THREE.Vector3(1, 1, 1), + } - if (parent) { - applyProps(state as any, { position, scale }) + if (parent) { + applyProps(state as any, { position, scale }) - // Zero out the parents matrix world for this operation - const matrixWorld = parent.matrixWorld.clone() - parent.matrixWorld.identity() + // Zero out the parents matrix world for this operation + const matrixWorld = parent.matrixWorld.clone() + parent.matrixWorld.identity() - if (!rotation || typeof rotation === 'number') { - const o = new THREE.Object3D() + if (!rotation || typeof rotation === 'number') { + const o = new THREE.Object3D() - o.position.copy(state.position) - o.lookAt(parent.position) - if (typeof rotation === 'number') o.rotateZ(rotation) - applyProps(state as any, { rotation: o.rotation }) - } else { - applyProps(state as any, { rotation }) - } + o.position.copy(state.position) + o.lookAt(parent.position) + if (typeof rotation === 'number') o.rotateZ(rotation) + applyProps(state as any, { rotation: o.rotation }) + } else { + applyProps(state as any, { rotation }) + } - target.geometry = new DecalGeometry(parent, state.position, state.rotation, state.scale) - if (helper.current) { - applyProps(helper.current as any, state) - // Prevent the helpers from blocking rays - helper.current.traverse((child) => (child.raycast = () => null)) - } - // Reset parents matix-world - parent.matrixWorld = matrixWorld + target.geometry = new DecalGeometry(parent, state.position, state.rotation, state.scale) + if (helper.current) { + applyProps(helper.current as any, state) + // Prevent the helpers from blocking rays + helper.current.traverse((child) => (child.raycast = () => null)) + } + // Reset parents matix-world + parent.matrixWorld = matrixWorld - return () => { - target.geometry.dispose() - } + return () => { + target.geometry.dispose() } - }, [mesh, ...vecToArray(position), ...vecToArray(scale), ...vecToArray(rotation)]) + } + }, [mesh, ...vecToArray(position), ...vecToArray(scale), ...vecToArray(rotation)]) - // } - return ( - - {children} - {debug && ( - - - - - - )} - - ) - } -) + // } + return ( + + {children} + {debug && ( + + + + + + )} + + ) +}) diff --git a/src/core/Detailed.tsx b/src/core/Detailed.tsx index efb40f1e8..1cc78b146 100644 --- a/src/core/Detailed.tsx +++ b/src/core/Detailed.tsx @@ -10,7 +10,7 @@ type Props = JSX.IntrinsicElements['lOD'] & { distances: number[] } -export const Detailed: ForwardRefComponent = React.forwardRef( +export const Detailed: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ children, hysteresis = 0, distances, ...props }: Props, ref) => { const lodRef = React.useRef(null!) React.useLayoutEffect(() => { diff --git a/src/core/DeviceOrientationControls.tsx b/src/core/DeviceOrientationControls.tsx index 7f252591a..76ed16056 100644 --- a/src/core/DeviceOrientationControls.tsx +++ b/src/core/DeviceOrientationControls.tsx @@ -16,7 +16,7 @@ export type DeviceOrientationControlsProps = ReactThreeFiber.Object3DNode< export const DeviceOrientationControls: ForwardRefComponent< DeviceOrientationControlsProps, DeviceOrientationControlsImp -> = React.forwardRef( +> = /* @__PURE__ */ React.forwardRef( (props: DeviceOrientationControlsProps, ref) => { const { camera, onChange, makeDefault, ...rest } = props const defaultCamera = useThree((state) => state.camera) diff --git a/src/core/Edges.tsx b/src/core/Edges.tsx index f1983671a..7ffdc3cd1 100644 --- a/src/core/Edges.tsx +++ b/src/core/Edges.tsx @@ -8,7 +8,7 @@ type Props = JSX.IntrinsicElements['lineSegments'] & { color?: ReactThreeFiber.Color } -export const Edges: ForwardRefComponent = React.forwardRef( +export const Edges: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { userData, children, geometry, threshold = 15, color = 'black', ...props }: Props, fref: React.ForwardedRef diff --git a/src/core/Effects.tsx b/src/core/Effects.tsx index ea365452f..6da57bacd 100644 --- a/src/core/Effects.tsx +++ b/src/core/Effects.tsx @@ -37,7 +37,7 @@ export const isWebGL2Available = () => { } } -export const Effects: ForwardRefComponent = React.forwardRef( +export const Effects: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { children, diff --git a/src/core/Example.tsx b/src/core/Example.tsx index 3d7127170..d2bc14cd5 100644 --- a/src/core/Example.tsx +++ b/src/core/Example.tsx @@ -18,7 +18,7 @@ export type ExampleApi = { decr: (x?: number) => void } -export const Example = React.forwardRef( +export const Example = /* @__PURE__ */ React.forwardRef( ({ font, color = '#cbcbcb', bevelSize = 0.04, debug = false, children, ...props }, fref) => { const [counter, setCounter] = React.useState(0) diff --git a/src/core/FaceControls.tsx b/src/core/FaceControls.tsx index d567715ef..93d1ede8e 100644 --- a/src/core/FaceControls.tsx +++ b/src/core/FaceControls.tsx @@ -91,9 +91,9 @@ export type FaceControlsApi = THREE.EventDispatcher & { pause: () => void } -const FaceControlsContext = createContext({} as FaceControlsApi) +const FaceControlsContext = /* @__PURE__ */ createContext({} as FaceControlsApi) -export const FaceControls = forwardRef( +export const FaceControls = /* @__PURE__ */ forwardRef( ( { camera, @@ -328,7 +328,7 @@ type WebcamProps = { autostart?: boolean } -const Webcam = forwardRef(({ videoTextureSrc, autostart = true }, fref) => { +const Webcam = /* @__PURE__ */ forwardRef(({ videoTextureSrc, autostart = true }, fref) => { const videoTextureApiRef = useRef(null) const faceControls = useFaceControls() @@ -374,7 +374,7 @@ const Webcam = forwardRef(({ videoTextureSrc, autostart type VideoTextureApi = { texture: THREE.VideoTexture } type VideoTextureProps = { src: VideoTextureSrc; start: boolean } -const VideoTexture = forwardRef(({ src, start }, fref) => { +const VideoTexture = /* @__PURE__ */ forwardRef(({ src, start }, fref) => { const texture = useVideoTexture(src, { start }) const video = texture.source.data diff --git a/src/core/FaceLandmarker.tsx b/src/core/FaceLandmarker.tsx index f983da96f..18245aa4a 100644 --- a/src/core/FaceLandmarker.tsx +++ b/src/core/FaceLandmarker.tsx @@ -4,7 +4,7 @@ import { createContext, ReactNode, useContext, useEffect } from 'react' import { FilesetResolver, FaceLandmarker as FaceLandmarkerImpl, FaceLandmarkerOptions } from '@mediapipe/tasks-vision' import { clear, suspend } from 'suspend-react' -const FaceLandmarkerContext = createContext({} as FaceLandmarkerImpl | undefined) +const FaceLandmarkerContext = /* @__PURE__ */ createContext({} as FaceLandmarkerImpl | undefined) type FaceLandmarkerProps = { basePath?: string diff --git a/src/core/Facemesh.tsx b/src/core/Facemesh.tsx index c0da43c69..7890cf007 100644 --- a/src/core/Facemesh.tsx +++ b/src/core/Facemesh.tsx @@ -9,7 +9,7 @@ export type MediaPipeFaceMesh = typeof FacemeshDatas.SAMPLE_FACE export type MediaPipePoints = | typeof FacemeshDatas.SAMPLE_FACE.keypoints - | typeof FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.faceLandmarks[0] + | (typeof FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.faceLandmarks)[0] export type FacemeshProps = { /** an array of 468+ keypoints as returned by google/mediapipe tasks-vision, default: a sample face */ @@ -27,13 +27,13 @@ export type FacemeshProps = { /** a landmark index (to get the position from) or a vec3 to be the origin of the mesh. default: undefined (ie. the bbox center) */ origin?: number | THREE.Vector3 /** A facial transformation matrix, as returned by FaceLandmarkerResult.facialTransformationMatrixes (see: https://developers.google.com/mediapipe/solutions/vision/face_landmarker/web_js#handle_and_display_results) */ - facialTransformationMatrix?: typeof FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.facialTransformationMatrixes[0] + facialTransformationMatrix?: (typeof FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.facialTransformationMatrixes)[0] /** Apply position offset extracted from `facialTransformationMatrix` */ offset?: boolean /** Offset sensitivity factor, less is more sensible */ offsetScalar?: number /** Fface blendshapes, as returned by FaceLandmarkerResult.faceBlendshapes (see: https://developers.google.com/mediapipe/solutions/vision/face_landmarker/web_js#handle_and_display_results) */ - faceBlendshapes?: typeof FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.faceBlendshapes[0] + faceBlendshapes?: (typeof FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.faceBlendshapes)[0] /** whether to enable eyes (nb. `faceBlendshapes` is required for), default: true */ eyes?: boolean /** Force `origin` to be the middle of the 2 eyes (nb. `eyes` is required for), default: false */ @@ -49,9 +49,9 @@ export type FacemeshApi = { eyeLeftRef: React.RefObject } -const defaultLookAt = new THREE.Vector3(0, 0, -1) +const defaultLookAt = /* @__PURE__ */ new THREE.Vector3(0, 0, -1) -const normal = (function () { +const normal = /* @__PURE__ */ (function () { const a = new THREE.Vector3() const b = new THREE.Vector3() const c = new THREE.Vector3() @@ -79,7 +79,7 @@ function mean(v1: THREE.Vector3, v2: THREE.Vector3) { return v1.clone().add(v2).multiplyScalar(0.5) } -export const Facemesh = React.forwardRef( +export const Facemesh = /* @__PURE__ */ React.forwardRef( ( { points = FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.faceLandmarks[0], @@ -356,116 +356,118 @@ export const FacemeshEyeDefaults = { }, } -export const FacemeshEye = React.forwardRef(({ side, debug = true }, fref) => { - const eyeMeshRef = React.useRef(null) - const irisDirRef = React.useRef(null) +export const FacemeshEye = /* @__PURE__ */ React.forwardRef( + ({ side, debug = true }, fref) => { + const eyeMeshRef = React.useRef(null) + const irisDirRef = React.useRef(null) - // - // _computeSphere() - // - // Compute eye's sphere .position and .radius - // + // + // _computeSphere() + // + // Compute eye's sphere .position and .radius + // - const [sphere] = React.useState(() => new THREE.Sphere()) - const _computeSphere = React.useCallback( - (faceGeometry) => { - const position = faceGeometry.getAttribute('position') as THREE.BufferAttribute + const [sphere] = React.useState(() => new THREE.Sphere()) + const _computeSphere = React.useCallback( + (faceGeometry) => { + const position = faceGeometry.getAttribute('position') as THREE.BufferAttribute - // get some eye contour landmarks points (from geometry) - const eyeContourLandmarks = FacemeshEyeDefaults.contourLandmarks[side] - const eyeContourPoints = eyeContourLandmarks.map((i) => new THREE.Vector3(position.getX(i), position.getY(i), position.getZ(i))) // prettier-ignore + // get some eye contour landmarks points (from geometry) + const eyeContourLandmarks = FacemeshEyeDefaults.contourLandmarks[side] + const eyeContourPoints = eyeContourLandmarks.map((i) => new THREE.Vector3(position.getX(i), position.getY(i), position.getZ(i))) // prettier-ignore - // compute center (centroid from eyeContourPoints) - sphere.center.set(0, 0, 0) - eyeContourPoints.forEach((v) => sphere.center.add(v)) - sphere.center.divideScalar(eyeContourPoints.length) + // compute center (centroid from eyeContourPoints) + sphere.center.set(0, 0, 0) + eyeContourPoints.forEach((v) => sphere.center.add(v)) + sphere.center.divideScalar(eyeContourPoints.length) - // radius (eye half-width) - sphere.radius = eyeContourPoints[0].sub(eyeContourPoints[1]).length() / 2 + // radius (eye half-width) + sphere.radius = eyeContourPoints[0].sub(eyeContourPoints[1]).length() / 2 - return sphere - }, - [sphere, side] - ) - - // - // _update() - // - // Update: - // - A. eye's mesh (according to sphere) - // - B. iris direction (according to "look*" blendshapes) - // - - const [rotation] = React.useState(() => new THREE.Euler()) - const _update = React.useCallback( - (faceGeometry, faceBlendshapes, sphere) => { - // A. - if (eyeMeshRef.current) { - sphere ??= _computeSphere(faceGeometry) // compute sphere dims (if not passed) - eyeMeshRef.current.position.copy(sphere.center) - eyeMeshRef.current.scale.setScalar(sphere.radius) - } + return sphere + }, + [sphere, side] + ) + + // + // _update() + // + // Update: + // - A. eye's mesh (according to sphere) + // - B. iris direction (according to "look*" blendshapes) + // - // B. - if (faceBlendshapes && irisDirRef.current) { - const blendshapes = FacemeshEyeDefaults.blendshapes[side] + const [rotation] = React.useState(() => new THREE.Euler()) + const _update = React.useCallback( + (faceGeometry, faceBlendshapes, sphere) => { + // A. + if (eyeMeshRef.current) { + sphere ??= _computeSphere(faceGeometry) // compute sphere dims (if not passed) + eyeMeshRef.current.position.copy(sphere.center) + eyeMeshRef.current.scale.setScalar(sphere.radius) + } - const lookIn = faceBlendshapes.categories[blendshapes[0]].score - const lookOut = faceBlendshapes.categories[blendshapes[1]].score - const lookUp = faceBlendshapes.categories[blendshapes[2]].score - const lookDown = faceBlendshapes.categories[blendshapes[3]].score + // B. + if (faceBlendshapes && irisDirRef.current) { + const blendshapes = FacemeshEyeDefaults.blendshapes[side] - const hfov = FacemeshEyeDefaults.fov.horizontal * THREE.MathUtils.DEG2RAD - const vfov = FacemeshEyeDefaults.fov.vertical * THREE.MathUtils.DEG2RAD - const rx = hfov * 0.5 * (lookDown - lookUp) - const ry = vfov * 0.5 * (lookIn - lookOut) * (side === 'left' ? 1 : -1) - rotation.set(rx, ry, 0) + const lookIn = faceBlendshapes.categories[blendshapes[0]].score + const lookOut = faceBlendshapes.categories[blendshapes[1]].score + const lookUp = faceBlendshapes.categories[blendshapes[2]].score + const lookDown = faceBlendshapes.categories[blendshapes[3]].score - irisDirRef.current.setRotationFromEuler(rotation) - } - }, - [_computeSphere, side, rotation] - ) - - // - // API - // - - const api = React.useMemo( - () => ({ - eyeMeshRef: eyeMeshRef, - irisDirRef: irisDirRef, - _computeSphere, - _update, - }), - [_computeSphere, _update] - ) - React.useImperativeHandle(fref, () => api, [api]) - - const color = FacemeshEyeDefaults.color[side] - return ( - - - {debug && } - - - <> - {debug && ( - - )} - + const hfov = FacemeshEyeDefaults.fov.horizontal * THREE.MathUtils.DEG2RAD + const vfov = FacemeshEyeDefaults.fov.vertical * THREE.MathUtils.DEG2RAD + const rx = hfov * 0.5 * (lookDown - lookUp) + const ry = vfov * 0.5 * (lookIn - lookOut) * (side === 'left' ? 1 : -1) + rotation.set(rx, ry, 0) + + irisDirRef.current.setRotationFromEuler(rotation) + } + }, + [_computeSphere, side, rotation] + ) + + // + // API + // + + const api = React.useMemo( + () => ({ + eyeMeshRef: eyeMeshRef, + irisDirRef: irisDirRef, + _computeSphere, + _update, + }), + [_computeSphere, _update] + ) + React.useImperativeHandle(fref, () => api, [api]) + + const color = FacemeshEyeDefaults.color[side] + return ( + + + {debug && } + + + <> + {debug && ( + + )} + + - - ) -}) + ) + } +) // // Sample datas diff --git a/src/core/FirstPersonControls.tsx b/src/core/FirstPersonControls.tsx index 482f2de88..d69c9ff0c 100644 --- a/src/core/FirstPersonControls.tsx +++ b/src/core/FirstPersonControls.tsx @@ -9,26 +9,28 @@ export type FirstPersonControlsProps = Object3DNode = - React.forwardRef(({ domElement, makeDefault, ...props }, ref) => { - const camera = useThree((state) => state.camera) - const gl = useThree((state) => state.gl) - const events = useThree((state) => state.events) as EventManager - const get = useThree((state) => state.get) - const set = useThree((state) => state.set) - const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement - const [controls] = React.useState(() => new FirstPersonControlImpl(camera, explDomElement)) + /* @__PURE__ */ React.forwardRef( + ({ domElement, makeDefault, ...props }, ref) => { + const camera = useThree((state) => state.camera) + const gl = useThree((state) => state.gl) + const events = useThree((state) => state.events) as EventManager + const get = useThree((state) => state.get) + const set = useThree((state) => state.set) + const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement + const [controls] = React.useState(() => new FirstPersonControlImpl(camera, explDomElement)) - React.useEffect(() => { - if (makeDefault) { - const old = get().controls - set({ controls }) - return () => set({ controls: old }) - } - }, [makeDefault, controls]) + React.useEffect(() => { + if (makeDefault) { + const old = get().controls + set({ controls }) + return () => set({ controls: old }) + } + }, [makeDefault, controls]) - useFrame((_, delta) => { - controls.update(delta) - }, -1) + useFrame((_, delta) => { + controls.update(delta) + }, -1) - return controls ? : null - }) + return controls ? : null + } + ) diff --git a/src/core/Float.tsx b/src/core/Float.tsx index fe8c3ad87..311df711f 100644 --- a/src/core/Float.tsx +++ b/src/core/Float.tsx @@ -13,7 +13,10 @@ export type FloatProps = JSX.IntrinsicElements['group'] & { floatingRange?: [number?, number?] } -export const Float: ForwardRefComponent = React.forwardRef( +export const Float: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + THREE.Group, + FloatProps +>( ( { children, diff --git a/src/core/FlyControls.tsx b/src/core/FlyControls.tsx index 46d5ff5d1..081e4378c 100644 --- a/src/core/FlyControls.tsx +++ b/src/core/FlyControls.tsx @@ -10,7 +10,7 @@ export type FlyControlsProps = ReactThreeFiber.Object3DNode = React.forwardRef< +export const FlyControls: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< FlyControlsImpl, FlyControlsProps >(({ domElement, ...props }, fref) => { diff --git a/src/core/GizmoHelper.tsx b/src/core/GizmoHelper.tsx index 69f85ad80..9873a8451 100644 --- a/src/core/GizmoHelper.tsx +++ b/src/core/GizmoHelper.tsx @@ -9,18 +9,18 @@ type GizmoHelperContext = { tweenCamera: (direction: Vector3) => void } -const Context = React.createContext({} as GizmoHelperContext) +const Context = /* @__PURE__ */ React.createContext({} as GizmoHelperContext) export const useGizmoContext = () => { return React.useContext(Context) } const turnRate = 2 * Math.PI // turn rate in angles per second -const dummy = new Object3D() -const matrix = new Matrix4() -const [q1, q2] = [new Quaternion(), new Quaternion()] -const target = new Vector3() -const targetPosition = new Vector3() +const dummy = /* @__PURE__ */ new Object3D() +const matrix = /* @__PURE__ */ new Matrix4() +const [q1, q2] = [/* @__PURE__ */ new Quaternion(), /* @__PURE__ */ new Quaternion()] +const target = /* @__PURE__ */ new Vector3() +const targetPosition = /* @__PURE__ */ new Vector3() type ControlsProto = { update(): void; target: THREE.Vector3 } diff --git a/src/core/GizmoViewcube.tsx b/src/core/GizmoViewcube.tsx index fb46a4b85..44fe74f60 100644 --- a/src/core/GizmoViewcube.tsx +++ b/src/core/GizmoViewcube.tsx @@ -21,7 +21,7 @@ const colors = { bg: '#f0f0f0', hover: '#999', text: 'black', stroke: 'black' } const defaultFaces = ['Right', 'Left', 'Top', 'Bottom', 'Front', 'Back'] const makePositionVector = (xyz: number[]) => new Vector3(...xyz).multiplyScalar(0.38) -const corners: Vector3[] = [ +const corners: Vector3[] = /* @__PURE__ */ [ [1, 1, 1], [1, 1, -1], [1, -1, 1], @@ -34,7 +34,7 @@ const corners: Vector3[] = [ const cornerDimensions: XYZ = [0.25, 0.25, 0.25] -const edges: Vector3[] = [ +const edges: Vector3[] = /* @__PURE__ */ [ [1, 1, 0], [1, 0, 1], [1, 0, -1], @@ -49,7 +49,7 @@ const edges: Vector3[] = [ [-1, -1, 0], ].map(makePositionVector) -const edgeDimensions = edges.map( +const edgeDimensions = /* @__PURE__ */ edges.map( (edge) => edge.toArray().map((axis: number): number => (axis == 0 ? 0.5 : 0.25)) as XYZ ) diff --git a/src/core/Gltf.tsx b/src/core/Gltf.tsx index ce4b605a7..363d0d007 100644 --- a/src/core/Gltf.tsx +++ b/src/core/Gltf.tsx @@ -9,7 +9,7 @@ type GltfProps = Omit & src: string } -export const Gltf: ForwardRefComponent = React.forwardRef( +export const Gltf: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ src, ...props }: GltfProps, ref: React.Ref) => { const { scene } = useGLTF(src) return diff --git a/src/core/Grid.tsx b/src/core/Grid.tsx index 4b3df2a8e..3e82a6344 100644 --- a/src/core/Grid.tsx +++ b/src/core/Grid.tsx @@ -10,6 +10,7 @@ import mergeRefs from 'react-merge-refs' import { extend, useFrame } from '@react-three/fiber' import { shaderMaterial } from './shaderMaterial' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' export type GridMaterialType = { /** Cell size, default: 0.5 */ @@ -49,7 +50,7 @@ declare global { } } -const GridMaterial = shaderMaterial( +const GridMaterial = /* @__PURE__ */ shaderMaterial( { cellSize: 0.5, sectionSize: 1, @@ -57,12 +58,12 @@ const GridMaterial = shaderMaterial( fadeStrength: 1, cellThickness: 0.5, sectionThickness: 1, - cellColor: new THREE.Color(), - sectionColor: new THREE.Color(), + cellColor: /* @__PURE__ */ new THREE.Color(), + sectionColor: /* @__PURE__ */ new THREE.Color(), infiniteGrid: false, followCamera: false, - worldCamProjPosition: new THREE.Vector3(), - worldPlanePosition: new THREE.Vector3(), + worldCamProjPosition: /* @__PURE__ */ new THREE.Vector3(), + worldPlanePosition: /* @__PURE__ */ new THREE.Vector3(), }, /* glsl */ ` varying vec3 localPosition; @@ -121,13 +122,13 @@ const GridMaterial = shaderMaterial( if (gl_FragColor.a <= 0.0) discard; #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> } ` ) export const Grid: ForwardRefComponent & GridProps, THREE.Mesh> = - React.forwardRef( + /* @__PURE__ */ React.forwardRef( ( { args, diff --git a/src/core/Image.tsx b/src/core/Image.tsx index 590cfc8c9..675cf209d 100644 --- a/src/core/Image.tsx +++ b/src/core/Image.tsx @@ -4,6 +4,7 @@ import { Color, extend } from '@react-three/fiber' import { shaderMaterial } from './shaderMaterial' import { useTexture } from './useTexture' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' export type ImageProps = Omit & { segments?: number @@ -33,8 +34,16 @@ declare global { } } -const ImageMaterialImpl = shaderMaterial( - { color: new THREE.Color('white'), scale: [1, 1], imageBounds: [1, 1], map: null, zoom: 1, grayscale: 0, opacity: 1 }, +const ImageMaterialImpl = /* @__PURE__ */ shaderMaterial( + { + color: /* @__PURE__ */ new THREE.Color('white'), + scale: [1, 1], + imageBounds: [1, 1], + map: null, + zoom: 1, + grayscale: 0, + opacity: 1, + }, /* glsl */ ` varying vec2 vUv; void main() { @@ -71,12 +80,12 @@ const ImageMaterialImpl = shaderMaterial( gl_FragColor = toGrayscale(texture2D(map, zUv) * vec4(color, opacity), grayscale); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> } ` ) -const ImageBase: ForwardRefComponent, THREE.Mesh> = React.forwardRef( +const ImageBase: ForwardRefComponent, THREE.Mesh> = /* @__PURE__ */ React.forwardRef( ( { children, @@ -116,23 +125,24 @@ const ImageBase: ForwardRefComponent, THREE.Mesh> = Reac } ) -const ImageWithUrl: ForwardRefComponent = React.forwardRef( +const ImageWithUrl: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ url, ...props }: ImageProps, ref: React.ForwardedRef) => { const texture = useTexture(url!) return } ) -const ImageWithTexture: ForwardRefComponent = React.forwardRef( +const ImageWithTexture: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ url: _url, ...props }: ImageProps, ref: React.ForwardedRef) => { return } ) -export const Image: ForwardRefComponent = React.forwardRef( - (props, ref) => { - if (props.url) return - else if (props.texture) return - else throw new Error(' requires a url or texture') - } -) +export const Image: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + THREE.Mesh, + ImageProps +>((props, ref) => { + if (props.url) return + else if (props.texture) return + else throw new Error(' requires a url or texture') +}) diff --git a/src/core/Instances.tsx b/src/core/Instances.tsx index 9515b2046..3ebaf43e9 100644 --- a/src/core/Instances.tsx +++ b/src/core/Instances.tsx @@ -33,10 +33,10 @@ type InstancedMesh = Omit() +const _instanceLocalMatrix = /* @__PURE__ */ new THREE.Matrix4() +const _instanceWorldMatrix = /* @__PURE__ */ new THREE.Matrix4() +const _instanceIntersects: THREE.Intersection[] = [] +const _mesh = /* @__PURE__ */ new THREE.Mesh() class PositionMesh extends THREE.Group { color: THREE.Color @@ -84,15 +84,15 @@ class PositionMesh extends THREE.Group { } } -const globalContext = /*@__PURE__*/ React.createContext(null!) -const parentMatrix = /*@__PURE__*/ new THREE.Matrix4() -const instanceMatrix = /*@__PURE__*/ new THREE.Matrix4() -const tempMatrix = /*@__PURE__*/ new THREE.Matrix4() -const translation = /*@__PURE__*/ new THREE.Vector3() -const rotation = /*@__PURE__*/ new THREE.Quaternion() -const scale = /*@__PURE__*/ new THREE.Vector3() +const globalContext = /* @__PURE__ */ React.createContext(null!) +const parentMatrix = /* @__PURE__ */ new THREE.Matrix4() +const instanceMatrix = /* @__PURE__ */ new THREE.Matrix4() +const tempMatrix = /* @__PURE__ */ new THREE.Matrix4() +const translation = /* @__PURE__ */ new THREE.Vector3() +const rotation = /* @__PURE__ */ new THREE.Quaternion() +const scale = /* @__PURE__ */ new THREE.Vector3() -export const Instance = React.forwardRef(({ context, children, ...props }: InstanceProps, ref) => { +export const Instance = /* @__PURE__ */ React.forwardRef(({ context, children, ...props }: InstanceProps, ref) => { React.useMemo(() => extend({ PositionMesh }), []) const group = React.useRef() const { subscribe, getParent } = React.useContext(context || globalContext) @@ -104,7 +104,7 @@ export const Instance = React.forwardRef(({ context, children, ...props }: Insta ) }) -export const Instances: ForwardRefComponent = React.forwardRef< +export const Instances: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< InstancedMesh, InstancesProps >(({ children, range, limit = 1000, frames = Infinity, ...props }, ref) => { @@ -205,30 +205,29 @@ export interface MergedProps extends InstancesProps { children: React.ReactNode } -export const Merged: ForwardRefComponent = React.forwardRef(function Merged( - { meshes, children, ...props }, - ref -) { - const isArray = Array.isArray(meshes) - // Filter out meshes from collections, which may contain non-meshes - if (!isArray) for (const key of Object.keys(meshes)) if (!meshes[key].isMesh) delete meshes[key] - return ( - - ( - - ))} - > - {(args) => - isArray - ? children(...args) - : children( - Object.keys(meshes) - .filter((key) => meshes[key].isMesh) - .reduce((acc, key, i) => ({ ...acc, [key]: args[i] }), {}) - ) - } - - - ) -}) +export const Merged: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( + function Merged({ meshes, children, ...props }, ref) { + const isArray = Array.isArray(meshes) + // Filter out meshes from collections, which may contain non-meshes + if (!isArray) for (const key of Object.keys(meshes)) if (!meshes[key].isMesh) delete meshes[key] + return ( + + ( + + ))} + > + {(args) => + isArray + ? children(...args) + : children( + Object.keys(meshes) + .filter((key) => meshes[key].isMesh) + .reduce((acc, key, i) => ({ ...acc, [key]: args[i] }), {}) + ) + } + + + ) + } +) diff --git a/src/core/Lightformer.tsx b/src/core/Lightformer.tsx index eb61e85ad..178d51986 100644 --- a/src/core/Lightformer.tsx +++ b/src/core/Lightformer.tsx @@ -15,7 +15,7 @@ export type LightProps = JSX.IntrinsicElements['mesh'] & { target?: [number, number, number] | THREE.Vector3 } -export const Lightformer: ForwardRefComponent = React.forwardRef( +export const Lightformer: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { args, diff --git a/src/core/Line.tsx b/src/core/Line.tsx index 99da1ee65..af1c502e0 100644 --- a/src/core/Line.tsx +++ b/src/core/Line.tsx @@ -22,7 +22,7 @@ export type LineProps = { color?: ColorRepresentation } -export const Line: ForwardRefComponent = React.forwardRef< +export const Line: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< Line2 | LineSegments2, LineProps >(function Line({ points, color = 'black', vertexColors, linewidth, lineWidth, segments, dashed, ...rest }, ref) { diff --git a/src/core/MapControls.tsx b/src/core/MapControls.tsx index 00ffc7ba3..83f4f8c1e 100644 --- a/src/core/MapControls.tsx +++ b/src/core/MapControls.tsx @@ -17,7 +17,7 @@ export type MapControlsProps = ReactThreeFiber.Overwrite< } > -export const MapControls: ForwardRefComponent = React.forwardRef< +export const MapControls: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< MapControlsImpl, MapControlsProps >((props = { enableDamping: true }, ref) => { diff --git a/src/core/MarchingCubes.tsx b/src/core/MarchingCubes.tsx index 6fe29ea27..27f661d38 100644 --- a/src/core/MarchingCubes.tsx +++ b/src/core/MarchingCubes.tsx @@ -10,7 +10,7 @@ type Api = { getParent: () => React.MutableRefObject } -const globalContext = React.createContext(null!) +const globalContext = /* @__PURE__ */ React.createContext(null!) export type MarchingCubesProps = { resolution?: number @@ -19,39 +19,41 @@ export type MarchingCubesProps = { enableColors?: boolean } & JSX.IntrinsicElements['group'] -export const MarchingCubes: ForwardRefComponent = React.forwardRef( - ( - { - resolution = 28, - maxPolyCount = 10000, - enableUvs = false, - enableColors = false, - children, - ...props - }: MarchingCubesProps, - ref - ) => { - const marchingCubesRef = React.useRef(null!) - const marchingCubes = React.useMemo( - () => new MarchingCubesImpl(resolution, null as unknown as THREE.Material, enableUvs, enableColors, maxPolyCount), - [resolution, maxPolyCount, enableUvs, enableColors] - ) - const api = React.useMemo(() => ({ getParent: () => marchingCubesRef }), []) +export const MarchingCubes: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ( + { + resolution = 28, + maxPolyCount = 10000, + enableUvs = false, + enableColors = false, + children, + ...props + }: MarchingCubesProps, + ref + ) => { + const marchingCubesRef = React.useRef(null!) + const marchingCubes = React.useMemo( + () => + new MarchingCubesImpl(resolution, null as unknown as THREE.Material, enableUvs, enableColors, maxPolyCount), + [resolution, maxPolyCount, enableUvs, enableColors] + ) + const api = React.useMemo(() => ({ getParent: () => marchingCubesRef }), []) - useFrame(() => { - marchingCubes.update() - marchingCubes.reset() - }, -1) // To make sure the reset runs before the balls or planes are added + useFrame(() => { + marchingCubes.update() + marchingCubes.reset() + }, -1) // To make sure the reset runs before the balls or planes are added - return ( - <> - - {children} - - - ) - } -) + return ( + <> + + {children} + + + ) + } + ) type MarchingCubeProps = { strength?: number @@ -59,7 +61,7 @@ type MarchingCubeProps = { color?: Color } & JSX.IntrinsicElements['group'] -export const MarchingCube: ForwardRefComponent = React.forwardRef( +export const MarchingCube: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ strength = 0.5, subtract = 12, color, ...props }: MarchingCubeProps, ref) => { const { getParent } = React.useContext(globalContext) const parentRef = React.useMemo(() => getParent(), [getParent]) @@ -80,7 +82,7 @@ type MarchingPlaneProps = { subtract?: number } & JSX.IntrinsicElements['group'] -export const MarchingPlane: ForwardRefComponent = React.forwardRef( +export const MarchingPlane: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ planeType: _planeType = 'x', strength = 0.5, subtract = 12, ...props }: MarchingPlaneProps, ref) => { const { getParent } = React.useContext(globalContext) const parentRef = React.useMemo(() => getParent(), [getParent]) diff --git a/src/core/Mask.tsx b/src/core/Mask.tsx index 2ef248e83..4e04769ba 100644 --- a/src/core/Mask.tsx +++ b/src/core/Mask.tsx @@ -11,7 +11,7 @@ type Props = Omit & { depthWrite?: boolean } -export const Mask: ForwardRefComponent = React.forwardRef( +export const Mask: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ id = 1, colorWrite = false, depthWrite = false, ...props }: Props, fref: React.ForwardedRef) => { const ref = React.useRef(null!) const spread = React.useMemo( diff --git a/src/core/MeshDiscardMaterial.tsx b/src/core/MeshDiscardMaterial.tsx index 083cc1aa3..fcd291771 100644 --- a/src/core/MeshDiscardMaterial.tsx +++ b/src/core/MeshDiscardMaterial.tsx @@ -12,7 +12,9 @@ declare global { } export const MeshDiscardMaterial: ForwardRefComponent = - React.forwardRef((props: JSX.IntrinsicElements['shaderMaterial'], fref: React.ForwardedRef) => { - extend({ DiscardMaterialImpl }) - return - }) + /* @__PURE__ */ React.forwardRef( + (props: JSX.IntrinsicElements['shaderMaterial'], fref: React.ForwardedRef) => { + extend({ DiscardMaterialImpl }) + return + } + ) diff --git a/src/core/MeshDistortMaterial.tsx b/src/core/MeshDistortMaterial.tsx index 7ec81a113..0cee69317 100644 --- a/src/core/MeshDistortMaterial.tsx +++ b/src/core/MeshDistortMaterial.tsx @@ -89,7 +89,7 @@ class DistortMaterialImpl extends MeshPhysicalMaterial { } } -export const MeshDistortMaterial: ForwardRefComponent = React.forwardRef( +export const MeshDistortMaterial: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ speed = 1, ...props }: Props, ref) => { const [material] = React.useState(() => new DistortMaterialImpl()) useFrame((state) => material && (material.time = state.clock.getElapsedTime() * speed)) diff --git a/src/core/MeshPortalMaterial.tsx b/src/core/MeshPortalMaterial.tsx index 87fdfb64c..5ec7aa20a 100644 --- a/src/core/MeshPortalMaterial.tsx +++ b/src/core/MeshPortalMaterial.tsx @@ -11,15 +11,16 @@ import { useFBO } from './useFBO' import { RenderTexture } from './RenderTexture' import { shaderMaterial } from './shaderMaterial' import { FullScreenQuad } from 'three-stdlib' +import { version } from '../helpers/constants' -const PortalMaterialImpl = shaderMaterial( +const PortalMaterialImpl = /* @__PURE__ */ shaderMaterial( { blur: 0, map: null, sdf: null, blend: 0, size: 0, - resolution: new THREE.Vector2(), + resolution: /* @__PURE__ */ new THREE.Vector2(), }, `varying vec2 vUv; void main() { @@ -42,7 +43,7 @@ const PortalMaterialImpl = shaderMaterial( float alpha = 1.0 - smoothstep(0.0, 1.0, clamp(d/k + 1.0, 0.0, 1.0)); gl_FragColor = vec4(t.rgb, blur == 0.0 ? t.a : t.a * alpha); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }` ) @@ -81,7 +82,7 @@ export type PortalProps = JSX.IntrinsicElements['shaderMaterial'] & { events?: boolean } -export const MeshPortalMaterial = React.forwardRef( +export const MeshPortalMaterial = /* @__PURE__ */ React.forwardRef( ( { children, @@ -261,9 +262,7 @@ function ManagePortalScene({ vec4 ta = texture2D(a, vUv); vec4 tb = texture2D(b, vUv); gl_FragColor = mix(tb, ta, blend); - #include <${ - parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment' - }> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }`, }) ) diff --git a/src/core/MeshReflectorMaterial.tsx b/src/core/MeshReflectorMaterial.tsx index 001710193..6bec45cfd 100644 --- a/src/core/MeshReflectorMaterial.tsx +++ b/src/core/MeshReflectorMaterial.tsx @@ -47,135 +47,158 @@ declare global { } } -extend({ MeshReflectorMaterialImpl }) - -export const MeshReflectorMaterial: ForwardRefComponent = React.forwardRef< - MeshReflectorMaterialImpl, - Props ->( - ( - { - mixBlur = 0, - mixStrength = 1, - resolution = 256, - blur = [0, 0], - minDepthThreshold = 0.9, - maxDepthThreshold = 1, - depthScale = 0, - depthToBlurRatioBias = 0.25, - mirror = 0, - distortion = 1, - mixContrast = 1, - distortionMap, - reflectorOffset = 0, - ...props - }, - ref - ) => { - const gl = useThree(({ gl }) => gl) - const camera = useThree(({ camera }) => camera) - const scene = useThree(({ scene }) => scene) - blur = Array.isArray(blur) ? blur : [blur, blur] - const hasBlur = blur[0] + blur[1] > 0 - const materialRef = React.useRef(null!) - const [reflectorPlane] = React.useState(() => new Plane()) - const [normal] = React.useState(() => new Vector3()) - const [reflectorWorldPosition] = React.useState(() => new Vector3()) - const [cameraWorldPosition] = React.useState(() => new Vector3()) - const [rotationMatrix] = React.useState(() => new Matrix4()) - const [lookAtPosition] = React.useState(() => new Vector3(0, 0, -1)) - const [clipPlane] = React.useState(() => new Vector4()) - const [view] = React.useState(() => new Vector3()) - const [target] = React.useState(() => new Vector3()) - const [q] = React.useState(() => new Vector4()) - const [textureMatrix] = React.useState(() => new Matrix4()) - const [virtualCamera] = React.useState(() => new PerspectiveCamera()) +export const MeshReflectorMaterial: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ( + { + mixBlur = 0, + mixStrength = 1, + resolution = 256, + blur = [0, 0], + minDepthThreshold = 0.9, + maxDepthThreshold = 1, + depthScale = 0, + depthToBlurRatioBias = 0.25, + mirror = 0, + distortion = 1, + mixContrast = 1, + distortionMap, + reflectorOffset = 0, + ...props + }, + ref + ) => { + extend({ MeshReflectorMaterialImpl }) + const gl = useThree(({ gl }) => gl) + const camera = useThree(({ camera }) => camera) + const scene = useThree(({ scene }) => scene) + blur = Array.isArray(blur) ? blur : [blur, blur] + const hasBlur = blur[0] + blur[1] > 0 + const materialRef = React.useRef(null!) + const [reflectorPlane] = React.useState(() => new Plane()) + const [normal] = React.useState(() => new Vector3()) + const [reflectorWorldPosition] = React.useState(() => new Vector3()) + const [cameraWorldPosition] = React.useState(() => new Vector3()) + const [rotationMatrix] = React.useState(() => new Matrix4()) + const [lookAtPosition] = React.useState(() => new Vector3(0, 0, -1)) + const [clipPlane] = React.useState(() => new Vector4()) + const [view] = React.useState(() => new Vector3()) + const [target] = React.useState(() => new Vector3()) + const [q] = React.useState(() => new Vector4()) + const [textureMatrix] = React.useState(() => new Matrix4()) + const [virtualCamera] = React.useState(() => new PerspectiveCamera()) - const beforeRender = React.useCallback(() => { - // TODO: As of R3f 7-8 this should be __r3f.parent - const parent = (materialRef.current as any).parent || (materialRef.current as any)?.__r3f.parent - if (!parent) return + const beforeRender = React.useCallback(() => { + // TODO: As of R3f 7-8 this should be __r3f.parent + const parent = (materialRef.current as any).parent || (materialRef.current as any)?.__r3f.parent + if (!parent) return - reflectorWorldPosition.setFromMatrixPosition(parent.matrixWorld) - cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld) - rotationMatrix.extractRotation(parent.matrixWorld) - normal.set(0, 0, 1) - normal.applyMatrix4(rotationMatrix) - reflectorWorldPosition.addScaledVector(normal, reflectorOffset) - view.subVectors(reflectorWorldPosition, cameraWorldPosition) - // Avoid rendering when reflector is facing away - if (view.dot(normal) > 0) return - view.reflect(normal).negate() - view.add(reflectorWorldPosition) - rotationMatrix.extractRotation(camera.matrixWorld) - lookAtPosition.set(0, 0, -1) - lookAtPosition.applyMatrix4(rotationMatrix) - lookAtPosition.add(cameraWorldPosition) - target.subVectors(reflectorWorldPosition, lookAtPosition) - target.reflect(normal).negate() - target.add(reflectorWorldPosition) - virtualCamera.position.copy(view) - virtualCamera.up.set(0, 1, 0) - virtualCamera.up.applyMatrix4(rotationMatrix) - virtualCamera.up.reflect(normal) - virtualCamera.lookAt(target) - virtualCamera.far = camera.far // Used in WebGLBackground - virtualCamera.updateMatrixWorld() - virtualCamera.projectionMatrix.copy(camera.projectionMatrix) - // Update the texture matrix - textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0) - textureMatrix.multiply(virtualCamera.projectionMatrix) - textureMatrix.multiply(virtualCamera.matrixWorldInverse) - textureMatrix.multiply(parent.matrixWorld) - // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html - // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf - reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition) - reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse) - clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant) - const projectionMatrix = virtualCamera.projectionMatrix - q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0] - q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5] - q.z = -1.0 - q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14] - // Calculate the scaled plane vector - clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)) - // Replacing the third row of the projection matrix - projectionMatrix.elements[2] = clipPlane.x - projectionMatrix.elements[6] = clipPlane.y - projectionMatrix.elements[10] = clipPlane.z + 1.0 - projectionMatrix.elements[14] = clipPlane.w - }, [camera, reflectorOffset]) + reflectorWorldPosition.setFromMatrixPosition(parent.matrixWorld) + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld) + rotationMatrix.extractRotation(parent.matrixWorld) + normal.set(0, 0, 1) + normal.applyMatrix4(rotationMatrix) + reflectorWorldPosition.addScaledVector(normal, reflectorOffset) + view.subVectors(reflectorWorldPosition, cameraWorldPosition) + // Avoid rendering when reflector is facing away + if (view.dot(normal) > 0) return + view.reflect(normal).negate() + view.add(reflectorWorldPosition) + rotationMatrix.extractRotation(camera.matrixWorld) + lookAtPosition.set(0, 0, -1) + lookAtPosition.applyMatrix4(rotationMatrix) + lookAtPosition.add(cameraWorldPosition) + target.subVectors(reflectorWorldPosition, lookAtPosition) + target.reflect(normal).negate() + target.add(reflectorWorldPosition) + virtualCamera.position.copy(view) + virtualCamera.up.set(0, 1, 0) + virtualCamera.up.applyMatrix4(rotationMatrix) + virtualCamera.up.reflect(normal) + virtualCamera.lookAt(target) + virtualCamera.far = camera.far // Used in WebGLBackground + virtualCamera.updateMatrixWorld() + virtualCamera.projectionMatrix.copy(camera.projectionMatrix) + // Update the texture matrix + textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0) + textureMatrix.multiply(virtualCamera.projectionMatrix) + textureMatrix.multiply(virtualCamera.matrixWorldInverse) + textureMatrix.multiply(parent.matrixWorld) + // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html + // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf + reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition) + reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse) + clipPlane.set( + reflectorPlane.normal.x, + reflectorPlane.normal.y, + reflectorPlane.normal.z, + reflectorPlane.constant + ) + const projectionMatrix = virtualCamera.projectionMatrix + q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0] + q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5] + q.z = -1.0 + q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14] + // Calculate the scaled plane vector + clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)) + // Replacing the third row of the projection matrix + projectionMatrix.elements[2] = clipPlane.x + projectionMatrix.elements[6] = clipPlane.y + projectionMatrix.elements[10] = clipPlane.z + 1.0 + projectionMatrix.elements[14] = clipPlane.w + }, [camera, reflectorOffset]) - const [fbo1, fbo2, blurpass, reflectorProps] = React.useMemo(() => { - const parameters = { - minFilter: LinearFilter, - magFilter: LinearFilter, - type: HalfFloatType, - } - const fbo1 = new WebGLRenderTarget(resolution, resolution, parameters) - fbo1.depthBuffer = true - fbo1.depthTexture = new DepthTexture(resolution, resolution) - fbo1.depthTexture.format = DepthFormat - fbo1.depthTexture.type = UnsignedShortType - const fbo2 = new WebGLRenderTarget(resolution, resolution, parameters) - const blurpass = new BlurPass({ + const [fbo1, fbo2, blurpass, reflectorProps] = React.useMemo(() => { + const parameters = { + minFilter: LinearFilter, + magFilter: LinearFilter, + type: HalfFloatType, + } + const fbo1 = new WebGLRenderTarget(resolution, resolution, parameters) + fbo1.depthBuffer = true + fbo1.depthTexture = new DepthTexture(resolution, resolution) + fbo1.depthTexture.format = DepthFormat + fbo1.depthTexture.type = UnsignedShortType + const fbo2 = new WebGLRenderTarget(resolution, resolution, parameters) + const blurpass = new BlurPass({ + gl, + resolution, + width: blur[0], + height: blur[1], + minDepthThreshold, + maxDepthThreshold, + depthScale, + depthToBlurRatioBias, + }) + const reflectorProps = { + mirror, + textureMatrix, + mixBlur, + tDiffuse: fbo1.texture, + tDepth: fbo1.depthTexture, + tDiffuseBlur: fbo2.texture, + hasBlur, + mixStrength, + minDepthThreshold, + maxDepthThreshold, + depthScale, + depthToBlurRatioBias, + distortion, + distortionMap, + mixContrast, + 'defines-USE_BLUR': hasBlur ? '' : undefined, + 'defines-USE_DEPTH': depthScale > 0 ? '' : undefined, + 'defines-USE_DISTORTION': distortionMap ? '' : undefined, + } + return [fbo1, fbo2, blurpass, reflectorProps] + }, [ gl, + blur, + textureMatrix, resolution, - width: blur[0], - height: blur[1], - minDepthThreshold, - maxDepthThreshold, - depthScale, - depthToBlurRatioBias, - }) - const reflectorProps = { mirror, - textureMatrix, - mixBlur, - tDiffuse: fbo1.texture, - tDepth: fbo1.depthTexture, - tDiffuseBlur: fbo2.texture, hasBlur, + mixBlur, mixStrength, minDepthThreshold, maxDepthThreshold, @@ -184,65 +207,44 @@ export const MeshReflectorMaterial: ForwardRefComponent 0 ? '' : undefined, - 'defines-USE_DISTORTION': distortionMap ? '' : undefined, - } - return [fbo1, fbo2, blurpass, reflectorProps] - }, [ - gl, - blur, - textureMatrix, - resolution, - mirror, - hasBlur, - mixBlur, - mixStrength, - minDepthThreshold, - maxDepthThreshold, - depthScale, - depthToBlurRatioBias, - distortion, - distortionMap, - mixContrast, - ]) + ]) - useFrame(() => { - // TODO: As of R3f 7-8 this should be __r3f.parent - const parent = (materialRef.current as any).parent || (materialRef.current as any)?.__r3f.parent - if (!parent) return + useFrame(() => { + // TODO: As of R3f 7-8 this should be __r3f.parent + const parent = (materialRef.current as any).parent || (materialRef.current as any)?.__r3f.parent + if (!parent) return - parent.visible = false - const currentXrEnabled = gl.xr.enabled - const currentShadowAutoUpdate = gl.shadowMap.autoUpdate - beforeRender() - gl.xr.enabled = false - gl.shadowMap.autoUpdate = false - gl.setRenderTarget(fbo1) - gl.state.buffers.depth.setMask(true) - if (!gl.autoClear) gl.clear() - gl.render(scene, virtualCamera) - if (hasBlur) blurpass.render(gl, fbo1, fbo2) - gl.xr.enabled = currentXrEnabled - gl.shadowMap.autoUpdate = currentShadowAutoUpdate - parent.visible = true - gl.setRenderTarget(null) - }) + parent.visible = false + const currentXrEnabled = gl.xr.enabled + const currentShadowAutoUpdate = gl.shadowMap.autoUpdate + beforeRender() + gl.xr.enabled = false + gl.shadowMap.autoUpdate = false + gl.setRenderTarget(fbo1) + gl.state.buffers.depth.setMask(true) + if (!gl.autoClear) gl.clear() + gl.render(scene, virtualCamera) + if (hasBlur) blurpass.render(gl, fbo1, fbo2) + gl.xr.enabled = currentXrEnabled + gl.shadowMap.autoUpdate = currentShadowAutoUpdate + parent.visible = true + gl.setRenderTarget(null) + }) - return ( - - ) - } -) + return ( + + ) + } + ) diff --git a/src/core/MeshTransmissionMaterial.tsx b/src/core/MeshTransmissionMaterial.tsx index 704934a4c..971f43630 100644 --- a/src/core/MeshTransmissionMaterial.tsx +++ b/src/core/MeshTransmissionMaterial.tsx @@ -376,7 +376,7 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial { export const MeshTransmissionMaterial: ForwardRefComponent< MeshTransmissionMaterialProps, JSX.IntrinsicElements['meshTransmissionMaterial'] -> = React.forwardRef( +> = /* @__PURE__ */ React.forwardRef( ( { buffer, diff --git a/src/core/MeshWobbleMaterial.tsx b/src/core/MeshWobbleMaterial.tsx index 0d2500e1c..e2062eb58 100644 --- a/src/core/MeshWobbleMaterial.tsx +++ b/src/core/MeshWobbleMaterial.tsx @@ -74,7 +74,7 @@ class WobbleMaterialImpl extends MeshStandardMaterial { } } -export const MeshWobbleMaterial: ForwardRefComponent = React.forwardRef( +export const MeshWobbleMaterial: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ speed = 1, ...props }: Props, ref) => { const [material] = React.useState(() => new WobbleMaterialImpl()) useFrame((state) => material && (material.time = state.clock.getElapsedTime() * speed)) diff --git a/src/core/MotionPathControls.tsx b/src/core/MotionPathControls.tsx index fe77a61a5..a15283ee9 100644 --- a/src/core/MotionPathControls.tsx +++ b/src/core/MotionPathControls.tsx @@ -49,7 +49,7 @@ type MotionState = { const isObject3DRef = (ref: any): ref is React.MutableRefObject => ref?.current instanceof THREE.Object3D -const context = React.createContext(null!) +const context = /* @__PURE__ */ React.createContext(null!) export function useMotion() { return React.useContext(context) as MotionState @@ -76,7 +76,7 @@ function Debug({ points = 50 }: { points?: number }) { ) } -export const MotionPathControls = React.forwardRef( +export const MotionPathControls = /* @__PURE__ */ React.forwardRef( ( { children, diff --git a/src/core/OrbitControls.tsx b/src/core/OrbitControls.tsx index 82e5643e6..c680c5411 100644 --- a/src/core/OrbitControls.tsx +++ b/src/core/OrbitControls.tsx @@ -27,84 +27,82 @@ export type OrbitControlsProps = Omit< 'ref' > -export const OrbitControls: ForwardRefComponent = React.forwardRef< - OrbitControlsImpl, - OrbitControlsProps ->( - ( - { - makeDefault, - camera, - regress, - domElement, - enableDamping = true, - keyEvents = false, - onChange, - onStart, - onEnd, - ...restProps - }, - ref - ) => { - const invalidate = useThree((state) => state.invalidate) - const defaultCamera = useThree((state) => state.camera) - const gl = useThree((state) => state.gl) - const events = useThree((state) => state.events) as EventManager - const setEvents = useThree((state) => state.setEvents) - const set = useThree((state) => state.set) - const get = useThree((state) => state.get) - const performance = useThree((state) => state.performance) - const explCamera = (camera || defaultCamera) as THREE.OrthographicCamera | THREE.PerspectiveCamera - const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement - const controls = React.useMemo(() => new OrbitControlsImpl(explCamera), [explCamera]) +export const OrbitControls: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ( + { + makeDefault, + camera, + regress, + domElement, + enableDamping = true, + keyEvents = false, + onChange, + onStart, + onEnd, + ...restProps + }, + ref + ) => { + const invalidate = useThree((state) => state.invalidate) + const defaultCamera = useThree((state) => state.camera) + const gl = useThree((state) => state.gl) + const events = useThree((state) => state.events) as EventManager + const setEvents = useThree((state) => state.setEvents) + const set = useThree((state) => state.set) + const get = useThree((state) => state.get) + const performance = useThree((state) => state.performance) + const explCamera = (camera || defaultCamera) as THREE.OrthographicCamera | THREE.PerspectiveCamera + const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement + const controls = React.useMemo(() => new OrbitControlsImpl(explCamera), [explCamera]) - useFrame(() => { - if (controls.enabled) controls.update() - }, -1) + useFrame(() => { + if (controls.enabled) controls.update() + }, -1) - React.useEffect(() => { - if (keyEvents) { - controls.connect(keyEvents === true ? explDomElement : keyEvents) - } + React.useEffect(() => { + if (keyEvents) { + controls.connect(keyEvents === true ? explDomElement : keyEvents) + } - controls.connect(explDomElement) - return () => void controls.dispose() - }, [keyEvents, explDomElement, regress, controls, invalidate]) + controls.connect(explDomElement) + return () => void controls.dispose() + }, [keyEvents, explDomElement, regress, controls, invalidate]) - React.useEffect(() => { - const callback = (e: OrbitControlsChangeEvent) => { - invalidate() - if (regress) performance.regress() - if (onChange) onChange(e) - } + React.useEffect(() => { + const callback = (e: OrbitControlsChangeEvent) => { + invalidate() + if (regress) performance.regress() + if (onChange) onChange(e) + } - const onStartCb = (e: Event) => { - if (onStart) onStart(e) - } + const onStartCb = (e: Event) => { + if (onStart) onStart(e) + } - const onEndCb = (e: Event) => { - if (onEnd) onEnd(e) - } + const onEndCb = (e: Event) => { + if (onEnd) onEnd(e) + } - controls.addEventListener('change', callback) - controls.addEventListener('start', onStartCb) - controls.addEventListener('end', onEndCb) + controls.addEventListener('change', callback) + controls.addEventListener('start', onStartCb) + controls.addEventListener('end', onEndCb) - return () => { - controls.removeEventListener('start', onStartCb) - controls.removeEventListener('end', onEndCb) - controls.removeEventListener('change', callback) - } - }, [onChange, onStart, onEnd, controls, invalidate, setEvents]) + return () => { + controls.removeEventListener('start', onStartCb) + controls.removeEventListener('end', onEndCb) + controls.removeEventListener('change', callback) + } + }, [onChange, onStart, onEnd, controls, invalidate, setEvents]) - React.useEffect(() => { - if (makeDefault) { - const old = get().controls - set({ controls }) - return () => set({ controls: old }) - } - }, [makeDefault, controls]) + React.useEffect(() => { + if (makeDefault) { + const old = get().controls + set({ controls }) + return () => set({ controls: old }) + } + }, [makeDefault, controls]) - return - } -) + return + } + ) diff --git a/src/core/OrthographicCamera.tsx b/src/core/OrthographicCamera.tsx index 634b0dd08..1844d79be 100644 --- a/src/core/OrthographicCamera.tsx +++ b/src/core/OrthographicCamera.tsx @@ -23,7 +23,7 @@ type Props = Omit & { envMap?: THREE.Texture } -export const OrthographicCamera: ForwardRefComponent = React.forwardRef( +export const OrthographicCamera: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ envMap, resolution = 256, frames = Infinity, children, makeDefault, ...props }: Props, ref) => { const set = useThree(({ set }) => set) const camera = useThree(({ camera }) => camera) diff --git a/src/core/Outlines.tsx b/src/core/Outlines.tsx index 53efe3e58..029c6cf2b 100644 --- a/src/core/Outlines.tsx +++ b/src/core/Outlines.tsx @@ -3,9 +3,16 @@ import * as React from 'react' import { shaderMaterial } from './shaderMaterial' import { extend, applyProps, ReactThreeFiber, useThree } from '@react-three/fiber' import { toCreasedNormals } from 'three-stdlib' +import { version } from '../helpers/constants' -const OutlinesMaterial = shaderMaterial( - { screenspace: false, color: new THREE.Color('black'), opacity: 1, thickness: 0.05, size: new THREE.Vector2() }, +const OutlinesMaterial = /* @__PURE__ */ shaderMaterial( + { + screenspace: false, + color: /* @__PURE__ */ new THREE.Color('black'), + opacity: 1, + thickness: 0.05, + size: /* @__PURE__ */ new THREE.Vector2(), + }, `#include #include #include @@ -46,7 +53,7 @@ const OutlinesMaterial = shaderMaterial( void main(){ gl_FragColor = vec4(color, opacity); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }` ) diff --git a/src/core/PerformanceMonitor.tsx b/src/core/PerformanceMonitor.tsx index 9b87a20e8..1e49a29f7 100644 --- a/src/core/PerformanceMonitor.tsx +++ b/src/core/PerformanceMonitor.tsx @@ -54,7 +54,7 @@ type PerformanceMonitorProps = { children?: React.ReactNode } -const context = createContext(null!) +const context = /* @__PURE__ */ createContext(null!) export function PerformanceMonitor({ iterations = 10, diff --git a/src/core/PerspectiveCamera.tsx b/src/core/PerspectiveCamera.tsx index dee24a757..0cedd5f62 100644 --- a/src/core/PerspectiveCamera.tsx +++ b/src/core/PerspectiveCamera.tsx @@ -23,7 +23,7 @@ type Props = Omit & { envMap?: THREE.Texture } -export const PerspectiveCamera: ForwardRefComponent = React.forwardRef( +export const PerspectiveCamera: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ envMap, resolution = 256, frames = Infinity, makeDefault, children, ...props }: Props, ref) => { const set = useThree(({ set }) => set) const camera = useThree(({ camera }) => camera) diff --git a/src/core/PointMaterial.tsx b/src/core/PointMaterial.tsx index 956614c25..083d5faf0 100644 --- a/src/core/PointMaterial.tsx +++ b/src/core/PointMaterial.tsx @@ -2,6 +2,7 @@ import * as THREE from 'three' import * as React from 'react' import { PrimitiveProps } from '@react-three/fiber' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' type PointMaterialType = JSX.IntrinsicElements['pointsMaterial'] @@ -13,7 +14,7 @@ declare global { } } -const opaque_fragment = parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'opaque_fragment' : 'output_fragment' +const opaque_fragment = version >= 154 ? 'opaque_fragment' : 'output_fragment' export class PointMaterialImpl extends THREE.PointsMaterial { constructor(props) { @@ -34,7 +35,7 @@ export class PointMaterialImpl extends THREE.PointsMaterial { float mask = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r); gl_FragColor = vec4(gl_FragColor.rgb, mask * gl_FragColor.a ); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> ` ) } @@ -44,7 +45,7 @@ export class PointMaterialImpl extends THREE.PointsMaterial { export const PointMaterial: ForwardRefComponent< Omit, PointMaterialImpl -> = React.forwardRef>((props, ref) => { +> = /* @__PURE__ */ React.forwardRef>((props, ref) => { const [material] = React.useState(() => new PointMaterialImpl(null)) return }) diff --git a/src/core/PointerLockControls.tsx b/src/core/PointerLockControls.tsx index 1695a3e2d..5666c76d9 100644 --- a/src/core/PointerLockControls.tsx +++ b/src/core/PointerLockControls.tsx @@ -20,7 +20,7 @@ export type PointerLockControlsProps = ReactThreeFiber.Object3DNode< } export const PointerLockControls: ForwardRefComponent = - React.forwardRef( + /* @__PURE__ */ React.forwardRef( ({ domElement, selector, onChange, onLock, onUnlock, enabled = true, makeDefault, ...props }, ref) => { const { camera, ...rest } = props const setEvents = useThree((state) => state.setEvents) diff --git a/src/core/Points.tsx b/src/core/Points.tsx index b293d659a..5e217d0e7 100644 --- a/src/core/Points.tsx +++ b/src/core/Points.tsx @@ -22,10 +22,10 @@ type PointsInstancesProps = JSX.IntrinsicElements['points'] & { limit?: number } -const _inverseMatrix = /*@__PURE__*/ new THREE.Matrix4() -const _ray = /*@__PURE__*/ new THREE.Ray() -const _sphere = /*@__PURE__*/ new THREE.Sphere() -const _position = /*@__PURE__*/ new THREE.Vector3() +const _inverseMatrix = /* @__PURE__ */ new THREE.Matrix4() +const _ray = /* @__PURE__ */ new THREE.Ray() +const _sphere = /* @__PURE__ */ new THREE.Sphere() +const _position = /* @__PURE__ */ new THREE.Vector3() export class PositionPoint extends THREE.Group { size: number @@ -82,14 +82,14 @@ export class PositionPoint extends THREE.Group { } let i, positionRef -const context = /*@__PURE__*/ React.createContext(null!) -const parentMatrix = /*@__PURE__*/ new THREE.Matrix4() -const position = /*@__PURE__*/ new THREE.Vector3() +const context = /* @__PURE__ */ React.createContext(null!) +const parentMatrix = /* @__PURE__ */ new THREE.Matrix4() +const position = /* @__PURE__ */ new THREE.Vector3() /** * Instance implementation, relies on react + context to update the attributes based on the children of this component */ -const PointsInstances: ForwardRefComponent = React.forwardRef< +const PointsInstances: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< THREE.Points, PointsInstancesProps >(({ children, range, limit = 1000, ...props }, ref) => { @@ -173,8 +173,8 @@ const PointsInstances: ForwardRefComponent = ) }) -export const Point: ForwardRefComponent = React.forwardRef( - ({ children, ...props }: JSX.IntrinsicElements['positionPoint'], ref) => { +export const Point: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef(({ children, ...props }: JSX.IntrinsicElements['positionPoint'], ref) => { React.useMemo(() => extend({ PositionPoint }), []) const group = React.useRef() const { subscribe, getParent } = React.useContext(context) @@ -184,8 +184,7 @@ export const Point: ForwardRefComponent ) - } -) + }) /** * Buffer implementation, relies on complete buffers of the correct number, leaves it to the user to update them @@ -199,7 +198,7 @@ type PointsBuffersProps = JSX.IntrinsicElements['points'] & { stride?: 2 | 3 } -export const PointsBuffer: ForwardRefComponent = React.forwardRef< +export const PointsBuffer: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< THREE.Points, PointsBuffersProps >(({ children, positions, colors, sizes, stride = 3, ...props }, forwardedRef) => { @@ -246,11 +245,9 @@ export const PointsBuffer: ForwardRefComponent ) }) -export const Points: ForwardRefComponent = React.forwardRef< - THREE.Points, - PointsBuffersProps | PointsInstancesProps ->((props, forwardedRef) => { - if ((props as PointsBuffersProps).positions instanceof Float32Array) { - return - } else return -}) +export const Points: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef((props, forwardedRef) => { + if ((props as PointsBuffersProps).positions instanceof Float32Array) { + return + } else return + }) diff --git a/src/core/PositionalAudio.tsx b/src/core/PositionalAudio.tsx index 709912cf6..659806b72 100644 --- a/src/core/PositionalAudio.tsx +++ b/src/core/PositionalAudio.tsx @@ -10,7 +10,7 @@ type Props = JSX.IntrinsicElements['positionalAudio'] & { loop?: boolean } -export const PositionalAudio: ForwardRefComponent = React.forwardRef( +export const PositionalAudio: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ url, distance = 1, loop = true, autoplay, ...props }: Props, ref) => { const sound = React.useRef() const camera = useThree(({ camera }) => camera) diff --git a/src/core/QuadraticBezierLine.tsx b/src/core/QuadraticBezierLine.tsx index 522cba2dd..b15440068 100644 --- a/src/core/QuadraticBezierLine.tsx +++ b/src/core/QuadraticBezierLine.tsx @@ -21,45 +21,44 @@ export type Line2Props = Object3DNode & { ) => void } -const v = new Vector3() -export const QuadraticBezierLine: ForwardRefComponent = React.forwardRef( - function QuadraticBezierLine({ start = [0, 0, 0], end = [0, 0, 0], mid, segments = 20, ...rest }, forwardref) { - const ref = React.useRef(null!) - const [curve] = React.useState( - () => new QuadraticBezierCurve3(undefined as any, undefined as any, undefined as any) - ) - const getPoints = React.useCallback((start, end, mid, segments = 20) => { - if (start instanceof Vector3) curve.v0.copy(start) - else curve.v0.set(...(start as [number, number, number])) - if (end instanceof Vector3) curve.v2.copy(end) - else curve.v2.set(...(end as [number, number, number])) - if (mid instanceof Vector3) { - curve.v1.copy(mid) - } else if (Array.isArray(mid)) { - curve.v1.set(...(mid as [number, number, number])) - } else { - curve.v1.copy( - curve.v0 - .clone() - .add(curve.v2.clone().sub(curve.v0)) - .add(v.set(0, curve.v0.y - curve.v2.y, 0)) - ) - } - return curve.getPoints(segments) - }, []) +const v = /* @__PURE__ */ new Vector3() +export const QuadraticBezierLine: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + Line2Props, + Props +>(function QuadraticBezierLine({ start = [0, 0, 0], end = [0, 0, 0], mid, segments = 20, ...rest }, forwardref) { + const ref = React.useRef(null!) + const [curve] = React.useState(() => new QuadraticBezierCurve3(undefined as any, undefined as any, undefined as any)) + const getPoints = React.useCallback((start, end, mid, segments = 20) => { + if (start instanceof Vector3) curve.v0.copy(start) + else curve.v0.set(...(start as [number, number, number])) + if (end instanceof Vector3) curve.v2.copy(end) + else curve.v2.set(...(end as [number, number, number])) + if (mid instanceof Vector3) { + curve.v1.copy(mid) + } else if (Array.isArray(mid)) { + curve.v1.set(...(mid as [number, number, number])) + } else { + curve.v1.copy( + curve.v0 + .clone() + .add(curve.v2.clone().sub(curve.v0)) + .add(v.set(0, curve.v0.y - curve.v2.y, 0)) + ) + } + return curve.getPoints(segments) + }, []) - React.useLayoutEffect(() => { - ref.current.setPoints = ( - start: Vector3 | [number, number, number], - end: Vector3 | [number, number, number], - mid: Vector3 | [number, number, number] - ) => { - const points = getPoints(start, end, mid) - if (ref.current.geometry) ref.current.geometry.setPositions(points.map((p) => p.toArray()).flat()) - } - }, []) + React.useLayoutEffect(() => { + ref.current.setPoints = ( + start: Vector3 | [number, number, number], + end: Vector3 | [number, number, number], + mid: Vector3 | [number, number, number] + ) => { + const points = getPoints(start, end, mid) + if (ref.current.geometry) ref.current.geometry.setPositions(points.map((p) => p.toArray()).flat()) + } + }, []) - const points = React.useMemo(() => getPoints(start, end, mid, segments), [start, end, mid, segments]) - return - } -) + const points = React.useMemo(() => getPoints(start, end, mid, segments), [start, end, mid, segments]) + return +}) diff --git a/src/core/Reflector.tsx b/src/core/Reflector.tsx index 60cd60aa2..67f8c3fcc 100644 --- a/src/core/Reflector.tsx +++ b/src/core/Reflector.tsx @@ -52,12 +52,13 @@ declare global { } } -extend({ MeshReflectorMaterial }) - /** * @deprecated Use MeshReflectorMaterial instead */ -export const Reflector: ForwardRefComponent = React.forwardRef( +export const Reflector: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + Mesh, + ReflectorProps +>( ( { mixBlur = 0, @@ -79,6 +80,8 @@ export const Reflector: ForwardRefComponent = React.forwar }, ref ) => { + extend({ MeshReflectorMaterial }) + React.useEffect(() => { console.warn( 'Reflector has been deprecated and will be removed next major. Replace it with !' diff --git a/src/core/RenderCubeTexture.tsx b/src/core/RenderCubeTexture.tsx index 0a37254a8..2bebd43a3 100644 --- a/src/core/RenderCubeTexture.tsx +++ b/src/core/RenderCubeTexture.tsx @@ -40,83 +40,84 @@ export type RenderCubeTextureApi = { camera: THREE.CubeCamera } -export const RenderCubeTexture: ForwardRefComponent = React.forwardRef( - ( - { - children, - compute, - renderPriority = -1, - eventPriority = 0, - frames = Infinity, - stencilBuffer = false, - depthBuffer = true, - generateMipmaps = false, - resolution = 896, - near = 0.1, - far = 1000, - flip = false, - position, - rotation, - scale, - quaternion, - matrix, - matrixAutoUpdate, - ...props - }, - forwardRef - ) => { - const { size, viewport } = useThree() +export const RenderCubeTexture: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ( + { + children, + compute, + renderPriority = -1, + eventPriority = 0, + frames = Infinity, + stencilBuffer = false, + depthBuffer = true, + generateMipmaps = false, + resolution = 896, + near = 0.1, + far = 1000, + flip = false, + position, + rotation, + scale, + quaternion, + matrix, + matrixAutoUpdate, + ...props + }, + forwardRef + ) => { + const { size, viewport } = useThree() - const camera = React.useRef(null!) - const fbo = React.useMemo(() => { - const fbo = new THREE.WebGLCubeRenderTarget( - Math.max((resolution || size.width) * viewport.dpr, (resolution || size.height) * viewport.dpr), - { - stencilBuffer, - depthBuffer, - generateMipmaps, - } - ) - fbo.texture.isRenderTargetTexture = !flip - fbo.texture.flipY = true - fbo.texture.type = THREE.HalfFloatType - return fbo - }, [resolution, flip]) + const camera = React.useRef(null!) + const fbo = React.useMemo(() => { + const fbo = new THREE.WebGLCubeRenderTarget( + Math.max((resolution || size.width) * viewport.dpr, (resolution || size.height) * viewport.dpr), + { + stencilBuffer, + depthBuffer, + generateMipmaps, + } + ) + fbo.texture.isRenderTargetTexture = !flip + fbo.texture.flipY = true + fbo.texture.type = THREE.HalfFloatType + return fbo + }, [resolution, flip]) - React.useEffect(() => { - return () => fbo.dispose() - }, [fbo]) + React.useEffect(() => { + return () => fbo.dispose() + }, [fbo]) - const [vScene] = React.useState(() => new THREE.Scene()) + const [vScene] = React.useState(() => new THREE.Scene()) - React.useImperativeHandle(forwardRef, () => ({ scene: vScene, fbo, camera: camera.current }), [fbo]) + React.useImperativeHandle(forwardRef, () => ({ scene: vScene, fbo, camera: camera.current }), [fbo]) - return ( - <> - {createPortal( - - {children} - {/* Without an element that receives pointer events state.pointer will always be 0/0 */} - null} /> - , - vScene, - { events: { compute, priority: eventPriority } } - )} - - - - ) - } -) + return ( + <> + {createPortal( + + {children} + {/* Without an element that receives pointer events state.pointer will always be 0/0 */} + null} /> + , + vScene, + { events: { compute, priority: eventPriority } } + )} + + + + ) + } + ) // The container component has to be separate, it can not be inlined because "useFrame(state" when run inside createPortal will return // the portals own state which includes user-land overrides (custom cameras etc), but if it is executed in 's render function diff --git a/src/core/RenderTexture.tsx b/src/core/RenderTexture.tsx index 8d5c9ae1b..8d7f7384c 100644 --- a/src/core/RenderTexture.tsx +++ b/src/core/RenderTexture.tsx @@ -29,7 +29,7 @@ type Props = JSX.IntrinsicElements['texture'] & { children: React.ReactNode } -export const RenderTexture: ForwardRefComponent = React.forwardRef( +export const RenderTexture: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { children, diff --git a/src/core/Resize.tsx b/src/core/Resize.tsx index 67e2c8c32..4f11343e7 100644 --- a/src/core/Resize.tsx +++ b/src/core/Resize.tsx @@ -14,7 +14,7 @@ export type ResizeProps = JSX.IntrinsicElements['group'] & { precise?: boolean } -export const Resize = React.forwardRef( +export const Resize = /* @__PURE__ */ React.forwardRef( ({ children, width, height, depth, box3, precise = true, ...props }, fRef) => { const ref = React.useRef(null!) const outer = React.useRef(null!) diff --git a/src/core/RoundedBox.tsx b/src/core/RoundedBox.tsx index e662b120a..3c688f7e6 100644 --- a/src/core/RoundedBox.tsx +++ b/src/core/RoundedBox.tsx @@ -24,45 +24,47 @@ type Props = { creaseAngle?: number } & Omit -export const RoundedBox: ForwardRefComponent = React.forwardRef(function RoundedBox( - { - args: [width = 1, height = 1, depth = 1] = [], - radius = 0.05, - steps = 1, - smoothness = 4, - bevelSegments = 4, - creaseAngle = 0.4, - children, - ...rest - }, - ref -) { - const shape = React.useMemo(() => createShape(width, height, radius), [width, height, radius]) - const params = React.useMemo( - () => ({ - depth: depth - radius * 2, - bevelEnabled: true, - bevelSegments: bevelSegments * 2, - steps, - bevelSize: radius - eps, - bevelThickness: radius, - curveSegments: smoothness, - }), - [depth, radius, smoothness] - ) - const geomRef = React.useRef(null!) +export const RoundedBox: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( + function RoundedBox( + { + args: [width = 1, height = 1, depth = 1] = [], + radius = 0.05, + steps = 1, + smoothness = 4, + bevelSegments = 4, + creaseAngle = 0.4, + children, + ...rest + }, + ref + ) { + const shape = React.useMemo(() => createShape(width, height, radius), [width, height, radius]) + const params = React.useMemo( + () => ({ + depth: depth - radius * 2, + bevelEnabled: true, + bevelSegments: bevelSegments * 2, + steps, + bevelSize: radius - eps, + bevelThickness: radius, + curveSegments: smoothness, + }), + [depth, radius, smoothness] + ) + const geomRef = React.useRef(null!) - React.useLayoutEffect(() => { - if (geomRef.current) { - geomRef.current.center() - toCreasedNormals(geomRef.current, creaseAngle) - } - }, [shape, params]) + React.useLayoutEffect(() => { + if (geomRef.current) { + geomRef.current.center() + toCreasedNormals(geomRef.current, creaseAngle) + } + }, [shape, params]) - return ( - - - {children} - - ) -}) + return ( + + + {children} + + ) + } +) diff --git a/src/core/ScreenQuad.tsx b/src/core/ScreenQuad.tsx index 1bff5f645..78f481531 100644 --- a/src/core/ScreenQuad.tsx +++ b/src/core/ScreenQuad.tsx @@ -15,7 +15,7 @@ function createScreenQuadGeometry() { type Props = Omit -export const ScreenQuad: ForwardRefComponent = React.forwardRef( +export const ScreenQuad: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( function ScreenQuad({ children, ...restProps }, ref) { const geometry = React.useMemo(createScreenQuadGeometry, []) diff --git a/src/core/ScreenSpace.tsx b/src/core/ScreenSpace.tsx index 66b98a02e..b95996d66 100644 --- a/src/core/ScreenSpace.tsx +++ b/src/core/ScreenSpace.tsx @@ -8,18 +8,19 @@ export type ScreenSpaceProps = { depth?: number } & JSX.IntrinsicElements['group'] -export const ScreenSpace: ForwardRefComponent = React.forwardRef( - ({ children, depth = -1, ...rest }, ref) => { - const localRef = React.useRef(null!) +export const ScreenSpace: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + Group, + ScreenSpaceProps +>(({ children, depth = -1, ...rest }, ref) => { + const localRef = React.useRef(null!) - useFrame(({ camera }) => { - localRef.current.quaternion.copy(camera.quaternion) - localRef.current.position.copy(camera.position) - }) - return ( - - {children} - - ) - } -) + useFrame(({ camera }) => { + localRef.current.quaternion.copy(camera.quaternion) + localRef.current.position.copy(camera.position) + }) + return ( + + {children} + + ) +}) diff --git a/src/core/Segments.tsx b/src/core/Segments.tsx index 3ec7d21ce..ba16ed7c9 100644 --- a/src/core/Segments.tsx +++ b/src/core/Segments.tsx @@ -22,9 +22,9 @@ type SegmentProps = Omit(null!) +const context = /* @__PURE__ */ React.createContext(null!) -const Segments: ForwardRefComponent = React.forwardRef( +const Segments: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( (props, forwardedRef) => { React.useMemo(() => extend({ SegmentObject }), []) @@ -114,16 +114,15 @@ export class SegmentObject { const normPos = (pos: SegmentProps['start']): SegmentObject['start'] => pos instanceof THREE.Vector3 ? pos : new THREE.Vector3(...(typeof pos === 'number' ? [pos, pos, pos] : pos)) -const Segment: ForwardRefComponent = React.forwardRef( - ({ color, start, end }, forwardedRef) => { - const api = React.useContext(context) - if (!api) throw 'Segment must used inside Segments component.' - const ref = React.useRef(null) - React.useLayoutEffect(() => api.subscribe(ref), []) - return ( - - ) - } -) +const Segment: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< + SegmentObject, + SegmentProps +>(({ color, start, end }, forwardedRef) => { + const api = React.useContext(context) + if (!api) throw 'Segment must used inside Segments component.' + const ref = React.useRef(null) + React.useLayoutEffect(() => api.subscribe(ref), []) + return +}) export { Segments, Segment } diff --git a/src/core/Shadow.tsx b/src/core/Shadow.tsx index 668530d87..81e71bf18 100644 --- a/src/core/Shadow.tsx +++ b/src/core/Shadow.tsx @@ -12,7 +12,7 @@ type Props = JSX.IntrinsicElements['mesh'] & { export type ShadowType = Mesh -export const Shadow: ForwardRefComponent = React.forwardRef( +export const Shadow: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { fog = false, renderOrder, depthWrite = false, colorStop = 0.0, color = 'black', opacity = 0.5, ...props }: Props, ref diff --git a/src/core/Sky.tsx b/src/core/Sky.tsx index 3e14a9bcc..677e0aed0 100644 --- a/src/core/Sky.tsx +++ b/src/core/Sky.tsx @@ -26,7 +26,7 @@ export function calcPosFromAngles(inclination: number, azimuth: number, vector: return vector } -export const Sky: ForwardRefComponent = React.forwardRef( +export const Sky: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { inclination = 0.6, diff --git a/src/core/Sparkles.tsx b/src/core/Sparkles.tsx index b68b965ec..301d5fc8d 100644 --- a/src/core/Sparkles.tsx +++ b/src/core/Sparkles.tsx @@ -3,6 +3,7 @@ import * as THREE from 'three' import { PointsProps, useThree, useFrame, extend, Node } from '@react-three/fiber' import { shaderMaterial } from './shaderMaterial' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' interface Props { /** Number of particles (default: 100) */ @@ -21,7 +22,7 @@ interface Props { noise?: number | [number, number, number] | THREE.Vector3 | Float32Array } -const SparklesImplMaterial = shaderMaterial( +const SparklesImplMaterial = /* @__PURE__ */ shaderMaterial( { time: 0, pixelRatio: 1 }, ` uniform float pixelRatio; uniform float time; @@ -52,7 +53,7 @@ const SparklesImplMaterial = shaderMaterial( float strength = 0.05 / distanceToCenter - 0.1; gl_FragColor = vec4(vColor, strength * vOpacity); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }` ) @@ -100,7 +101,7 @@ function usePropAsIsOrAsAttribute( }, [prop]) } -export const Sparkles: ForwardRefComponent = React.forwardRef< +export const Sparkles: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< THREE.Points, Props & PointsProps >(({ noise = 1, count = 100, speed = 1, opacity = 1, scale = 1, size, color, children, ...props }, forwardRef) => { diff --git a/src/core/Stars.tsx b/src/core/Stars.tsx index a32f4c304..9cfd2bd46 100644 --- a/src/core/Stars.tsx +++ b/src/core/Stars.tsx @@ -4,6 +4,7 @@ import * as React from 'react' import { ReactThreeFiber, useFrame } from '@react-three/fiber' import { Points, Vector3, Spherical, Color, AdditiveBlending, ShaderMaterial } from 'three' import { ForwardRefComponent } from '../helpers/ts-utils' +import { version } from '../helpers/constants' type Props = { radius?: number @@ -42,7 +43,7 @@ class StarfieldMaterial extends ShaderMaterial { gl_FragColor = vec4(vColor, opacity); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }`, }) } @@ -60,7 +61,7 @@ const genStar = (r: number) => { return new Vector3().setFromSpherical(new Spherical(r, Math.acos(1 - Math.random() * 2), Math.random() * 2 * Math.PI)) } -export const Stars: ForwardRefComponent = React.forwardRef( +export const Stars: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ radius = 100, depth = 50, count = 5000, saturation = 0, factor = 4, fade = false, speed = 1 }: Props, ref) => { const material = React.useRef() const [position, color, size] = React.useMemo(() => { diff --git a/src/core/Svg.tsx b/src/core/Svg.tsx index f9a9af762..983298161 100644 --- a/src/core/Svg.tsx +++ b/src/core/Svg.tsx @@ -16,67 +16,69 @@ export interface SvgProps extends Omit { strokeMeshProps?: MeshProps } -export const Svg: ForwardRefComponent = forwardRef(function R3FSvg( - { src, skipFill, skipStrokes, fillMaterial, strokeMaterial, fillMeshProps, strokeMeshProps, ...props }, - ref -) { - const svg = useLoader(SVGLoader, !src.startsWith(' = /* @__PURE__ */ forwardRef( + function R3FSvg( + { src, skipFill, skipStrokes, fillMaterial, strokeMaterial, fillMeshProps, strokeMeshProps, ...props }, + ref + ) { + const svg = useLoader(SVGLoader, !src.startsWith(' - skipStrokes - ? [] - : svg.paths.map((path) => - path.userData?.style.stroke === undefined || path.userData.style.stroke === 'none' - ? null - : path.subPaths.map((subPath) => SVGLoader.pointsToStroke(subPath.getPoints(), path.userData!.style)) - ), - [svg, skipStrokes] - ) + const strokeGeometries = useMemo( + () => + skipStrokes + ? [] + : svg.paths.map((path) => + path.userData?.style.stroke === undefined || path.userData.style.stroke === 'none' + ? null + : path.subPaths.map((subPath) => SVGLoader.pointsToStroke(subPath.getPoints(), path.userData!.style)) + ), + [svg, skipStrokes] + ) - useEffect(() => { - return () => strokeGeometries.forEach((group) => group && group.map((g) => g.dispose())) - }, [strokeGeometries]) + useEffect(() => { + return () => strokeGeometries.forEach((group) => group && group.map((g) => g.dispose())) + }, [strokeGeometries]) - return ( - - - {svg.paths.map((path, p) => ( - - {!skipFill && - path.userData?.style.fill !== undefined && - path.userData.style.fill !== 'none' && - SVGLoader.createShapes(path).map((shape, s) => ( - - - - - ))} - {!skipStrokes && - path.userData?.style.stroke !== undefined && - path.userData.style.stroke !== 'none' && - path.subPaths.map((_subPath, s) => ( - - - - ))} - - ))} + return ( + + + {svg.paths.map((path, p) => ( + + {!skipFill && + path.userData?.style.fill !== undefined && + path.userData.style.fill !== 'none' && + SVGLoader.createShapes(path).map((shape, s) => ( + + + + + ))} + {!skipStrokes && + path.userData?.style.stroke !== undefined && + path.userData.style.stroke !== 'none' && + path.subPaths.map((_subPath, s) => ( + + + + ))} + + ))} + - - ) -}) + ) + } +) diff --git a/src/core/Text.tsx b/src/core/Text.tsx index 48ef07c21..e7669d13c 100644 --- a/src/core/Text.tsx +++ b/src/core/Text.tsx @@ -39,7 +39,7 @@ type Props = JSX.IntrinsicElements['mesh'] & { } // eslint-disable-next-line prettier/prettier -export const Text: ForwardRefComponent = React.forwardRef( +export const Text: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { sdfGlyphSize = 64, diff --git a/src/core/Text3D.tsx b/src/core/Text3D.tsx index 7842e345c..1aa809b9a 100644 --- a/src/core/Text3D.tsx +++ b/src/core/Text3D.tsx @@ -36,7 +36,7 @@ const getTextFromChildren = (children) => { export const Text3D: ForwardRefComponent< React.PropsWithChildren, THREE.Mesh -> = React.forwardRef< +> = /* @__PURE__ */ React.forwardRef< THREE.Mesh, React.PropsWithChildren >( diff --git a/src/core/TrackballControls.tsx b/src/core/TrackballControls.tsx index 6e90351e2..377c30659 100644 --- a/src/core/TrackballControls.tsx +++ b/src/core/TrackballControls.tsx @@ -18,51 +18,54 @@ export type TrackballControlsProps = ReactThreeFiber.Overwrite< } > -export const TrackballControls: ForwardRefComponent = React.forwardRef< - TrackballControlsImpl, - TrackballControlsProps ->(({ makeDefault, camera, domElement, regress, onChange, onStart, onEnd, ...restProps }, ref) => { - const { invalidate, camera: defaultCamera, gl, events, set, get, performance, viewport } = useThree() - const explCamera = camera || defaultCamera - const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement - const controls = React.useMemo(() => new TrackballControlsImpl(explCamera as THREE.PerspectiveCamera), [explCamera]) +export const TrackballControls: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ({ makeDefault, camera, domElement, regress, onChange, onStart, onEnd, ...restProps }, ref) => { + const { invalidate, camera: defaultCamera, gl, events, set, get, performance, viewport } = useThree() + const explCamera = camera || defaultCamera + const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement + const controls = React.useMemo( + () => new TrackballControlsImpl(explCamera as THREE.PerspectiveCamera), + [explCamera] + ) - useFrame(() => { - if (controls.enabled) controls.update() - }, -1) + useFrame(() => { + if (controls.enabled) controls.update() + }, -1) - React.useEffect(() => { - controls.connect(explDomElement) - return () => void controls.dispose() - }, [explDomElement, regress, controls, invalidate]) + React.useEffect(() => { + controls.connect(explDomElement) + return () => void controls.dispose() + }, [explDomElement, regress, controls, invalidate]) - React.useEffect(() => { - const callback = (e: THREE.Event) => { - invalidate() - if (regress) performance.regress() - if (onChange) onChange(e) - } - controls.addEventListener('change', callback) - if (onStart) controls.addEventListener('start', onStart) - if (onEnd) controls.addEventListener('end', onEnd) - return () => { - if (onStart) controls.removeEventListener('start', onStart) - if (onEnd) controls.removeEventListener('end', onEnd) - controls.removeEventListener('change', callback) - } - }, [onChange, onStart, onEnd, controls, invalidate]) + React.useEffect(() => { + const callback = (e: THREE.Event) => { + invalidate() + if (regress) performance.regress() + if (onChange) onChange(e) + } + controls.addEventListener('change', callback) + if (onStart) controls.addEventListener('start', onStart) + if (onEnd) controls.addEventListener('end', onEnd) + return () => { + if (onStart) controls.removeEventListener('start', onStart) + if (onEnd) controls.removeEventListener('end', onEnd) + controls.removeEventListener('change', callback) + } + }, [onChange, onStart, onEnd, controls, invalidate]) - React.useEffect(() => { - controls.handleResize() - }, [viewport]) + React.useEffect(() => { + controls.handleResize() + }, [viewport]) - React.useEffect(() => { - if (makeDefault) { - const old = get().controls - set({ controls }) - return () => set({ controls: old }) - } - }, [makeDefault, controls]) + React.useEffect(() => { + if (makeDefault) { + const old = get().controls + set({ controls }) + return () => set({ controls: old }) + } + }, [makeDefault, controls]) - return -}) + return + } + ) diff --git a/src/core/Trail.tsx b/src/core/Trail.tsx index 8b3f178de..a131330cb 100644 --- a/src/core/Trail.tsx +++ b/src/core/Trail.tsx @@ -88,10 +88,10 @@ export function useTrail(target: Object3D, settings: Partial) { export type MeshLineGeometry = THREE.Mesh & MeshLineGeometryImpl -export const Trail: ForwardRefComponent, MeshLineGeometry> = React.forwardRef< - MeshLineGeometry, - React.PropsWithChildren ->((props, forwardRef) => { +export const Trail: ForwardRefComponent< + React.PropsWithChildren, + MeshLineGeometry +> = /* @__PURE__ */ React.forwardRef>((props, forwardRef) => { const { children } = props const { width, length, decay, local, stride, interval } = { ...defaults, diff --git a/src/core/TransformControls.tsx b/src/core/TransformControls.tsx index d44133d70..c1526aa34 100644 --- a/src/core/TransformControls.tsx +++ b/src/core/TransformControls.tsx @@ -34,108 +34,111 @@ export type TransformControlsProps = ReactThreeFiber.Object3DNode = React.forwardRef< - TransformControlsImpl, - TransformControlsProps ->(({ children, domElement, onChange, onMouseDown, onMouseUp, onObjectChange, object, makeDefault, ...props }, ref) => { - const transformOnlyPropNames = [ - 'enabled', - 'axis', - 'mode', - 'translationSnap', - 'rotationSnap', - 'scaleSnap', - 'space', - 'size', - 'showX', - 'showY', - 'showZ', - ] +export const TransformControls: ForwardRefComponent = + /* @__PURE__ */ React.forwardRef( + ( + { children, domElement, onChange, onMouseDown, onMouseUp, onObjectChange, object, makeDefault, ...props }, + ref + ) => { + const transformOnlyPropNames = [ + 'enabled', + 'axis', + 'mode', + 'translationSnap', + 'rotationSnap', + 'scaleSnap', + 'space', + 'size', + 'showX', + 'showY', + 'showZ', + ] - const { camera, ...rest } = props - const transformProps = pick(rest, transformOnlyPropNames) - const objectProps = omit(rest, transformOnlyPropNames) - // @ts-expect-error new in @react-three/fiber@7.0.5 - const defaultControls = useThree((state) => state.controls) as ControlsProto - const gl = useThree((state) => state.gl) - const events = useThree((state) => state.events) - const defaultCamera = useThree((state) => state.camera) - const invalidate = useThree((state) => state.invalidate) - const get = useThree((state) => state.get) - const set = useThree((state) => state.set) - const explCamera = camera || defaultCamera - const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement - const controls = React.useMemo( - () => new TransformControlsImpl(explCamera, explDomElement), - [explCamera, explDomElement] - ) - const group = React.useRef() + const { camera, ...rest } = props + const transformProps = pick(rest, transformOnlyPropNames) + const objectProps = omit(rest, transformOnlyPropNames) + // @ts-expect-error new in @react-three/fiber@7.0.5 + const defaultControls = useThree((state) => state.controls) as ControlsProto + const gl = useThree((state) => state.gl) + const events = useThree((state) => state.events) + const defaultCamera = useThree((state) => state.camera) + const invalidate = useThree((state) => state.invalidate) + const get = useThree((state) => state.get) + const set = useThree((state) => state.set) + const explCamera = camera || defaultCamera + const explDomElement = (domElement || events.connected || gl.domElement) as HTMLElement + const controls = React.useMemo( + () => new TransformControlsImpl(explCamera, explDomElement), + [explCamera, explDomElement] + ) + const group = React.useRef() - React.useLayoutEffect(() => { - if (object) { - controls.attach(object instanceof THREE.Object3D ? object : object.current) - } else if (group.current instanceof THREE.Object3D) { - controls.attach(group.current) - } + React.useLayoutEffect(() => { + if (object) { + controls.attach(object instanceof THREE.Object3D ? object : object.current) + } else if (group.current instanceof THREE.Object3D) { + controls.attach(group.current) + } - return () => void controls.detach() - }, [object, children, controls]) + return () => void controls.detach() + }, [object, children, controls]) - React.useEffect(() => { - if (defaultControls) { - const callback = (event) => (defaultControls.enabled = !event.value) - controls.addEventListener('dragging-changed', callback) - return () => controls.removeEventListener('dragging-changed', callback) - } - }, [controls, defaultControls]) + React.useEffect(() => { + if (defaultControls) { + const callback = (event) => (defaultControls.enabled = !event.value) + controls.addEventListener('dragging-changed', callback) + return () => controls.removeEventListener('dragging-changed', callback) + } + }, [controls, defaultControls]) - const onChangeRef = React.useRef<(e?: THREE.Event) => void>() - const onMouseDownRef = React.useRef<(e?: THREE.Event) => void>() - const onMouseUpRef = React.useRef<(e?: THREE.Event) => void>() - const onObjectChangeRef = React.useRef<(e?: THREE.Event) => void>() + const onChangeRef = React.useRef<(e?: THREE.Event) => void>() + const onMouseDownRef = React.useRef<(e?: THREE.Event) => void>() + const onMouseUpRef = React.useRef<(e?: THREE.Event) => void>() + const onObjectChangeRef = React.useRef<(e?: THREE.Event) => void>() - React.useLayoutEffect(() => void (onChangeRef.current = onChange), [onChange]) - React.useLayoutEffect(() => void (onMouseDownRef.current = onMouseDown), [onMouseDown]) - React.useLayoutEffect(() => void (onMouseUpRef.current = onMouseUp), [onMouseUp]) - React.useLayoutEffect(() => void (onObjectChangeRef.current = onObjectChange), [onObjectChange]) + React.useLayoutEffect(() => void (onChangeRef.current = onChange), [onChange]) + React.useLayoutEffect(() => void (onMouseDownRef.current = onMouseDown), [onMouseDown]) + React.useLayoutEffect(() => void (onMouseUpRef.current = onMouseUp), [onMouseUp]) + React.useLayoutEffect(() => void (onObjectChangeRef.current = onObjectChange), [onObjectChange]) - React.useEffect(() => { - const onChange = (e: THREE.Event) => { - invalidate() - onChangeRef.current?.(e) - } + React.useEffect(() => { + const onChange = (e: THREE.Event) => { + invalidate() + onChangeRef.current?.(e) + } - const onMouseDown = (e: THREE.Event) => onMouseDownRef.current?.(e) - const onMouseUp = (e: THREE.Event) => onMouseUpRef.current?.(e) - const onObjectChange = (e: THREE.Event) => onObjectChangeRef.current?.(e) + const onMouseDown = (e: THREE.Event) => onMouseDownRef.current?.(e) + const onMouseUp = (e: THREE.Event) => onMouseUpRef.current?.(e) + const onObjectChange = (e: THREE.Event) => onObjectChangeRef.current?.(e) - controls.addEventListener('change', onChange) - controls.addEventListener('mouseDown', onMouseDown) - controls.addEventListener('mouseUp', onMouseUp) - controls.addEventListener('objectChange', onObjectChange) + controls.addEventListener('change', onChange) + controls.addEventListener('mouseDown', onMouseDown) + controls.addEventListener('mouseUp', onMouseUp) + controls.addEventListener('objectChange', onObjectChange) - return () => { - controls.removeEventListener('change', onChange) - controls.removeEventListener('mouseDown', onMouseDown) - controls.removeEventListener('mouseUp', onMouseUp) - controls.removeEventListener('objectChange', onObjectChange) - } - }, [invalidate, controls]) + return () => { + controls.removeEventListener('change', onChange) + controls.removeEventListener('mouseDown', onMouseDown) + controls.removeEventListener('mouseUp', onMouseUp) + controls.removeEventListener('objectChange', onObjectChange) + } + }, [invalidate, controls]) - React.useEffect(() => { - if (makeDefault) { - const old = get().controls - set({ controls }) - return () => set({ controls: old }) - } - }, [makeDefault, controls]) + React.useEffect(() => { + if (makeDefault) { + const old = get().controls + set({ controls }) + return () => set({ controls: old }) + } + }, [makeDefault, controls]) - return controls ? ( - <> - - - {children} - - - ) : null -}) + return controls ? ( + <> + + + {children} + + + ) : null + } + ) diff --git a/src/core/Wireframe.tsx b/src/core/Wireframe.tsx index c51643181..30e011064 100644 --- a/src/core/Wireframe.tsx +++ b/src/core/Wireframe.tsx @@ -1,6 +1,6 @@ import * as React from 'react' import * as THREE from 'three' -import * as FIBER from '@react-three/fiber' +import { MaterialNode, extend } from '@react-three/fiber' import { WireframeMaterial, WireframeMaterialProps, @@ -12,13 +12,11 @@ import { declare global { namespace JSX { interface IntrinsicElements { - meshWireframeMaterial: FIBER.MaterialNode + meshWireframeMaterial: MaterialNode } } } -FIBER.extend({ MeshWireframeMaterial: WireframeMaterial }) - interface WireframeProps { geometry?: THREE.BufferGeometry | React.RefObject simplify?: boolean @@ -120,6 +118,7 @@ function WireframeWithCustomGeo({ simplify = false, ...props }: WireframeProps & WireframeMaterialProps) { + extend({ MeshWireframeMaterial: WireframeMaterial }) const [geometry, setGeometry] = React.useState(null!) React.useLayoutEffect(() => { diff --git a/src/core/meshBounds.tsx b/src/core/meshBounds.tsx index 4e882488a..185d4ecf4 100644 --- a/src/core/meshBounds.tsx +++ b/src/core/meshBounds.tsx @@ -1,9 +1,9 @@ import { Raycaster, Matrix4, Ray, Sphere, Vector3, Intersection } from 'three' -const _inverseMatrix = new Matrix4() -const _ray = new Ray() -const _sphere = new Sphere() -const _vA = new Vector3() +const _inverseMatrix = /* @__PURE__ */ new Matrix4() +const _ray = /* @__PURE__ */ new Ray() +const _sphere = /* @__PURE__ */ new Sphere() +const _vA = /* @__PURE__ */ new Vector3() export function meshBounds(raycaster: Raycaster, intersects: Intersection[]) { const geometry = this.geometry diff --git a/src/core/shapes.tsx b/src/core/shapes.tsx index 0bd8a2ad4..2a1bdb308 100644 --- a/src/core/shapes.tsx +++ b/src/core/shapes.tsx @@ -20,25 +20,25 @@ function create(type: string, effect?: (mesh: THREE.Mesh) => void): ForwardRe }) } -export const Box = create('box') -export const Circle = create('circle') -export const Cone = create('cone') -export const Cylinder = create('cylinder') -export const Sphere = create('sphere') -export const Plane = create('plane') -export const Tube = create('tube') -export const Torus = create('torus') -export const TorusKnot = create('torusKnot') -export const Tetrahedron = create('tetrahedron') -export const Ring = create('ring') -export const Polyhedron = create('polyhedron') -export const Icosahedron = create('icosahedron') -export const Octahedron = create('octahedron') -export const Dodecahedron = create('dodecahedron') -export const Extrude = create('extrude') -export const Lathe = create('lathe') -export const Capsule = create('capsule') -export const Shape = create('shape', ({ geometry }) => { +export const Box = /* @__PURE__ */ create('box') +export const Circle = /* @__PURE__ */ create('circle') +export const Cone = /* @__PURE__ */ create('cone') +export const Cylinder = /* @__PURE__ */ create('cylinder') +export const Sphere = /* @__PURE__ */ create('sphere') +export const Plane = /* @__PURE__ */ create('plane') +export const Tube = /* @__PURE__ */ create('tube') +export const Torus = /* @__PURE__ */ create('torus') +export const TorusKnot = /* @__PURE__ */ create('torusKnot') +export const Tetrahedron = /* @__PURE__ */ create('tetrahedron') +export const Ring = /* @__PURE__ */ create('ring') +export const Polyhedron = /* @__PURE__ */ create('polyhedron') +export const Icosahedron = /* @__PURE__ */ create('icosahedron') +export const Octahedron = /* @__PURE__ */ create('octahedron') +export const Dodecahedron = /* @__PURE__ */ create('dodecahedron') +export const Extrude = /* @__PURE__ */ create('extrude') +export const Lathe = /* @__PURE__ */ create('lathe') +export const Capsule = /* @__PURE__ */ create('capsule') +export const Shape = /* @__PURE__ */ create('shape', ({ geometry }) => { // Calculate UVs (by https://discourse.threejs.org/u/prisoner849) // https://discourse.threejs.org/t/custom-shape-in-image-not-working/49348/10 const pos = geometry.attributes.position as THREE.BufferAttribute diff --git a/src/core/useBVH.tsx b/src/core/useBVH.tsx index d68243201..1e346e698 100644 --- a/src/core/useBVH.tsx +++ b/src/core/useBVH.tsx @@ -56,7 +56,7 @@ export function useBVH(mesh: React.MutableRefObject, options?: }, [mesh, JSON.stringify(options)]) } -export const Bvh: ForwardRefComponent = React.forwardRef( +export const Bvh: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { enabled = true, diff --git a/src/core/useProgress.tsx b/src/core/useProgress.tsx index 7868057b2..5713831c4 100644 --- a/src/core/useProgress.tsx +++ b/src/core/useProgress.tsx @@ -11,7 +11,7 @@ type Data = { } let saveLastTotalLoaded = 0 -const useProgress = create((set) => { +const useProgress = /* @__PURE__ */ create((set) => { DefaultLoadingManager.onStart = (item, loaded, total) => { set({ active: true, diff --git a/src/helpers/constants.ts b/src/helpers/constants.ts new file mode 100644 index 000000000..e1889ba63 --- /dev/null +++ b/src/helpers/constants.ts @@ -0,0 +1,5 @@ +import { REVISION } from 'three' + +const getVersion = () => parseInt(REVISION.replace(/\D+/g, '')) + +export const version = /* @__PURE__ */ getVersion() diff --git a/src/materials/ConvolutionMaterial.tsx b/src/materials/ConvolutionMaterial.tsx index 2904c7ad4..525809b62 100644 --- a/src/materials/ConvolutionMaterial.tsx +++ b/src/materials/ConvolutionMaterial.tsx @@ -1,4 +1,5 @@ import * as THREE from 'three' +import { version } from '../helpers/constants' export class ConvolutionMaterial extends THREE.ShaderMaterial { readonly kernel: Float32Array @@ -53,9 +54,7 @@ export class ConvolutionMaterial extends THREE.ShaderMaterial { #include #include - #include <${ - parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment' - }> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }`, vertexShader: `uniform vec2 texelSize; uniform vec2 halfTexelSize; diff --git a/src/materials/DiscardMaterial.tsx b/src/materials/DiscardMaterial.tsx index f94d19b97..909fd5087 100644 --- a/src/materials/DiscardMaterial.tsx +++ b/src/materials/DiscardMaterial.tsx @@ -1,6 +1,6 @@ import { shaderMaterial } from '../core/shaderMaterial' -export const DiscardMaterial = shaderMaterial( +export const DiscardMaterial = /* @__PURE__ */ shaderMaterial( {}, 'void main() { }', 'void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); discard; }' diff --git a/src/materials/MeshRefractionMaterial.tsx b/src/materials/MeshRefractionMaterial.tsx index ceae1c01f..337190cb4 100644 --- a/src/materials/MeshRefractionMaterial.tsx +++ b/src/materials/MeshRefractionMaterial.tsx @@ -4,8 +4,9 @@ import * as THREE from 'three' import { shaderMaterial } from '../core/shaderMaterial' import { MeshBVHUniformStruct, shaderStructs, shaderIntersectFunction } from 'three-mesh-bvh' +import { version } from '../helpers/constants' -export const MeshRefractionMaterial = shaderMaterial( +export const MeshRefractionMaterial = /* @__PURE__ */ shaderMaterial( { envMap: null, bounces: 3, @@ -13,11 +14,11 @@ export const MeshRefractionMaterial = shaderMaterial( correctMips: true, aberrationStrength: 0.01, fresnel: 0, - bvh: new MeshBVHUniformStruct(), - color: new THREE.Color('white'), - resolution: new THREE.Vector2(), - viewMatrixInverse: new THREE.Matrix4(), - projectionMatrixInverse: new THREE.Matrix4(), + bvh: /* @__PURE__ */ new MeshBVHUniformStruct(), + color: /* @__PURE__ */ new THREE.Color('white'), + resolution: /* @__PURE__ */ new THREE.Vector2(), + viewMatrixInverse: /* @__PURE__ */ new THREE.Matrix4(), + projectionMatrixInverse: /* @__PURE__ */ new THREE.Matrix4(), }, /*glsl*/ ` uniform mat4 viewMatrixInverse; @@ -166,6 +167,6 @@ export const MeshRefractionMaterial = shaderMaterial( float nFresnel = fresnelFunc(viewDirection, normal) * fresnel; gl_FragColor = vec4(mix(finalColor, vec3(1.0), nFresnel), 1.0); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }` ) diff --git a/src/materials/SpotLightMaterial.tsx b/src/materials/SpotLightMaterial.tsx index 2101cc394..e97f02105 100644 --- a/src/materials/SpotLightMaterial.tsx +++ b/src/materials/SpotLightMaterial.tsx @@ -1,4 +1,5 @@ import * as THREE from 'three' +import { version } from '../helpers/constants' export class SpotLightMaterial extends THREE.ShaderMaterial { constructor() { @@ -79,7 +80,7 @@ export class SpotLightMaterial extends THREE.ShaderMaterial { gl_FragColor = vec4(lightColor, intensity * opacity); #include - #include <${parseInt(THREE.REVISION.replace(/\D+/g, '')) >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + #include <${version >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> }`, }) } diff --git a/src/materials/WireframeMaterial.tsx b/src/materials/WireframeMaterial.tsx index 4cd8e14f3..3db27c28c 100644 --- a/src/materials/WireframeMaterial.tsx +++ b/src/materials/WireframeMaterial.tsx @@ -34,9 +34,9 @@ export const WireframeMaterialShaders = { squeeze: false, squeezeMin: 0.2, squeezeMax: 1, - stroke: new THREE.Color('#ff0000'), - backfaceStroke: new THREE.Color('#0000ff'), - fill: new THREE.Color('#00ff00'), + stroke: /* @__PURE__ */ new THREE.Color('#ff0000'), + backfaceStroke: /* @__PURE__ */ new THREE.Color('#0000ff'), + fill: /* @__PURE__ */ new THREE.Color('#00ff00'), }, vertex: /* glsl */ ` attribute vec3 barycentric; @@ -137,7 +137,7 @@ export const WireframeMaterialShaders = { `, } -export const WireframeMaterial = shaderMaterial( +export const WireframeMaterial = /* @__PURE__ */ shaderMaterial( WireframeMaterialShaders.uniforms, WireframeMaterialShaders.vertex + /* glsl */ ` diff --git a/src/web/Html.tsx b/src/web/Html.tsx index b7e6864b8..77d4f3bfc 100644 --- a/src/web/Html.tsx +++ b/src/web/Html.tsx @@ -17,9 +17,9 @@ import { Assign } from 'utility-types' import { MaterialProps, ReactThreeFiber, useFrame, useThree } from '@react-three/fiber' import { ForwardRefComponent } from '../helpers/ts-utils' -const v1 = new Vector3() -const v2 = new Vector3() -const v3 = new Vector3() +const v1 = /* @__PURE__ */ new Vector3() +const v2 = /* @__PURE__ */ new Vector3() +const v3 = /* @__PURE__ */ new Vector3() function defaultCalculatePosition(el: Object3D, camera: Camera, size: { width: number; height: number }) { const objectPos = v1.setFromMatrixPosition(el.matrixWorld) @@ -142,7 +142,7 @@ export interface HtmlProps receiveShadow?: boolean // Receive shadow for occlusion plane } -export const Html: ForwardRefComponent = React.forwardRef( +export const Html: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ( { children, diff --git a/src/web/KeyboardControls.tsx b/src/web/KeyboardControls.tsx index 6a9f1c134..34f3ad2c4 100644 --- a/src/web/KeyboardControls.tsx +++ b/src/web/KeyboardControls.tsx @@ -51,7 +51,7 @@ type KeyboardControlsApi = [ UseBoundStore> ] -const context = /*@__PURE__*/ React.createContext(null!) +const context = /* @__PURE__ */ React.createContext(null!) export function KeyboardControls({ map, children, onChange, domElement }: KeyboardControlsProps) { const key = map.map((item) => item.name + item.keys).join('-') diff --git a/src/web/ScrollControls.tsx b/src/web/ScrollControls.tsx index b292d51b5..b8437665c 100644 --- a/src/web/ScrollControls.tsx +++ b/src/web/ScrollControls.tsx @@ -45,7 +45,7 @@ export type ScrollControlsState = { visible(from: number, distance: number, margin?: number): boolean } -const context = React.createContext(null!) +const context = /* @__PURE__ */ React.createContext(null!) export function useScroll() { return React.useContext(context) @@ -210,7 +210,7 @@ export function ScrollControls({ return {children} } -const ScrollCanvas: ForwardRefComponent<{}, THREE.Group> = React.forwardRef(({ children }, ref) => { +const ScrollCanvas: ForwardRefComponent<{}, THREE.Group> = /* @__PURE__ */ React.forwardRef(({ children }, ref) => { const group = React.useRef(null!) const state = useScroll() const { width, height } = useThree((state) => state.viewport) @@ -256,7 +256,7 @@ type ScrollProps = { children?: React.ReactNode } -export const Scroll: ForwardRefComponent = React.forwardRef( +export const Scroll: ForwardRefComponent = /* @__PURE__ */ React.forwardRef( ({ html, ...props }: ScrollProps, ref) => { const El = html ? ScrollHtml : ScrollCanvas return diff --git a/src/web/Select.tsx b/src/web/Select.tsx index 23bc745be..008ae1a36 100644 --- a/src/web/Select.tsx +++ b/src/web/Select.tsx @@ -4,7 +4,7 @@ import { SelectionBox } from 'three-stdlib' import { useThree } from '@react-three/fiber' import shallow from 'zustand/shallow' -const context = React.createContext([]) +const context = /* @__PURE__ */ React.createContext([]) type Props = JSX.IntrinsicElements['group'] & { /** Allow multi select, default: false */ diff --git a/src/web/View.tsx b/src/web/View.tsx index ca11e5c9f..c8cf6aea0 100644 --- a/src/web/View.tsx +++ b/src/web/View.tsx @@ -4,7 +4,7 @@ import { createPortal, useFrame, useThree } from '@react-three/fiber' const isOrthographicCamera = (def: any): def is THREE.OrthographicCamera => def && (def as THREE.OrthographicCamera).isOrthographicCamera -const col = new THREE.Color() +const col = /* @__PURE__ */ new THREE.Color() /** * In `@react-three/fiber` after `v8.0.0` but prior to `v8.1.0`, `state.size` contained only dimension diff --git a/src/web/pivotControls/AxisArrow.tsx b/src/web/pivotControls/AxisArrow.tsx index fef0bf1bf..b9737bc7c 100644 --- a/src/web/pivotControls/AxisArrow.tsx +++ b/src/web/pivotControls/AxisArrow.tsx @@ -5,8 +5,8 @@ import { Line } from '../../core/Line' import { Html } from '../Html' import { context } from './context' -const vec1 = new THREE.Vector3() -const vec2 = new THREE.Vector3() +const vec1 = /* @__PURE__ */ new THREE.Vector3() +const vec2 = /* @__PURE__ */ new THREE.Vector3() export const calculateOffset = ( clickPoint: THREE.Vector3, @@ -36,8 +36,8 @@ export const calculateOffset = ( return offset } -const upV = new THREE.Vector3(0, 1, 0) -const offsetMatrix = new THREE.Matrix4() +const upV = /* @__PURE__ */ new THREE.Vector3(0, 1, 0) +const offsetMatrix = /* @__PURE__ */ new THREE.Matrix4() export const AxisArrow: React.FC<{ direction: THREE.Vector3; axis: 0 | 1 | 2 }> = ({ direction, axis }) => { const { diff --git a/src/web/pivotControls/AxisRotator.tsx b/src/web/pivotControls/AxisRotator.tsx index 73038d42b..5aba33652 100644 --- a/src/web/pivotControls/AxisRotator.tsx +++ b/src/web/pivotControls/AxisRotator.tsx @@ -6,8 +6,8 @@ import { Html } from '../Html' import clamp from 'lodash.clamp' import { context } from './context' -const clickDir = new THREE.Vector3() -const intersectionDir = new THREE.Vector3() +const clickDir = /* @__PURE__ */ new THREE.Vector3() +const intersectionDir = /* @__PURE__ */ new THREE.Vector3() const toDegrees = (radians: number) => (radians * 180) / Math.PI const toRadians = (degrees: number) => (degrees * Math.PI) / 180 @@ -53,10 +53,10 @@ const minimizeAngle = (angle: number) => { return result } -const rotMatrix = new THREE.Matrix4() -const posNew = new THREE.Vector3() -const ray = new THREE.Ray() -const intersection = new THREE.Vector3() +const rotMatrix = /* @__PURE__ */ new THREE.Matrix4() +const posNew = /* @__PURE__ */ new THREE.Vector3() +const ray = /* @__PURE__ */ new THREE.Ray() +const intersection = /* @__PURE__ */ new THREE.Vector3() export const AxisRotator: React.FC<{ dir1: THREE.Vector3; dir2: THREE.Vector3; axis: 0 | 1 | 2 }> = ({ dir1, diff --git a/src/web/pivotControls/PlaneSlider.tsx b/src/web/pivotControls/PlaneSlider.tsx index 572f827f4..3c483992d 100644 --- a/src/web/pivotControls/PlaneSlider.tsx +++ b/src/web/pivotControls/PlaneSlider.tsx @@ -27,9 +27,9 @@ const decomposeIntoBasis = (e1: THREE.Vector3, e2: THREE.Vector3, offset: THREE. return [x, y] } -const ray = new THREE.Ray() -const intersection = new THREE.Vector3() -const offsetMatrix = new THREE.Matrix4() +const ray = /* @__PURE__ */ new THREE.Ray() +const intersection = /* @__PURE__ */ new THREE.Vector3() +const offsetMatrix = /* @__PURE__ */ new THREE.Matrix4() export const PlaneSlider: React.FC<{ dir1: THREE.Vector3; dir2: THREE.Vector3; axis: 0 | 1 | 2 }> = ({ dir1, diff --git a/src/web/pivotControls/context.ts b/src/web/pivotControls/context.ts index ad36b710c..5b1349624 100644 --- a/src/web/pivotControls/context.ts +++ b/src/web/pivotControls/context.ts @@ -27,4 +27,4 @@ export type PivotContext = { annotationsClass?: string } -export const context = React.createContext(null!) +export const context = /* @__PURE__ */ React.createContext(null!) diff --git a/src/web/pivotControls/index.tsx b/src/web/pivotControls/index.tsx index 305f62a67..f0de05258 100644 --- a/src/web/pivotControls/index.tsx +++ b/src/web/pivotControls/index.tsx @@ -8,9 +8,9 @@ import { AxisRotator } from './AxisRotator' import { context, OnDragStartProps } from './context' import { ForwardRefComponent } from '../../helpers/ts-utils' -const tV0 = new THREE.Vector3() -const tV1 = new THREE.Vector3() -const tV2 = new THREE.Vector3() +const tV0 = /* @__PURE__ */ new THREE.Vector3() +const tV1 = /* @__PURE__ */ new THREE.Vector3() +const tV2 = /* @__PURE__ */ new THREE.Vector3() const getPoint2 = (point3: THREE.Vector3, camera: THREE.Camera, size: Size) => { const widthHalf = size.width / 2 @@ -39,25 +39,25 @@ export const calculateScaleFactor = (point3: THREE.Vector3, radiusPx: number, ca return scale } -const mL0 = new THREE.Matrix4() -const mW0 = new THREE.Matrix4() -const mP = new THREE.Matrix4() -const mPInv = new THREE.Matrix4() -const mW = new THREE.Matrix4() -const mL = new THREE.Matrix4() -const mL0Inv = new THREE.Matrix4() -const mdL = new THREE.Matrix4() +const mL0 = /* @__PURE__ */ new THREE.Matrix4() +const mW0 = /* @__PURE__ */ new THREE.Matrix4() +const mP = /* @__PURE__ */ new THREE.Matrix4() +const mPInv = /* @__PURE__ */ new THREE.Matrix4() +const mW = /* @__PURE__ */ new THREE.Matrix4() +const mL = /* @__PURE__ */ new THREE.Matrix4() +const mL0Inv = /* @__PURE__ */ new THREE.Matrix4() +const mdL = /* @__PURE__ */ new THREE.Matrix4() -const bb = new THREE.Box3() -const bbObj = new THREE.Box3() -const vCenter = new THREE.Vector3() -const vSize = new THREE.Vector3() -const vAnchorOffset = new THREE.Vector3() -const vPosition = new THREE.Vector3() +const bb = /* @__PURE__ */ new THREE.Box3() +const bbObj = /* @__PURE__ */ new THREE.Box3() +const vCenter = /* @__PURE__ */ new THREE.Vector3() +const vSize = /* @__PURE__ */ new THREE.Vector3() +const vAnchorOffset = /* @__PURE__ */ new THREE.Vector3() +const vPosition = /* @__PURE__ */ new THREE.Vector3() -const xDir = new THREE.Vector3(1, 0, 0) -const yDir = new THREE.Vector3(0, 1, 0) -const zDir = new THREE.Vector3(0, 0, 1) +const xDir = /* @__PURE__ */ new THREE.Vector3(1, 0, 0) +const yDir = /* @__PURE__ */ new THREE.Vector3(0, 1, 0) +const zDir = /* @__PURE__ */ new THREE.Vector3(0, 0, 1) type PivotControlsProps = { /** Scale of the gizmo, 1 */ @@ -110,7 +110,7 @@ type PivotControlsProps = { children?: React.ReactNode } -export const PivotControls: ForwardRefComponent = React.forwardRef< +export const PivotControls: ForwardRefComponent = /* @__PURE__ */ React.forwardRef< THREE.Group, PivotControlsProps >(