普通视图

发现新文章,点击刷新页面。
昨天 — 2025年5月18日首页

Step - Invert

作者 烛阴
2025年5月18日 22:51

Task

Write a shader that splits the screen into two parts: the left half should be red and the right half should be black.

编写一个着色器,将屏幕分成两部分:左半部分应为红色,右半部分应为黑色。

Requirements

The shader should avoid using branching or conditional statements in its code, and instead rely on the step function to determine the color of each pixel.

着色器应避免在其代码中使用分支或条件语句,而是依靠step函数来确定每个像素的颜色。

Theory

您可以step通过从中减去阶跃函数结果来反转函数的结果1

如果输入值小于阈值,并且输入值大于或等于阈值,则函数返回。通过从中减去此结果,step可以有效地反转输出:0.0``1.0``1.0

  • • 如果原始结果是0.0,则反转的结果将是1.0
  • • 如果原始结果是1.0,则反转的结果将是0.0

例子

下面是一个示例代码片段,用于说明如何step在 GLSL 中反转函数的结果:

float invertedStep = 1.0 - step(threshold, value);

因此,如果大于或等于,invertedStep则为,否则为。0.0``value``threshold``1.0

Answer

uniform vec2 iResolution;

void main() {
  // Normalized pixel coordinates (from 0 to 1)
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  float result = step(0.5, 1.0 - uv.x);

  gl_FragColor = vec4(result, 0.0, 0.0, 1.0);
}

效果

image.png

练习

Step - Invert

最后

如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!

昨天以前首页

Step

作者 烛阴
2025年5月17日 23:06

Task

Write a shader that splits the screen into two parts: the left half should be black and the right half should be red. The shader should work for any screen resolution. To achieve this, consider using the iResolution uniform variable and gl_FragColor to control the position of the split.

编写一个着色器,将屏幕分成两部分:左半部分为黑色,右半部分为红色。该着色器应适用于任何屏幕分辨率。为此,请考虑使用iResolutionuniform 变量 和gl_FragColor来控制分割的位置。

Requirements

The shader should avoid using branching or conditional statements in its code, and instead rely on the step function to determine the color of each pixel.

着色器应避免在其代码中使用分支或条件语句,而是依靠step函数来确定每个像素的颜色。

Theory

step是一个阈值函数。如果传递的值小于阈值,step则返回0.0,否则返回1.0edge是阈值

函数

float step(float edge, float x)

  • 如果是x < edge,函数返回0.0
  • 如果是x >= edge,函数返回1.0

示例用法

float edge = 0.5;

float x = 0.3;

float result = step(edge, x); // x < edge ? 0.0 : 1.0

Answer

uniform vec2 iResolution;

void main() {
  vec2 uv = gl_FragCoord.xy/iResolution.xy;
  float result = step(0.5, uv.x);
  gl_FragColor = vec4(result, 0.0, 0.0, 1.0);
}

效果

image.png

练习

Step

最后

如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!

❌
❌