如何在特定位置用p5着色器绘制正方形?



使用p5.js我有:

s.draw = () => {
s.background(0);
s.translate(-s.windowWidth / 2, -s.windowHeight / 2, 0);
s.shader(shader);
shader.setUniform("u_resolution", [s.width, s.height]);
shader.setUniform('vPos', getSquarePoints(cols/2, rows/2));
s.square(0, 0, cellSize);    
}
const getSquarePoints = (i, j) => {
return new Float32Array([
i, j,
(i + cellSize), j,
i, (j + cellSize),
(i + cellSize), j,
(i + cellSize), (j + cellSize),
i, (j + cellSize),
])
}

My vertex:

#ifdef GL_ES
precision mediump float;
#endif
attribute vec3 aPosition;
varying vec2 vPos;
void main() {
vec4 positionVec4 = vec4(aPosition, 1.0);
positionVec4.xy = positionVec4.xy * 2.0 - 1.0;
gl_Position = positionVec4;
}

片段:

#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
varying vec2 vPos;
void main() {
vec2 st = gl_FragCoord.xy / u_resolution.xy;
gl_FragColor = vec4(st.x, st.y, 0.0, 1.0);
}

所以vPos有错误的类型,但我的计划是定义6个点需要用2个三角形做一个正方形,并将这些点发送到位置缓冲区。

  • 我该怎么做呢?
  • 这是"正确的方式"吗?

我不太理解这个问题,无法给出适当的反馈,但由于没有更聪明的人回答,我将尝试。我确实使用下面的过程得到了类似的工作:

1、在draw函数中创建一个图像对象:

let pixel_image = createImage(width, height);
pixel_image.loadPixels();

2,使用.set()填充图像的像素,I和j,应该来自循环并且是您想要覆盖的像素。

pixel_image.set(i, j, color(0, 90, 102));
3、更新图像像素
pixel_image.updatePixels();

查看在p5.js中从像素位置创建图像,了解如何完成上述步骤

4,将图像保存到shader. fragment文件中的一个变量中。出于某种原因,我将变量命名为pixel_coordds:

shader.setUniform('pixel_coords', pixel_image);

5,在shader. rag文件中,你会看到传入的图像:

统一sampler2D pixel_coord;查看从p5到shaders的shader文件图像以了解更多信息

Shader fragment file:

precision mediump float;
// we need our texcoords for drawing textures
varying vec2 vTexCoord;
// images are sent to the shader as a variable type called sampler2D
uniform sampler2D pixel_coords;
void main() {
// by default, our texcoords will be upside down
// lets flip them by inverting the y component
vec2 uv = vTexCoord;
uv.y = 1.0 - uv.y;
// we can access our image by using the GLSL shader function texture2D()
// texture2D expects a sampler2D, and texture coordinates as it's input
vec4 image = texture2D(pixel_coords, uv);
gl_FragColor = image;
}

shader vert file

// our vertex data
attribute vec3 aPosition;
// our texcoordinates
attribute vec2 aTexCoord;
// this is a variable that will be shared with the fragment shader
// we will assign the attribute texcoords to the varying texcoords to move them from the vert shader to the frag shader
// it can be called whatever you want but often people prefix it with 'v' to indicate that it is a varying
varying vec2 vTexCoord;
void main() {
// copy the texture coordinates
vTexCoord = aTexCoord;
// copy the position data into a vec4, using 1.0 as the w component
vec4 positionVec4 = vec4(aPosition, 1.0);
positionVec4.xy = positionVec4.xy * 2.0 - 1.0;
// send the vertex information on to the fragment shader
gl_Position = positionVec4;
}

最新更新