215
CHAPTER 9: User Interface
var positionHandle: Int? = 0
var colorHandle: Int? = 0
val vertexCount =
triangleCoords.size / COORDS_PER_VERTEX
val vertexStride = COORDS_PER_VERTEX * 4
// 4
bytes per vertex
companion object {
// number of coordinates per vertex
internal val COORDS_PER_VERTEX = 3
internal var triangleCoords =
floatArrayOf( // in counterclockwise order:
0.0f, 0.6f, 0.0f, // top
-0.5f, -0.3f, 0.0f, // bottom left
0.5f, -0.3f, 0.0f //
bottom right
)
}
Inside the class’s init block, the shaders get loaded and initialized, and a vertex buffer gets
prepared.
init {
val vertexShader = MyGLRenderer.loadShader(
GLES20.GL_VERTEX_SHADER,
vertexShaderCode)
val fragmentShader = MyGLRenderer.loadShader(
GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode)
// create
empty OpenGL ES Program
program = GLES20.glCreateProgram()
// add the vertex shader to program
GLES20.glAttachShader(program!!, vertexShader)
// add the fragment shader to program
GLES20.glAttachShader(program!!, fragmentShader)
// creates OpenGL
ES program executables
GLES20.glLinkProgram(program!!)
// initialize vertex byte buffer for shape
// coordinates
val bb = ByteBuffer.allocateDirect(
// (4 bytes per float)
triangleCoords.size * 4)
// use the device hardware's
native byte order
bb.order(ByteOrder.nativeOrder())
// create a floating point buffer from bb
vertexBuffer = bb.asFloatBuffer()
// add the coordinates to the buffer