【问题标题】:how does the pow function work in glsl? [closed]pow 函数在 glsl 中是如何工作的? [关闭]
【发布时间】:2018-04-20 11:36:37
【问题描述】:

我正在关注这个网站: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 值相关的工作原理

【问题讨论】:

  • 您阅读过规范吗? khronos.org/registry/OpenGL-Refpages/gl4/html/pow.xhtml... 所以说 10 ^ 1.5 - 如果你不明白,请看这里:math.stackexchange.com/questions/21381/…
  • 10st.x 的一个例子。 st.x 可以是任何东西。
  • 好的,感谢您的反馈和帮助。我想我的数学很弱,所以我正在努力解决这个问题。你是否建议我回到基础学习数学,然后再回到这段旅程?
  • 荒谬的是,这个问题被关闭为题外话。这个问题和出色的答案是 stackoverflow 有多好的一个例子。

标签: three.js glsl webgl


【解决方案1】:

计算该行的代码可以说是这段代码

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 之间计算 b = st.x * 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

【讨论】:

  • 好吧有道理,好像我只是在数学上挣扎。这意味着我应该回到基础,学习一些数学,然后回到这段旅程?
  • 假装直到成功!
猜你喜欢
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多