Android glVertexAttribPointer Stride / Offset

时间:2016-10-12 02:51:23

标签: java android opengl-es shader

我有一个打包的顶点缓冲区,其中包含位置坐标以及格式为{x,y,z,r,g,b}的顶点的颜色值。

我能够将正确的xyz值传递给Vertex Shader。出乎意料的是,渲染的方块呈白色。

使用glVertexAttribPointer(...)从压缩顶点缓冲区渲染的正确方法是什么?

代码:

public float vertices[] = {
        1, 1, 1, 255, 255, 255,
        -1, 1, 1, 255, 87, 255,
        -1, -1, 1, 87, 67, 255,
        1, -1, 1, 0, 0, 0
};
public FloatBuffer verticesBuffer;

public int indices[] = {
        0, 1, 3,
        1, 2, 3
};
public IntBuffer indicesBuffer;

ByteBuffer bb = ByteBuffer.allocateDirect(vertices.length * 4);
bb.order(ByteOrder.nativeOrder());
verticesBuffer = bb.asFloatBuffer();
verticesBuffer.put(vertices);
verticesBuffer.position(0);

bb = ByteBuffer.allocateDirect(indices.length * 4);
bb.order(ByteOrder.nativeOrder());
indicesBuffer = bb.asIntBuffer();
indicesBuffer.put(indices);
indicesBuffer.position(0);
@Override
public void onDrawFrame(GL10 notUsed) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram(programId);

    verticesBuffer.position(0);
    glEnableVertexAttribArray(vertexPositionHandle);
    glVertexAttribPointer(vertexPositionHandle, 3, GL_FLOAT, false, (POS_SZ + COL_SZ) * FLOAT_SZ, verticesBuffer);

    verticesBuffer.position(POS_SZ);
    glEnableVertexAttribArray(vertexColorHandle);
    glVertexAttribPointer(vertexColorHandle, 3, GL_FLOAT, false, (POS_SZ + COL_SZ) * FLOAT_SZ, verticesBuffer);

    glUniformMatrix4fv(projectionMatrixHandle, 1, false, projectionMatrix, 0);
    glUniformMatrix4fv(viewMatrixHandle, 1, false, viewMatrix, 0);
    glUniformMatrix4fv(modelMatrixHandle, 1, false, modelMatrix, 0);

    glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_INT, indicesBuffer);

    glDisableVertexAttribArray(vertexPositionHandle);
    glDisableVertexAttribArray(vertexColorHandle);
}

着色器:

public static String VertexShader =
    "attribute vec3 a_Position;" +
    "attribute vec3 a_Color;" +
    "" +
    "uniform mat4 u_ProjectionMatrix;" +
    "uniform mat4 u_ViewMatrix;" +
    "uniform mat4 u_ModelMatrix;" +
    "" +
    "varying vec3 v_Color;" +
    "" +
    "void main()" +
    "{" +
        "gl_Position = u_ProjectionMatrix * u_ViewMatrix * u_ModelMatrix * vec4(a_Position, 1);" +
        "v_Color = a_Color;" +
    "}";
public static String FragmentShader =
    "precision mediump float;" +
    "" +
    "varying vec3 v_Color;" +
    "" +
    "void main()" +
    "{" +
        "gl_FragColor = vec4(1, v_Color);" +
    "}";

1 个答案:

答案 0 :(得分:0)

感谢Reto Koradi,我有两个问题......

顶点颜色作为 0-1 的值传入。顶点数组必须是:

public float vertices[] = {
        1.0f,   1.0f,   1.0f,   1.0f,   0.0f,   0.0f,
        -1.0f,  1.0f,   1.0f,   0.0f,   1.0f,   0.0f,
        -1.0f,  -1.0f,  1.0f,   0.0f,   0.0f,   1.0f,
        1.0f,   -1.0f,  1.0f,   0.0f,   0.0f,   0.0f,
};

此外,我在片段着色器中遇到了一个小问题:

"gl_FragColor = vec4(1, v_Color);" +

它是(r,g,b,a),所以它应该是:

"gl_FragColor = vec4(v_Color, 1);" +