Search code examples
three.jsdouble-quotestemplate-literals

Is it possible to eliminate the hassle of quotes and comma in three.js shaders?


For example, in Flash (Actionscript) I could get rid of double quotes and pluses per line of shader code (AGAL) just by using CDATA with the only requirement to left-justify the code like this:

// VERTEX SHADER CODE
var vertexShader:String = <![CDATA[
// varying registers: v1, v2, v3
// temp reg: vt0

m44 vt0, va0, vc0                       // transform vertices in world space with model matrix --> vt0  
sub v3, vc16, vt0                       // interpolate direction to light --> v3

m44 op, vt0, vc8                        // append the tranformed vertices to view-projection matrix in order to transform to clip space and output position
m44 v1, va1, vc4                        // transform normals with transposed & inverted modelmatrix and interpolate --> v1
mov v2, va2                             // interpolate uvs --> v2

]]>;

In three.js (Javascript) is it possible to get rid of the two quotes and comma per line in a similar way?

var fspass1 = [ 
"varying vec2 vUv;",
"uniform float time;",

"void main() {",

"float r = vUv.x;",
"if( vUv.y < 0.5 ) r = 0.0;",
"float g = vUv.y;",
"if( vUv.x < 0.5 ) g = 0.0;",

"gl_FragColor = vec4( r, g, time, 1.0 );",

"}"
].join("\n")

I tried the following but it does NOT work:

var fspass1 = "<![CDATA[

varying vec2 vUv;
uniform float time;

void main() {

float r = vUv.x;
if( vUv.y < 0.5 ) r = 0.0;
float g = vUv.y;
if( vUv.x < 0.5 ) g = 0.0;

gl_FragColor = vec4( r, g, time, 1.0 );

}
]]>";

Am I doing something wrong? Is there a solution? It is really distracting, time consuming anti-user friendly and embarrassing nowadays to still have to use stupid double quotes, commas etc per line of code in order to be ...understood by the framework. It should be more clever than that, programs should make our lives easier, not more difficult!


Solution

  • The lack of examples in JS files instead of inside Script tags in HTML files and the likeness of a backtick with a single quote, was the cause of my confusion and I bet for more people who still use quotes and commas or pluses, including in many three.js examples.

    So, the solution was as suggested the use of "template literals", that is, to simply enclose the whole multi-line shader code with backticks as bellow! That is a major efficiency-improvement, a life saver! :)

    The following code works, no quotes in every line and no commas!

    var fspass1 =
        `varying vec2 vUv;
    
        uniform float time;
    
        void main() {
    
            float r = vUv.x;
    
            if( vUv.y < 0.5 ) r = 0.0;
            float g = vUv.y;
    
            if( vUv.x < 0.5 ) g = 0.0;
            gl_FragColor = vec4( r, g, time, 1.0 );
    
        }`;
    

    In 24 years, I have never used a "backtick" until now, so in order to type it, just hit the button at the left of the '1' number.