矩阵变换类
package test.com.opengles7_1;三角形绘制类
import android.opengl.Matrix;
/**
* Created by hbin on 2016/8/15.
*/
public class MatrixState {
private static float[] mProjMatrix = new float[16];//4x4矩阵 投影用
private static float[] mVMatrix = new float[16];//摄像机位置朝向9参数矩阵
private static float[] mMVPMatrix;//最后起作用的总变换矩阵
static float[] mMMatrix=new float[16] ;//具体物体的移动旋转矩阵
public static void setInitStack()//获取不变换初始矩阵
{
Matrix.setRotateM(mMMatrix, 0, 0, 1, 0, 0);
}
public static void translate(float x,float y,float z)//设置沿xyz轴移动
{
Matrix.translateM(mMMatrix, 0, x, y, z);
}
public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴转动
{
Matrix.rotateM(mMMatrix,0,angle,x,y,z);
}
//设置摄像机
public static void setCamera
(
float cx,//摄像机位置x
float cy, //摄像机位置y
float cz, //摄像机位置z
float tx, //摄像机目标点x
float ty, //摄像机目标点y
float tz, //摄像机目标点z
float upx, //摄像机UP向量X分量
float upy, //摄像机UP向量Y分量
float upz //摄像机UP向量Z分量
)
{
Matrix.setLookAtM
(
mVMatrix,
0,
cx,
cy,
cz,
tx,
ty,
tz,
upx,
upy,
upz
);
}
//设置透视投影参数
public static void setProjectFrustum
(
float left,//near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near,//near面距离
float far //far面距离
)
{
Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//获取具体物体的总变换矩阵
public static float[] getFinalMatrix()
{
mMVPMatrix=new float[16];
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
return mMVPMatrix;
}
}
package test.com.opengles7_1;
import android.opengl.GLES20;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
/**
* Created by hbin on 2016/8/15.
* 纹理三角形
*/
public class Triangle {
int mProgram;//自定义渲染管线程序id
int muMVPMatrixHandle;//总变换矩阵引用id
int maPositionHandle; //顶点位置属性引用id
int maTexCoorHandle; //顶点纹理坐标属性引用id
String mVertexShader;//顶点着色器
String mFragmentShader;//片元着色器
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mTexCoorBuffer;//顶点纹理坐标数据缓冲
int vCount=0;
float xAngle=0;//绕x轴旋转的角度
float yAngle=0;//绕y轴旋转的角度
float zAngle=0;//绕z轴旋转的角度
public Triangle(MySurfaceView mv)
{
//初始化顶点坐标与着色数据
initVertexData();
//初始化着色器
initShader(mv);
}
//初始化顶点坐标与着色数据的方法
public void initVertexData()
{
vCount=3;
final float UNIT_SIZE=0.15F;
float vertices[]=new float[]
{
0*UNIT_SIZE,11*UNIT_SIZE,0,
-11*UNIT_SIZE,-11*UNIT_SIZE,0,
11*UNIT_SIZE,-11*UNIT_SIZE,0
};
//创建顶点坐标数据缓冲
ByteBuffer vbb=ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer=vbb.asFloatBuffer();
mVertexBuffer.put(vertices);//向缓冲区放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//顶点纹理坐标数据的初始化
float texCoor[]=new float[]//顶点颜色值数组,每个顶点4个色彩值RGBA
{
0.5f,0,
0,1,
1,1
};
//创建顶点纹理坐标数据缓冲
ByteBuffer cbb=ByteBuffer.allocateDirect(texCoor.length*4);
cbb.order(ByteOrder.nativeOrder());
mTexCoorBuffer=cbb.asFloatBuffer();
mTexCoorBuffer.put(texCoor);
mTexCoorBuffer.position(0);
}
//初始化着色器
public void initShader(MySurfaceView mv)
{
//加载顶点着色器的脚本内容
mVertexShader=ShaderUtil.loadFromAssetsFile("vertex.sh", mv.getResources());
//加载片元着色器的脚本内容
mFragmentShader=ShaderUtil.loadFromAssetsFile("frag.sh", mv.getResources());
//基于顶点着色器与片元着色器创建程序
mProgram = ShaderUtil.createProgram(mVertexShader, mFragmentShader);
//获取程序中顶点位置属性引用id
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点纹理坐标属性引用id
maTexCoorHandle= GLES20.glGetAttribLocation(mProgram, "aTexCoor");
//获取程序中总变换矩阵引用id
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
}
public void drawSelf(int texId)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
MatrixState.setInitStack();
//设置沿Z轴正向位移1
MatrixState.translate(0,0,1);
//设置绕y轴旋转
MatrixState.rotate(yAngle,0,1,0);
//设置绕Z轴旋转
MatrixState.rotate(zAngle,0,0,1);
//设置绕x轴旋转
MatrixState.rotate(xAngle,1,0,0);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle,1,false,MatrixState.getFinalMatrix(),0);
//为画笔指定顶点位置数据
GLES20.glVertexAttribPointer(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//为画笔指定顶点纹理坐标数据
GLES20.glVertexAttribPointer(
maTexCoorHandle,
2,
GLES20.GL_FLOAT,
false,
2*4,
mTexCoorBuffer
);
//允许顶点位置数据数组
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maTexCoorHandle);
//绑定纹理
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId);
//绘制纹理矩形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
}
surfaceview绘制类
package test.com.opengles7_1;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.view.MotionEvent;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by hbin on 2016/8/15.
*/
public class MySurfaceView extends GLSurfaceView {
private final float TOUCH_SCALE_FACTOR=180.0f/320;//角度缩放比例
private SceneRenderer mRenderer;//场景渲染器
private float mPreviousY;//上次的触控位置Y坐标
private float mPreviousX;//上次的触控位置X坐标
int textureId;//系统分配的纹理id
public MySurfaceView(Context context) {
super(context);
this.setEGLContextClientVersion(2);
mRenderer=new SceneRenderer();
setRenderer(mRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
@Override
public boolean onTouchEvent(MotionEvent e){
float y=e.getY();
float x=e.getX();
switch (e.getAction()){
case MotionEvent.ACTION_MOVE:
float dy=y-mPreviousY;
float dx=x-mPreviousX;
mRenderer.texRect.yAngle+=dx*TOUCH_SCALE_FACTOR;
mRenderer.texRect.zAngle+=dy*TOUCH_SCALE_FACTOR;
}
mPreviousY=y;
mPreviousX=x;
return true;
}
private class SceneRenderer implements GLSurfaceView.Renderer{
Triangle texRect;//纹理矩形
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//设置屏幕背景色
GLES20.glClearColor(0.5f,0.5f,0.5f,1.0f);
texRect=new Triangle(MySurfaceView.this);
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
initTexture();
//关闭背面剪裁
GLES20.glDisable(GLES20.GL_CULL_FACE);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//设置视窗大小及位置
GLES20.glViewport(0,0,width,height);
//计算宽高比
float ratio=(float)width/height;
//生成透视投影矩阵
MatrixState.setProjectFrustum(-ratio,ratio,-1,1,1,10);
//生成摄像机9参数位置矩阵
MatrixState.setCamera(0,0,3,0f,0f,0f,0f,1.0f,0f);
}
@Override
public void onDrawFrame(GL10 gl) {
//清除深度缓冲与颜色缓冲
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
//绘制纹理矩形
texRect.drawSelf(textureId);
}
}
public void initTexture()//textureId
{
//生成纹理id
int[] textures=new int[1];
GLES20.glGenTextures
(
1,//产生的纹理id数量
textures,//纹理id的数组
0 //偏移量
);
textureId=textures[0];
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureId);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
//通过输入流加载图片
AssetManager am=getResources().getAssets();
InputStream is=null;;
Bitmap bitmap=null;
try {
// is=am.open("wall.png");
Resources res=this.getContext().getResources();
is=res.openRawResource(R.raw.wall);
bitmap= BitmapFactory.decodeStream(is);
}catch (Exception ex){
ex.printStackTrace();
}
finally {
try {
is.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
//实际加载纹理
GLUtils.texImage2D
(
GLES20.GL_TEXTURE_2D,//纹理类型,在OpenGL ES中必须为GL10.GL_TEXTURE_2D
0,//纹理的层次,0表示基本图像层,可以理解为直接贴图
bitmap,//纹理图像
0 //纹理边框尺寸
);
bitmap.recycle(); //纹理加载成功后释放图片
}
}
着色语言加载类
package test.com.opengles7_1;效果图
import android.content.res.Resources;
import android.opengl.GLES20;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* Created by hbin on 2016/8/15.
* 加载顶点Shader与片元Shader的工具类
*/
public class ShaderUtil {
//加载制定shader的方法
public static int loadShader
(
int shaderType, //shader的类型 GLES20.GL_VERTEX_SHADER GLES20.GL_FRAGMENT_SHADER
String source //shader的脚本字符串
)
{
//创建一个新shader
int shader = GLES20.glCreateShader(shaderType);
//若创建成功则加载shader
if (shader != 0)
{
//加载shader的源代码
GLES20.glShaderSource(shader, source);
//编译shader
GLES20.glCompileShader(shader);
//存放编译成功shader数量的数组
int[] compiled = new int[1];
//获取Shader的编译情况
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0)
{//若编译失败则显示错误日志并删除此shader
Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":");
Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
//创建shader程序的方法
public static int createProgram(String vertexSource, String fragmentSource)
{
//加载顶点着色器
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0)
{
return 0;
}
//加载片元着色器
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0)
{
return 0;
}
//创建程序
int program = GLES20.glCreateProgram();
//若程序创建成功则向程序中加入顶点着色器与片元着色器
if (program != 0)
{
//向程序中加入顶点着色器
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
//向程序中加入片元着色器
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
//链接程序
GLES20.glLinkProgram(program);
//存放链接成功program数量的数组
int[] linkStatus = new int[1];
//获取program的链接情况
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
//若链接失败则报错并删除程序
if (linkStatus[0] != GLES20.GL_TRUE)
{
Log.e("ES20_ERROR", "Could not link program: ");
Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
//检查每一步操作是否有错误的方法
public static void checkGlError(String op)
{
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR)
{
Log.e("ES20_ERROR", op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
//从sh脚本中加载shader内容的方法
public static String loadFromAssetsFile(String fname,Resources r)
{
String result=null;
try
{
InputStream in=r.getAssets().open(fname);
int ch=0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch=in.read())!=-1)
{
baos.write(ch);
}
byte[] buff=baos.toByteArray();
baos.close();
in.close();
result=new String(buff,"UTF-8");
result=result.replaceAll("\\r\\n","\n");
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}
完整项目下载地址
http://download.csdn.net/detail/hb707934728/9604389