Uniform parser

From The WebGL Cookbook
Jump to: navigation, search

Here is a parser for uniform names in shaders.

var ExtractUniformsFromShaderSource = function(source){
var reg = new RegExp("\uniform ((bool|int|uint|float|[biu]?vec[234]|mat[234]x?[234]?) ([A-Za-z0-9]*));","gi");
var tmp;
var returnvalue= [];
while (tmp = reg.exec(str)){
returnvalue.push(tmp[3]);
};
return returnvalue
}

Usage:

ar str = "    varying vec2 vTextureCoord;  varying vec4 vTransformedNormal;  varying vec4 vPosition; uniform float uMaterialShininess; uniform vec3 uMaterialSpecularColor; uniform bool uShowSpecularHighlights;  uniform bool uUseLighting; uniform bool uUseTextures;  uniform vec3 uAmbientColor;  uniform vec3 uPointLightingLocation;uniform vec3 uPointLightingSpecularColor;  uniform vec3 uPointLightingDiffuseColor;uniform sampler2D uSampler;  void main(void) {vec3 ambientLightWeighting = vec3(1.0, 1.0, 1.0);vec3 diffuseLightWeighting = vec3(0.0, 0.0, 0.0);vec3 specularLightWeighting = vec3(0.0, 0.0, 0.0); if (uUseLighting) {  ambientLightWeighting = uAmbientColor; vec3 lightDirection = normalize(uPointLightingLocation - vPosition.xyz);vec3 normal = normalize(vTransformedNormal.xyz); if (uShowSpecularHighlights) {vec3 eyeDirection = normalize(-vPosition.xyz);        vec3 reflectionDirection = reflect(-lightDirection, normal);  float specularLightBrightness = pow(max(dot(reflectionDirection, eyeDirection), 0.0), uMaterialShininess);     specularLightWeighting = uPointLightingSpecularColor * specularLightBrightness;  } float diffuseLightBrightness = max(dot(normal, lightDirection), 0.0);diffuseLightWeighting = uPointLightingDiffuseColor * diffuseLightBrightness;} vec4 fragmentColor;   if (uUseTextures) { fragmentColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));} else { fragmentColor = vec4(1.0, 1.0, 1.0, 1.0);} gl_FragColor = vec4(fragmentColor.rgb * ambientLightWeighting + fragmentColor.rgb * diffuseLightWeighting + uMaterialSpecularColor * specularLightWeighting, fragmentColor.a);}"
 
ExtractUniformsFromShaderSource(str);
 
/* returns ["uMaterialShininess", "uMaterialSpecularColor", "uShowSpecularHighlights", "uUseLighting", "uUseTextures", "uAmbientColor", "uPointLightingLocation", "uPointLightingSpecularColor", "uPointLightingDiffuseColor"]
*/
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox