Api Demo - .graphics(24)>>Cube

阅读更多
package com.example.android.apis.graphics;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import javax.microedition.khronos.opengles.GL10;

/**
 * A vertex shaded cube.
 */
class Cube
{
    public Cube()
    {
        int one = 0x10000;
      /*
       * 0x10000是出于OPENGL前期内存节约的考虑, 以INT型模拟FLOAT型来表示, 0x 0001 0000 前面4位表示小数点前,后4位表示小数点后,
       *所以0x10000表示浮点数的1。如果你用的是FloatBuffer,就可以知道此处应该写1.0
       */
        int vertices[] = {//顶点数组
                -one, -one, -one,
                one, -one, -one,
                one,  one, -one,
                -one,  one, -one,
                -one, -one,  one,
                one, -one,  one,
                one,  one,  one,
                -one,  one,  one,
        };

        int colors[] = {//颜色数组
                0,    0,    0,  one,
                one,    0,    0,  one,
                one,  one,    0,  one,
                0,  one,    0,  one,
                0,    0,  one,  one,
                one,    0,  one,  one,
                one,  one,  one,  one,
                0,  one,  one,  one,
        };

        byte indices[] = {//索引数组,即指定哪3个点构成一个面(三角形)
                0, 4, 5,    0, 5, 1,
                1, 5, 6,    1, 6, 2,
                2, 6, 7,    2, 7, 3,
                3, 7, 4,    3, 4, 0,
                4, 7, 6,    4, 6, 5,
                3, 0, 1,    3, 1, 2
        };


        ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);//建立顶点缓冲 int类型占8个字节,Byte占2个所以*4;
        vbb.order(ByteOrder.nativeOrder());//设置为本地平台字节顺序。
        mVertexBuffer = vbb.asIntBuffer();//将Byte缓冲转为int缓冲。
        mVertexBuffer.put(vertices);//放入顶点数组
        mVertexBuffer.position(0);//置0;

        ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);//颜色缓冲
        cbb.order(ByteOrder.nativeOrder());
        mColorBuffer = cbb.asIntBuffer();
        mColorBuffer.put(colors);
        mColorBuffer.position(0);

        mIndexBuffer = ByteBuffer.allocateDirect(indices.length);//索引缓冲。
        mIndexBuffer.put(indices);
        mIndexBuffer.position(0);
    }

    public void draw(GL10 gl)
    {
        gl.glFrontFace(gl.GL_CW);//确定正面。
        gl.glVertexPointer(3, gl.GL_FIXED, 0, mVertexBuffer);//为画笔指定顶点坐标
        gl.glColorPointer(4, gl.GL_FIXED, 0, mColorBuffer);//为画笔指定顶点颜色
        gl.glDrawElements(gl.GL_TRIANGLES, 36, gl.GL_UNSIGNED_BYTE, mIndexBuffer);//索引法画图。
    }

    private IntBuffer   mVertexBuffer;
    private IntBuffer   mColorBuffer;
    private ByteBuffer  mIndexBuffer;
}

 

你可能感兴趣的:(android,graphics)