pow 函数在 glsl 中如何工作?

how does the pow function work in glsl?

我正在关注网站:https://thebookofshaders.com/05/

我现在正在处理这段代码,但我似乎无法理解当我将不同的值插入函数时 pow 函数是如何改变行的:

// 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);
}

因此,现在坚持使用 pow 函数以及更改值如何相对于 st.x 值

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

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) 会给你一条曲线。只需对 0 和 1

之间的 st.x 的各种值进行数学运算 b = st.x * 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