Drawing a triangle OpenGL ES for Android

Here Insert Picture Description
Android triangle is drawn in the vertex shader is as follows:

attribute vec4 vPosition;
void main() {
    gl_Position = vPosition;
}

vPosition vertex, passed by the application.

Fragment shader code is as follows:

precision mediump float;
void main()
{
  gl_FragColor = vec4(1,0,0,1);
}

Create a program:

private fun createProgram() {
            var vertexCode =
                AssetsUtils.readAssetsTxt(
                    context = context,
                    filePath = "glsl/triangle_vertex.glsl"
                )
            var fragmentCode =
                AssetsUtils.readAssetsTxt(
                    context = context,
                    filePath = "glsl/triangle_fragment.glsl"
                )
            mProgramHandle = GLTools.createAndLinkProgram(vertexCode, fragmentCode)
        }

triangle_vertex.glsl vertex shader and triangle_vertex.glsl represent a fragment shader and files stored at assets / glsl directory, readAssetsTxt assets directory common method to read the file.

Get a handle parameters:

vPositionLoc = GLES20.glGetAttribLocation(mProgramHandle, "vPosition")

Vertex data initialization line code is as follows:

var vertexBuffer = GLTools.array2Buffer(
            floatArrayOf(
                0.0f, 0.5f, 0.0f, // top
                -0.5f, -0.5f, 0.0f, // bottom left
                0.5f, -0.5f, 0.0f  // bottom right
            )
        )

draw:

override fun onDrawFrame(p0: GL10?) {
            GLES20.glUseProgram(mProgramHandle)

            vertexBuffer.position(0)
            GLES20.glEnableVertexAttribArray(vPositionLoc)
            GLES20.glVertexAttribPointer(vPositionLoc, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer)
            
            GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3)
        }

GL_TRIANGLES representation drawing triangles.

Drawing triangle there are 3 ways:

  • GL_TRIANGLES: 3 vertices drawing a triangle, the apex of the triangle, even if repeated, should also be declared in the vertex array. If there are six vertices, then a triangle composed of 2,3, 4,5,6 to form a triangle.
  • GL_TRIANGLE_STRIP: two front vertices of a triangle, and a subsequent vertices of a triangle Further, if there are six vertices, the composition has a vertex of a triangle (1,2,3), (2,3,4), ( 3,4,5), (4,5,6) a total of four triangles, so there are N vertices, the triangle is drawn with a number N-2.
  • GL_TRIANGLE_FAN: a first point to the central point, the other vertices as an edge point of the fan to draw the composition of adjacent triangles, if there are six vertices, vertex of a triangle with a composition (2,3), (1,3, 4), (1,4,5), (1,5,6) a total of four triangles.

Read More:

Published 123 original articles · won praise 68 · Views 300,000 +

Guess you like

Origin blog.csdn.net/mengks1987/article/details/104105069