Created
April 27, 2014 05:29
-
-
Save IceCreamYou/11338221 to your computer and use it in GitHub Desktop.
A utility function to extract convenient multi-line strings with embedded variables from comments in function bodies. Particularly useful for inline GLSL shader code.
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
/** | |
* Extract a multiline string from a multiline comment inside a function. | |
* | |
* @param {Function} fn The function containing the string. | |
* @param {vars} A map of tokens to values to replace in the string. | |
*/ | |
function textFromComment(fn, vars) { | |
var s = (fn + '').match(/^[\s\S]*?\/\*!?\s*([\s\S]+?)\s*\*\/$/m)[1]; | |
if (typeof vars !== 'undefined') { | |
var keys = Object.keys(vars).sort(function(a, b) { return b.length - a.length; }); | |
for (var i = 0, l = keys.length; i < l; i++) { | |
var key = keys[i], val = vars[key]; | |
s = s.split('$' + key).join(val); | |
} | |
} | |
return s; | |
} | |
/* Usage example */ | |
textFromComment(fragmentShader, { | |
assignTextures: assign, | |
declareTextures: declare, | |
}); | |
function fragmentShader() { | |
/*! | |
varying vec2 vUv; | |
varying vec3 vPosition; | |
$declareTextures | |
void main() { | |
vec4 color = texture2D( texture_0, vUv ); // base | |
$assignTextures | |
gl_FragColor = color; | |
} | |
*/ | |
var z; // prevent UglifyJS from removing the above comment | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment