在 Processing 3 中将代码实现为着色器

Implementing code as a shader in Processing 3

我最近在处理 3 中创建了一个简单的程序来将每个像素设置到它的位置作为颜色。

void setup()
{
  size(960,960);
}

void draw()
{
  for(int j = 0;j < height;j++)
  {
    for(int i = 0;i < width;i++)
    {
      set(i,j,color(map(i,0,width,0,255),map(j,0,height,0,255),0));
    }
  }
}

我怎样才能将其实现为着色器?

注意:我已经在网上查过了,但找不到真正的答案。

如果你还不是很熟悉着色器,你应该先看看这个页面:https://processing.org/tutorials/pshader/

您可能想要绘制一个覆盖整个屏幕的矩形,并使用内置的 GLSL 变量 gl_FragCoord,它为您提供 x 中当前像素的索引] 和 y 很像你的循环变量 ij。有关完整文档,请参阅 https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/gl_FragCoord.xhtml

还要记住,片段着色器输出的值在 0 到 1 范围内,而不是 0 到 255 范围内。所以最终相关的着色器代码可能类似于:

uniform vec2 windowSize; //the shader doesn't know this automatically, so you'll need to pass it in yourself
void main() {
  gl_FragColor = vec4(gl_FragCoord / windowSize, 0, 1);
}