GLES20.glVertexAttribPointer / glDrawElements中的“offset”参数是什么,ptr / indices来自哪里?

时间:2011-10-10 05:07:23

标签: android opengl-es opengl-es-2.0

我正在使用Android中的OpenGL ES 2.0,并查看the docs for GLES20我遇到了以下方法:

public static void glDrawElements(
    int mode, int count, int type, Buffer indices)
public static void glDrawElements(
    int mode, int count, int type, int offset)

public static void glVertexAttribPointer(
    int indx, int size, int type, boolean normalized, int stride, Buffer ptr)
public static void glVertexAttribPointer(
    int indx, int size, int type, boolean normalized, int stride, int offset)

采用Buffer对象的两种方法对我有意义,但其他两种方法则没有。他们在哪里获得index / attibute-values(分别),以及offset的偏移是什么? (我假设这两个问题的答案相同。)

2 个答案:

答案 0 :(得分:6)

原型中的偏移意味着您在此调用之前提交了INDEX数组。如果您使用的是VBO(顶点缓冲区对象),则应该使用它。使用glBindBuffer绑定索引缓冲区并在需要时指定偏移量下一个电话。

首先你需要绑定缓冲区(这里是索引缓冲区),你可以指定元素从'offset'开始的位置。

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_resources.element_buffer);
glDrawElements(
    GL_TRIANGLE_STRIP,  /* mode */
    4,                  /* count */
    GL_UNSIGNED_SHORT,  /* type */
    (void*)0            /* element array buffer offset */
);

代表

 public static void glVertexAttribPointer(
int indx, int size, int type, boolean normalized, int stride, int offset)

这意味着您在此调用之前提交顶点缓冲区,并且可以指定缓冲区中应该使用的偏移量。 请查看以下链接以获取更多帮助。 http://duriansoftware.com/joe/An-intro-to-modern-OpenGL.-Chapter-2.3:-Rendering.html

如你所料,两者都有相同的原因:)。希望这有帮助!

更新:您需要创建一个缓冲区来绑定它。这可以通过以下步骤完成。

     glGenBuffers(); // create a buffer object
     glBindBuffer(); // use the buffer
     glBufferData(); // allocate memory in the buffer

选中此链接以创建VBO。 http://www.opengl.org/wiki/Vertex_Buffer_Object

关于偏移类型:偏移量作为指针传递,但参数用于其整数值,因此我们将整数强制转换为void *。

答案 1 :(得分:0)

方法

public static void glDrawElements(
    int mode, int count, int type, int offset)

用于使用VBO索引进行渲染。

offset - 是indexVBO 的偏移量,以字节为单位;

在使用之前,您应该将索引上传到VBO对象:

import static android.opengl.GLES20.*;

private static final int SIZEOF_SHORT = 2;

void fillIndices() {
    int indexAmount = ...;
    int sizeBytes = indexAmount * SIZEOF_SHORT;
    ShortBuffer indicesS = ByteBuffer.allocateDirect(sizeBytes).order(ByteOrder.nativeOrder()).asShortBuffer();
    indicesS.put(getShortIndices(indexAmount));

    indicesS.position(0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeBytes, indicesS, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

short[] getShortIndices(int indexAmount) {
    short[] indices = new short[indexAmount];
    // fill indices here
    return indices;
}

然后你可以绑定它并将它与glDrawElements()

一起使用
public void draw(){
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);
    glDrawElements(GL_TRIANGLE_STRIP, indexCount, GL_UNSIGNED_SHORT, firstIndex * SIZEOF_SHORT);}
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

您可以使用GL_UNSIGNED_BYTE,GL_UNSIGNED_SHORT和GL_UNSIGNED_INT作为索引。