Created
April 9, 2025 16:29
-
-
Save sketchpunk/267642d2a491f2849ac42288429e78be to your computer and use it in GitHub Desktop.
Raw Shader Template for Threejs
This file contains hidden or 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'; | |
class CustomMaterial extends THREE.RawShaderMaterial { | |
constructor( props={} ){ | |
super(); | |
// Merge custom props with default options | |
const opts = Object.assign( | |
{ | |
offset : [ 0, 1, 0 ], | |
color : new THREE.Color( '#00ff00' ), | |
}, | |
props, | |
); | |
this.name = 'CustomMaterial'; | |
this.glslVersion = THREE.GLSL3; | |
this.depthTest = true | |
// this.transparent = true; | |
// this.alphaToCoverage = true; | |
// this.side = THREE.DoubleSide; | |
// this.lights = false; | |
this.uniforms = { | |
offset : { value: opts.offset }, | |
color : { value: opts.color }, | |
}; | |
this.vertexShader = ` | |
in vec3 position; // Vertex Position | |
in vec3 normal; // Vertex Normal Direction | |
in vec2 uv; // Vertex Texture UV Coordinate | |
uniform mat4 modelMatrix; // To WorldSpace | |
uniform mat4 viewMatrix; // To ViewSpace | |
uniform mat4 projectionMatrix; // To NDC ( Normalized Device Coordinate Space ) aka ScreenSpace | |
uniform vec3 offset; | |
out vec3 fragWPos; | |
out vec3 fragWNorm; | |
out vec2 fragUV; | |
void main(){ | |
vec4 wpos = modelMatrix * vec4( position + offset, 1.0 ); // Add custom offset & put into worldspace | |
fragWPos = wpos.xyz; // Pass worldspace position to fragment shader | |
fragUV = uv; // Pass UV to worldspace position | |
fragWNorm = ( modelMatrix * vec4( normal, 0.0 ) ).xyz; | |
gl_Position = projectionMatrix * viewMatrix * wpos; | |
}`; | |
this.fragmentShader = `precision mediump float; | |
in vec3 fragWPos; | |
in vec2 fragUV; | |
in vec3 fragWNorm; | |
out vec4 outColor; | |
// uniform vec3 cameraPosition; // Auto uniforms, 3js will update for you | |
uniform vec3 color; | |
void main(){ | |
vec3 norm = normalize( fragWNorm ); | |
outColor = vec4( color * norm, 1.0 ); | |
}`; | |
} | |
// #region SETTERS | |
setOffset( v ){ | |
this.uniforms.offset.value = v; | |
return this; | |
} | |
// #endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment