Reputation: 257
I'm really new to gl and trying to understand how to give my shaders a position attribute. A library I was using somehow made it so I got a vec3 position for each pixel of a surface. Does anyone know how I could achieve that? I believe if I pass in an attribute or uniform then it will be that value for every pixel that the shader processes. I'm wondering how to get it to increment as it shades the area.
This is how I'm drawing my surface:
draw(gl) {
gl.useProgram(this.prog);
gl.bindBuffer(gl.ARRAY_BUFFER, this.coordsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.coords, gl.STREAM_DRAW);
gl.vertexAttribPointer(this.coordsAttrib, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(this.coordsAttrib);
gl.uniform2fv(this.inTexCoordUni, this.inTexCoord);
gl.uniform1f(this.rotationUni, this.rotation);
gl.uniform2fv(this.dimensionsUni, this.dimensions);
gl.uniform1f(this.borderWidthUni, this.borderWidth);
gl.uniform2fv(this.positionUni, this.position);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
}
Here are the shaders:
precision mediump float;
uniform vec2 position1;
uniform vec2 textureSize_;
uniform vec2 inTexCoord;
uniform float rotation;
varying vec2 texCoord;
varying vec2 center;
attribute vec2 coords1;
void main() {
gl_Position = vec4(coords1, 0.0, 1.0);
float inX = (inTexCoord.x/textureSize_.x);
float inY = (inTexCoord.y/textureSize_.y);
float x = position1.x*2.5/textureSize_.x+inX;
float y = position1.y*2.5/textureSize_.y+inY;
float s = sin(rotation);
float c = cos(rotation);
float dX = x - inX;
float dY = y - inY;
float newX = inX + c * dX - s * dY;
float newY = inY + s * dX + c * dY;
center.x = inTexCoord.x/textureSize_.x;
center.y = inTexCoord.y/textureSize_.y;
texCoord.x = newX;
texCoord.y = newY;
}
precision mediump float;
uniform vec2 textureSize_;
uniform sampler2D texture1;
uniform vec2 dimensions;
uniform float borderWidth;
varying vec2 texCoord;
varying vec2 center;
void main() {
float dx = texCoord.x - center.x;
float dy = texCoord.y - center.y;
float dist = sqrt(dx * dx + dy * dy);
float radius = (dimensions.x*2.5/textureSize_.x)/2.0-0.003;
if(dist > radius)
discard;
else if(dist > radius-borderWidth)
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
else
gl_FragColor = vec4(texture2D(texture1, texCoord).rgb, 1.0);
}
Upvotes: 1
Views: 940
Reputation:
The fragment shader allows for individual pixel access.
A good example of this is a fullscreen quad. Even though only 4 vertices (4 vec2 positions) get sent to the vertex shader, the shaders do work behind-the-scenes on "pos = position"...
#version 450 core
layout (location = 0) in vec2 position;
out vec2 pos;
void main() {
pos = position;
gl_Position = vec4(position[0], position[1], 0, 1);
}
You can do something like this in the fragment shader:
#version 450 core
out vec4 final_color;
in vec2 pos;
void main()
{
if (pos[0] + 0.001 > pos[1] && pos[0] - 0.001 < pos[1]){
final_color = vec4(1, 0, 0, 1);
}
else{
final_color = vec4(0, 0, 0, 1);
}
}
To render the following...
Upvotes: 2