R3F / ThreeJS / Typescript - Custom shader types that support Uniform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as THREE from "three"; | |
import { MeshProps, Object3DNode, useFrame } from "@react-three/fiber"; | |
import { GlassViewMaterial } from "./shaders/GlassViewShader"; | |
import { Mesh } from "three"; | |
import { useRef } from "react"; | |
// We extend Mesh and replace material with ShaderMaterial - which our custom shader is based off | |
interface GlassViewMesh extends THREE.Mesh { | |
material: THREE.ShaderMaterial; | |
} | |
// Optional props if we needed? Not really required at all. | |
// export type GlassViewMeshProps = Object3DNode<GlassViewMesh, GlassViewMesh>; | |
// The component props (we extend from Mesh to get things like position, rotation, etc) | |
type GlassViewProps = MeshProps & {}; | |
// The component | |
export default function GlassView({}: GlassViewProps) { | |
// We use our custom "Mesh" ref | |
const meshRef = useRef<GlassViewMesh>(); | |
// Setting the uniforms | |
// You can test the types here | |
useFrame((state, delta) => { | |
if (meshRef.current) { | |
meshRef.current.rotation.x = meshRef.current.rotation.y += 0.01; | |
} | |
if (meshRef.current?.material?.uniforms?.time) { | |
meshRef.current.material.uniforms.time.value += | |
Math.sin(delta / 2) * Math.cos(delta / 2); | |
} | |
}); | |
return ( | |
<> | |
<mesh ref={meshRef} position={[0, 0, 0]}> | |
<planeBufferGeometry args={[1, 1]} /> | |
<GlassViewMaterial /> | |
{/* <meshPhongMaterial color="blue" /> */} | |
</mesh> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment