二、定义形状
1.定义一个三角形
OpenGL ES能在3D空间中明确坐标来画出物体。要画一个三角形,首先要定义它的坐标。OpenGL中的典型作法是定义一个浮点集合代表顶点。为了达到好的效率,将这些坐标写入ByteBuffer中,等待传到OpenGL画图管道进行处理。
public class Triangle { private FloatBuffer vertexBuffer; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float triangleCoords[] = { // in counterclockwise order: 0.0f, 0.622008459f, 0.0f, // top -0.5f, -0.311004243f, 0.0f, // bottom left 0.5f, -0.311004243f, 0.0f // bottom right }; // Set color with red, green, blue and alpha (opacity) values float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f }; public Triangle() { // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect( // (number of coordinate values * 4 bytes per float) triangleCoords.length * 4); // use the device hardware's native byte order bb.order(ByteOrder.nativeOrder()); // create a floating point buffer from the ByteBuffer vertexBuffer = bb.asFloatBuffer(); // add the coordinates to the FloatBuffer vertexBuffer.put(triangleCoords); // set the buffer to read the first coordinate vertexBuffer.position(0); } }OpenGL ES假定一个坐标系统[0,0,0](x,y,z)是一个GLSurfaceView边框的中心。[1,1,0]是边框的右上角,[-1,-1,0]是框架的左下角。
需要注意的是这个形状坐标是按照逆时针定义的,绘制的顺序十分重要因为它指明了形状的哪一面在前。
2.定义一个正方形。
定义一个正方形的方法很多,在OpenGL中,通常的做法是绘制两个三角形进行拼凑。
需要定义正方形的四个角的坐标,定义时注意按照逆时针的方向。把定义好的的值放入到ByteBuffer中。为了避免三角形的坐标被定义两次,用drawing list 告诉OpenGL ES graphics pipeline怎么画出这些顶点。
public class Square { private FloatBuffer vertexBuffer; private ShortBuffer drawListBuffer; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float squareCoords[] = { -0.5f, 0.5f, 0.0f, // top left -0.5f, -0.5f, 0.0f, // bottom left 0.5f, -0.5f, 0.0f, // bottom right 0.5f, 0.5f, 0.0f }; // top right private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices public Square() { // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect( // (# of coordinate values * 4 bytes per float) squareCoords.length * 4); bb.order(ByteOrder.nativeOrder()); vertexBuffer = bb.asFloatBuffer(); vertexBuffer.put(squareCoords); vertexBuffer.position(0); // initialize byte buffer for the draw list ByteBuffer dlb = ByteBuffer.allocateDirect( // (# of coordinate values * 2 bytes per short) drawOrder.length * 2); dlb.order(ByteOrder.nativeOrder()); drawListBuffer = dlb.asShortBuffer(); drawListBuffer.put(drawOrder); drawListBuffer.position(0); } }