how does the pow function work in glsl?

时间:2018-04-20 00:38:53

标签: three.js glsl webgl

I'm following the website: https://thebookofshaders.com/05/

I'm working on this code now but I can't seem to understand how the pow function is making the line change when I plug in different values into the function:

// Author: Inigo Quiles
// Title: Expo

#ifdef GL_ES
precision mediump float;
#endif

#define PI 3.14159265359

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

float plot(vec2 st, float pct){
  return  smoothstep( pct-0.02, pct, st.y) -
          smoothstep( pct, pct+0.02, st.y);
}

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution;

    float y = pow(st.x, 1.5);<-- 1.5 what is it doing exactly? how does changing the values make the line change in relation to the st.x value?

    vec3 color = vec3(y);

    float pct = plot(st,y);
    color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0);

    gl_FragColor = vec4(color,1.0);
}

Hence, for now stuck with the pow function and how changing the values works in relation to the st.x value

1 个答案:

答案 0 :(得分:2)

计算这条线的代码可以说就是这段代码

float plot(vec2 st, float pct){
  return  smoothstep( pct-0.02, pct, st.y) -
          smoothstep( pct, pct+0.02, st.y);
}

因为它只使用st.y我认为如果像这样写的话可能会更容易理解

float one_if_a_is_close_to_b_else_zero(float a, float b){
  return smoothstep(a - 0.02, a, b) -
         smoothstep(a, a + 0.02, b);
}

该代码用于选择2种颜色。一种颜色是

color = vec3(y);

这将是一个灰色阴影

另一种颜色为vec3(0.0, 1.0, 0.0),为绿色

此行选择这两种颜色,灰色或绿色

color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0);

可能更容易理解

vec3 gray = vec3(y);
vec3 green = vec3(0, 1, 0);

// choose gray when pct is 0
// green when pct is 1
// and a mix between them when pct is between 0 and 1
color = mix(gray, green, pct);

所以剩下的就是选择pct所以我们也要重写它。

// st.x goes from 0.0 to 1.0 left to right across the canvas
// st.y goes from 0.0 to 1.0 up the canvas
float a = st.y;
float b = pow(st.x, 1.5);
float pct = one_if_a_is_close_to_b_else_zero(a, b);

而不是使用pow,您可以尝试一些替换

float b = st.x;  // same as pow(st.x, 1.)

float b = st.x * st.x;  // same as pow(st.x, 2.)

float b = st.x * st.x * st.x;  // same as pow(st.x, 3.)

知道st.x从0变为1,应该很清楚pow(st.x, 1)会给你一条直线而pow(st.x, 2.0)会给你一条曲线。只需对b = st.x * st.x 0和1

的各种值进行数学st.x
  0 *   0 = 0.00
 .1 *  .1 = 0.01
 .2 *  .2 = 0.04
 .3 *  .3 = 0.09
 .4 *  .4 = 0.16
 .5 *  .5 = 0.25   // we're half way between 0 and 1 but the result is only .25
 .6 *  .6 = 0.36
 .7 *  .7 = 0.49
 .8 *  .8 = 0.64
 .9 *  .8 = 0.81
1.0 * 1.0 = 1.00