Task
Write a shader that draws a grid. Each cell in the grid should be
50x50
pixels in size, with a margin of10
pixels between cells.
编写一个绘制网格的着色器。网格中的每个单元格应为50x50
像素大小,单元格之间的间距为10像素。
Requirements
The shader should avoid using branching or conditional statements in its code, and instead rely on the
fract
andstep
functions to determine the color of each pixel.
着色器应避免在其代码中使用分支或条件语句,而是依靠fract
和step
函数来确定每个像素的颜色。
Theory
把一个单元格和一个间距做为一个整体, 开始
10
像素作为间距,[10, 60]
作为单元格,宽和高使用同样的处理方式,使用step
处理各自区域之间的值。
Answer
glsl
void main() {
float cellSize = 50.0f;
float margin = 10.0f;
vec2 cell = gl_FragCoord.xy/(cellSize + margin);
float x = step(margin / (cellSize + margin), fract(cell.x));
float y = step(margin / (cellSize + margin), fract(cell.y));
gl_FragColor = vec4(1.0 * x * y, 0.0, 0.0, 1.0);
}
效果

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