When it comes to shaders, they are simply strings that you can manipulate and acquire as needed. Luckily, three.js provides a variety of tools to assist you in creating them more effectively.
One way to work with shaders is through the THREE.Material
abstraction, which allows you to define basic properties while three.js handles the shader configuration behind the scenes.
//no shaders involved
var redPlastic = new THREE.MeshStandardMaterial({
color: 'red',
roughness: notVeryRough
})
If you use a ShaderMaterial
, you will need to write raw GLSL code, but the material still simplifies certain tasks that would otherwise require manual intervention. On the other hand, RawShaderMaterial
requires writing everything from scratch. Here's an example with THREE.ShaderMaterial
:
varying vec2 vUv;
void main(){
vUv = uv;
vec4 worldPosition = modelMatrix * vec4( position, 1.);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
When three.js is compiled and integrated into a webpage, the THREE.ShaderChunk
dictionary is available within the THREE namespace. This contains various GLSL code snippets used in constructing materials.
You can extract these snippets from their source files and incorporate them into your own shader files or strings.
You can also use string templates to compose your shaders:
`${THREE.ShaderChunk.some_chunk}
void main(){
...
${anotherChunk}
gl_Position = ...
`
If you wish to enhance the default materials provided by three.js, you can utilize the (arguably buggy and quirky :)) onBeforeCompile
feature. This allows you to apply a callback to any built-in material, giving you access to the shader object before compilation. Here, you can insert your own GLSL code, replace chunks, or perform other manipulations on the string.
To make use of this feature, it's important to understand the structure of the shaders constructed from the following source:
https://github.com/mrdoob/three.js/tree/dev/src/renderers/shaders/ShaderChunk