1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.example.android.opengl; 17 18 import java.nio.ByteBuffer; 19 import java.nio.ByteOrder; 20 import java.nio.FloatBuffer; 21 22 import javax.microedition.khronos.opengles.GL10; 23 24 /** 25 * A two-dimensional triangle for use as a drawn object in OpenGL ES 1.0/1.1. 26 */ 27 public class Triangle { 28 29 private final FloatBuffer vertexBuffer; 30 31 // number of coordinates per vertex in this array 32 static final int COORDS_PER_VERTEX = 3; 33 static float triangleCoords[] = { 34 // in counterclockwise order: 35 0.0f, 0.622008459f, 0.0f,// top 36 -0.5f, -0.311004243f, 0.0f,// bottom left 37 0.5f, -0.311004243f, 0.0f // bottom right 38 }; 39 40 float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 0.0f }; 41 42 /** 43 * Sets up the drawing object data for use in an OpenGL ES context. 44 */ Triangle()45 public Triangle() { 46 // initialize vertex byte buffer for shape coordinates 47 ByteBuffer bb = ByteBuffer.allocateDirect( 48 // (number of coordinate values * 4 bytes per float) 49 triangleCoords.length * 4); 50 // use the device hardware's native byte order 51 bb.order(ByteOrder.nativeOrder()); 52 53 // create a floating point buffer from the ByteBuffer 54 vertexBuffer = bb.asFloatBuffer(); 55 // add the coordinates to the FloatBuffer 56 vertexBuffer.put(triangleCoords); 57 // set the buffer to read the first coordinate 58 vertexBuffer.position(0); 59 } 60 61 /** 62 * Encapsulates the OpenGL ES instructions for drawing this shape. 63 * 64 * @param gl - The OpenGL ES context in which to draw this shape. 65 */ draw(GL10 gl)66 public void draw(GL10 gl) { 67 // Since this shape uses vertex arrays, enable them 68 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); 69 70 // draw the shape 71 gl.glColor4f( // set color: 72 color[0], color[1], 73 color[2], color[3]); 74 gl.glVertexPointer( // point to vertex data: 75 COORDS_PER_VERTEX, 76 GL10.GL_FLOAT, 0, vertexBuffer); 77 gl.glDrawArrays( // draw shape: 78 GL10.GL_TRIANGLES, 0, 79 triangleCoords.length / COORDS_PER_VERTEX); 80 81 // Disable vertex array drawing to avoid 82 // conflicts with shapes that don't use it 83 gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); 84 } 85 } 86