[英]OpenGL ES 2.0 colored rectangle
I want to write an app for Android with OpenGL ES 2.0 that displays a colored rectangle, like that:我想为带有 OpenGL ES 2.0 的 Android 编写一个应用程序,该应用程序显示一个彩色矩形,如下所示:
This are my 2 shaders:这是我的 2 个着色器:
// Vertex Shader
attribute vec4 vPosition;
void main() {
gl_Position = vPosition;
}
// Fragment Shader
uniform vec4 u_colorRGBA;
void main() {
gl_FragColor = u_colorRGBA;
}
I can draw rectangles with different colors, but i want to draw them so each corner has a diffrent color.我可以绘制具有不同颜色的矩形,但我想绘制它们以便每个角都有不同的颜色。 Can i pass variables from the vertex shader to the fragment shader to define the color of each corner?
我可以将变量从顶点着色器传递给片段着色器来定义每个角的颜色吗? If so how do i define the variables and pass them over?
如果是这样,我如何定义变量并传递它们? Or is there another way to do it?
或者有其他方法可以做到吗?
I figured out a way to do it:我想出了一种方法来做到这一点:
I changed my shaders like this:我像这样改变了我的着色器:
// Vertex Shader
attribute vec4 inColor;
varying vec4 vColor;
attribute vec4 vPosition;
void main() {
gl_Position = vPosition;
vColor = inColor;
}
// Fragment Shader
varying vec4 vColor;
void main() {
gl_FragColor = vColor;
}
Then i draw the rectangle like that:然后我像这样绘制矩形:
public static void Draw(float vertices[], int verticesCount, float color[]) {
vertexBuffer.put(vertices);
vertexBuffer.position(0);
GLES20.glEnableVertexAttribArray(sPosition);
GLES20.glVertexAttribPointer(sPosition, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);
colorBuffer.put(color);
colorBuffer.position(0);
GLES20.glEnableVertexAttribArray(sColor);
GLES20.glVertexAttribPointer(sColor, 4, GLES20.GL_FLOAT, false, 0, colorBuffer);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, verticesCount); // Draw
GLES20.glDisableVertexAttribArray(sPosition);
GLES20.glDisableVertexAttribArray(sColor);
}
Is this the correct way of doing it?这是正确的做法吗? Or are their better ways?
或者是他们更好的方法?
Good job, that is only one way to pass color variables through two shaders.干得好,这只是通过两个着色器传递颜色变量的一种方法。
However, a little more simply, you can do it without passing them through two shaders.但是,更简单一点,您可以在不通过两个着色器的情况下完成此操作。
vec2 uv = gl_FragCoord.xy / resolution.xy;
gl_FragColor = vec4(uv,0.0,1.0);
You still need to pass one uniform2f, resolution directly going to the fragment shader or you can define it as a constant like const vec2 resolution = vec2(320.,480.);您仍然需要传递一个uniform2f,分辨率直接进入片段着色器,或者您可以将其定义为常量,如const vec2 resolution = vec2(320.,480.); in the fragment shader
在片段着色器中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.