在openGL中更改三角坐标

时间:2014-07-03 15:57:34

标签: android c++ buffer opengl-es-2.0

我的draw()课程中有一个Triangle方法,如下所示:


protected void draw() {
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "a_Position");
        mColorHandle = GLES20.glGetAttribLocation(mProgram, "a_Color");

        GLES20.glUseProgram(mProgram);

        vertexBuffer.position(0);
        GLES20.glVertexAttribPointer(mPositionHandle, 2, GLES20.GL_FLOAT, false,
        0, vertexBuffer);

        GLES20.glEnableVertexAttribArray(mPositionHandle);

        vertexBuffer.position(6);
        GLES20.glVertexAttribPointer(mColorHandle, 4, GLES20.GL_FLOAT, false,
        0, vertexBuffer); // NOTE: A stride of 0 since the data is packed.

        GLES20.glEnableVertexAttribArray(mColorHandle);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);

        GLES20.glDisableVertexAttribArray(mPositionHandle);
        GLES20.glDisableVertexAttribArray(mColorHandle);
}

draw()方法在onDrawFrame()中不断被调用,因此我的三角形不断被绘制。我希望能够改变三角形的坐标。注意:我正在初始化我的顶点缓冲区,如下所示:


private void init() {
        triangleVertexData = concat(triangleCoords, color);

        ByteBuffer bb = ByteBuffer.allocateDirect(triangleVertexData.length * 4);

        bb.order(ByteOrder.nativeOrder());

        vertexBuffer = bb.asFloatBuffer();

        vertexBuffer.put(triangleVertexData);

        vertexBuffer.position(0);
}

我的triangleVertexData格式为 {x,y,x,y,x,y,r,g,b,a,r,g,b,a,r,g,b ,a}


我的问题是,如何实施changeCoordinates(float[] p1, float[] p2, float[] p3);方法?

到目前为止,这是我提出的:

protected void changeCoords(float[] p1, float[] p2, float[] p3) {

        float[] coords = new float[] {p1[0], p1[1],
                                    p2[0], p2[1],
                                    p3[0], p3[1]};

        triangleCoords = coords;

        triangleVertexData = concat(triangleCoords, color);

        vertexBuffer.clear();

        vertexBuffer.put(triangleVertexData);

        vertexBuffer.position(0);
    }

然而这不起作用,随机时间我在put()行上得到一个BufferOverflowException,我不明白为什么。

2 个答案:

答案 0 :(得分:1)

我认为异常的原因是,方法changeCoords()draw()不同步。请注意,您要在vertexBuffer方法中修改draw()vertexBuffer.position(6);。如果在此之后安排changeCoords(),则会出现问题。

回复评论:

是。在vertexBuffer.put(triangleVertexData)方法中执行语句changeCoords之前,如果draw()被调用,则remaining中只会有vertexBuffer个。{/ p>

您可以尝试以下方法之一:

  • 在离开vertexBuffer方法之前将draw的位置设置为零。可能就在..glVertexAttribPointer(mColorHandle, 4,...陈述之后。
  • 为每个 - 顶点和颜色使用单独的缓冲区。

其他事情可能我应该注意..

  • 尝试重新使用数组。不要经常分配它们。
  • 如果符合您的需要,请查看System.arraycopy复制数组
  • 请务必确保您不想使用Jin提及的translateMscaleM个实用程序

答案 1 :(得分:0)

我不知道为什么你会试图以这种方式移动三角形。 android.opengl.Matrix中提供的线性代数方法完全取决于您尝试做的事情。

要翻译三角形(或任何一组顶点),请:

 Matrix.translateM(float[] m, int mOffset, float x, float y, float z);

并且在不同方向上拉伸顶点它是一个缩放操作:

 Matrix.scaleM(float[] m, int mOffset, float x, float y, float z);

即使您要实现坐标更改方法,也只能按照指定triangleVertexData的方式指定顶点/颜色。