The demo is real, you can click it! It contains full code, too. ๐ฆ
Custom Shader Material (CSM) lets you extend Three.js' material library with your own Vertex and Fragment shaders.
import CustomShaderMaterial from 'three-custom-shader-material'
function Cube() {
const materialRef = useRef()
useFrame((state) => {
if (materialRef.current) {
materialRef.current.uniforms.uTime.value = state.clock.elapsedTime
}
})
return (
<mesh>
<boxGeometry />
<CustomShaderMaterial
ref={materialRef}
baseMaterial={MeshPhysicalMaterial}
vertexShader={/* glsl */ ` ... `}
fragmentShader={/* glsl */ ` ... `}
uniforms={{
uTime: {
value: 0,
},
}}
flatShading
color={0xff00ff}
// ...
/>
</mesh>
)
}
Show Typescript example
import CustomShaderMaterial, { CSM } from 'three-custom-shader-material'
function Cube() {
const materialRef = useRef<CSM | null>(null)
useFrame((state) => {
if (materialRef.current) {
materialRef.current.uniforms.uTime.value = state.clock.elapsedTime
}
})
return (
<mesh>
<boxGeometry />
<CustomShaderMaterial
ref={materialRef}
baseMaterial={MeshPhysicalMaterial}
vertexShader={/* glsl */ ` ... `}
fragmentShader={/* glsl */ ` ... `}
uniforms={{
uTime: {
value: 0,
},
}}
flatShading
color={0xff00ff}
// ...
/>
</mesh>
)
}
Show VanillaJS example
import { CSM } from 'three-custom-shader-material'
function Box() {
const geometry = new THREE.BoxGeometry()
const material = new CSM({
MeshPhysicalMaterial // baseMaterial
/* glsl */ ` ... `, // vertexShader
/* glsl */ ` ... `, // fragmentShader
{ uTime: {
value: 0, // uniforms
},
},
{
flatShading: true // options
color: 0xff00ff
}
})
return new THREE.Mesh(geometry, material)
}
npm
npm install three-custom-shader-material
Yarn
yarn add three-custom-shader-material
CSM provides the following output variables:
Variable | Required | Type | Description | Available In | Notes |
---|---|---|---|---|---|
csm_Position | โ | vec3 |
Custom vertex position. | Vertex Shader | csm_Position will be multiplied by projectionMatrix and modelViewPosition furthur down the line. |
csm_Normal | โ | vec3 |
Custom vertex normals. | Vertex Shader | |
csm_PointSize | โ | float |
Custom gl_Point size. | Vertex Shader | |
csm_DiffuseColor | โ | vec4 |
Custom diffuse color. | Fragment Shader |
You must use these variables like you would use standard GLSL output variables.
// gl_Position = projectionMatrix * modelViewPosition * position * vec3(2.0);
csm_Position = position * vec3(2.0);
- Support
MeshToonMaterial
- Support
MeshLambertMaterial
- Support
MeshDepthMaterial
-
gl_FragColor
override - Make
csm_Position
independent frommodelViewPosition
andprojectionMatrix
Icon made by Freepik from www.flaticon.com.