|
| 1 | +import * as THREE from 'three' |
| 2 | +import { useRef } from 'react' |
| 3 | +import { useFrame, useThree } from '@react-three/fiber' |
| 4 | +import { BlendFunction, Effect } from 'postprocessing' |
| 5 | + |
| 6 | +import { wrapEffect } from '../util' |
| 7 | + |
| 8 | +// |
| 9 | +// Effect |
| 10 | +// |
| 11 | + |
| 12 | +const ExampleShader = { |
| 13 | + fragment: ` |
| 14 | + uniform vec3 color; |
| 15 | + uniform float time; |
| 16 | + void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { |
| 17 | + outputColor = vec4(color, 0.5 + (cos(time) / 2.0 + 0.5)); |
| 18 | + } |
| 19 | + `, |
| 20 | +} |
| 21 | + |
| 22 | +type ExampleEffectOptions = { |
| 23 | + /** The color for this effect */ |
| 24 | + color: THREE.Color |
| 25 | + /** The blend function of this effect */ |
| 26 | + blendFunction?: BlendFunction |
| 27 | +} |
| 28 | + |
| 29 | +export class ExampleEffect extends Effect { |
| 30 | + constructor({ color, blendFunction }: ExampleEffectOptions) { |
| 31 | + super('LensFlareEffect', ExampleShader.fragment, { |
| 32 | + blendFunction, |
| 33 | + uniforms: new Map<string, THREE.Uniform>([ |
| 34 | + ['color', new THREE.Uniform(color)], |
| 35 | + ['time', new THREE.Uniform(0)], |
| 36 | + ]), |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + update(_renderer: any, _inputBuffer: any, deltaTime: number) { |
| 41 | + const time = this.uniforms.get('time') |
| 42 | + if (time) { |
| 43 | + time.value += deltaTime |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// |
| 49 | +// Component |
| 50 | +// |
| 51 | + |
| 52 | +const ExampleWrapped = wrapEffect(ExampleEffect) |
| 53 | + |
| 54 | +type ExampleProps = React.ComponentPropsWithoutRef<typeof ExampleWrapped> & { |
| 55 | + /** mouse */ |
| 56 | + mouse?: boolean |
| 57 | +} |
| 58 | + |
| 59 | +export const Example = ({ mouse = false, ...props }: ExampleProps) => { |
| 60 | + const pointer = useThree(({ pointer }) => pointer) |
| 61 | + |
| 62 | + const ref = useRef<ExampleEffect>(null) |
| 63 | + |
| 64 | + useFrame(() => { |
| 65 | + if (!mouse) return |
| 66 | + if (!ref?.current) return |
| 67 | + |
| 68 | + const uColor = ref.current.uniforms.get('color') |
| 69 | + if (!uColor) return |
| 70 | + |
| 71 | + uColor.value.r = pointer.x / 2.0 + 0.5 |
| 72 | + uColor.value.g = pointer.y / 2.0 + 0.5 |
| 73 | + }) |
| 74 | + |
| 75 | + return <ExampleWrapped ref={ref} {...props} /> |
| 76 | +} |
0 commit comments