Last active
July 26, 2022 20:02
-
-
Save zz85/8917654 to your computer and use it in GitHub Desktop.
AutoGen Three.js Shader Uniforms
This file contains 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
// https://github.com/mrdoob/three.js/issues/4145 | |
// based on https://github.com/unconed/ShaderGraph.js/blob/master/src/Snippet.js | |
var typeMaps = { | |
'float': 'f', | |
'vec2': 'v2', | |
'vec3': 'v3', | |
'vec4': 'v4', | |
'mat3': 'm3', | |
'mat4': 'm4', | |
'sampler2D': 't', | |
'samplerCube': 't', | |
} | |
var typeNatives = { | |
'v2': THREE.Vector2, | |
'v3': THREE.Vector3, | |
'm3': THREE.Matrix3, | |
'm4': THREE.Matrix4 | |
} | |
function parseUniforms(code, uniforms) { | |
if (!uniforms) uniforms = {}; | |
// Remove all comments and normalize newlines | |
code = code.replace(/\r\n?/g, '\n').replace(/\/\/[^\n]*\n/g, ' ').replace(/\/\*(.|\n)*?\*\//g, ' '); | |
var match_uniforms = /(?:^|;)\s*uniform\s+(([A-Za-z0-9]+)\s+([A-Za-z0-9_]+)\s*(?:\[([^\]]+)\])?)(?:$|(?=;))/g; | |
var match, type, name, array, shortType; | |
while (match = match_uniforms.exec(code)) { | |
type = match[2]; | |
name = match[3]; | |
array = match[4]; | |
shortType = typeMaps[type]; | |
if (!uniforms[name]) uniforms[name] = {}; | |
uniforms[name].type = shortType + ( array ? 'v' : '' ); | |
if (uniforms[name].value == undefined) // don't overwrite exisiting uniform values | |
uniforms[name].value = shortType in typeNatives ? new typeNatives[ shortType ] : 0; | |
}; | |
return uniforms; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment