Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created August 1, 2022 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/d91d5101d1c290aca784b2ae31eb7a24 to your computer and use it in GitHub Desktop.
Save whoisryosuke/d91d5101d1c290aca784b2ae31eb7a24 to your computer and use it in GitHub Desktop.
R3F / ThreeJS / Typescript - Custom shader types that support Uniform
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