Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Last active November 2, 2022 21:59
Show Gist options
  • Save sketchpunk/0f5ca9cc69431d15216f688803c2083e to your computer and use it in GitHub Desktop.
Save sketchpunk/0f5ca9cc69431d15216f688803c2083e to your computer and use it in GitHub Desktop.
Resolve shader code of three,js materials
import { ShaderChunk } from 'three';
/*
USAGE
const geo = new THREE.BoxGeometry( 1, 1, 1 );
const mat = new THREE.PointsMaterial( { size: 0.5, vertexColors: true } );
const mesh = new THREE.Points( geo, mat );
resolvedShaderPromise( mat ).
then( sh => console.log( sh ) );
*/
export default function resolvedShaderPromise( mat ){
return new Promise( ( resolve, reject )=>{
mat.onBeforeCompile = function( shader, renderer ){
const out = {
vertex : resolveIncludes( shader.vertexShader ),
fragment : resolveIncludes( shader.fragmentShader ),
};
resolve( out );
};
});
}
// https://github.com/mrdoob/three.js/blob/d9af9952fc32c2a1281707946177135b90297aab/src/renderers/webgl/WebGLProgram.js#L205
function resolveIncludes( src ){
const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
return src.replace( includePattern, includeReplacer );
}
function includeReplacer( match, include ) {
const string = ShaderChunk[ include ];
if( string === undefined ) throw new Error( 'Can not resolve #include <' + include + '>' );
return resolveIncludes( string );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment