在一个glDrawElements()中绘制多个对象

时间:2016-11-02 22:20:11

标签: android opengl-es-2.0

我正在使用这个2D教程练习OpenGL ES2.0中的基本知识: http://androidblog.reindustries.com/a-real-opengl-es-2-0-2d-tutorial-part-2/

基本上它只是绘制一个带纹理的矩形。 现在我想在不同位置的一个glDrawElements()调用中绘制多个rects但具有相同的纹理。所以我向verticesindices数组添加了更多项目。然而纹理坐标(uvs数组)对于每个矩形是相同的,并且通过复制相同的值来拉伸它是没有意义的。我可以以某种方式重用它,或者可能在着色器代码中的某处将它设置为常量吗?

顶点着色器:

uniform mat4 uMVPMatrix;
attribute vec4 vPosition;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
  gl_Position = uMVPMatrix * vPosition;
  v_texCoord = a_texCoord;
}

片段着色器:

precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D s_texture;
void main() {
  gl_FragColor = texture2D( s_texture, v_texCoord );
}

数组(用于缓冲区):

vertices = new float[]
{  10.0f, 200f, 0.0f,
   10.0f, 100f, 0.0f,
   100f, 100f, 0.0f,
   100f, 200f, 0.0f,
};

indices = new short[] {0, 1, 2, 0, 2, 3};

uvs = new float[] {
      0.0f, 0.0f,
      0.0f, 1.0f,
      1.0f, 1.0f,
      1.0f, 0.0f
  };

渲染代码:

private void Render() {
  GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

  int mPositionHandle = GLES20.glGetAttribLocation(program, "vPosition");
  GLES20.glEnableVertexAttribArray(mPositionHandle);
  GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);

  int mTexCoordLoc = GLES20.glGetAttribLocation(program, "a_texCoord" );
  GLES20.glEnableVertexAttribArray ( mTexCoordLoc );
  GLES20.glVertexAttribPointer ( mTexCoordLoc, 2, GLES20.GL_FLOAT, false, 0, uvBuffer);

  int mtrxhandle = GLES20.glGetUniformLocation(program, "uMVPMatrix");
  GLES20.glUniformMatrix4fv(mtrxhandle, 1, false, m, 0);

  int mSamplerLoc = GLES20.glGetUniformLocation (program, "s_texture" );
  GLES20.glUniform1i ( mSamplerLoc, 0);

  GLES20.glDrawElements(GLES20.GL_TRIANGLES, indices.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

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

0 个答案:

没有答案