EGL既然做平台和OpenGL ES的中间件那EGL做的就肯定是和平台息息相关的事:
- 创建绘图窗口
也就是所谓的FrameBuffer,FrameBuffer可以显示到屏幕上(SurfaceView) - 创建渲染环境(Context上下文)
渲染环境指OpenGL ES的所有项目运行需要的数据结构。如顶点、片段着色器、顶点数据矩阵。
OpenGL渲染一般流程
OpenGL的渲染是基于线程的,我们这里先创建一个GLRenderer类继承于HandlerThread:
public class GLRenderer extends HandlerThread{
private static final String TAG = "GLThread";
private EGLConfig eglConfig = null;
private EGLDisplay eglDisplay = EGL14.EGL_NO_DISPLAY;
private EGLContext eglContext = EGL14.EGL_NO_CONTEXT;
private int program;
private int vPosition;
private int uColor;
public GLRenderer() {
super("GLRenderer");
}
/**
* 创建OpenGL环境
*/
private void createGL(){
// 获取显示设备(默认的显示设备)
eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
// 初始化
int []version = new int[2];
if (!EGL14.eglInitialize(eglDisplay, version,0,version,1)) {
throw new RuntimeException("EGL error "+EGL14.eglGetError());
}
// 获取FrameBuffer格式和能力
int []configAttribs = {
EGL14.EGL_BUFFER_SIZE, 32,
EGL14.EGL_ALPHA_SIZE, 8,
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
EGL14.EGL_SURFACE_TYPE, EGL14.EGL_WINDOW_BIT,
EGL14.EGL_NONE
};
int []numConfigs = new int[1];
EGLConfig[]configs = new EGLConfig[1];
if (!EGL14.eglChooseConfig(eglDisplay, configAttribs,0, configs, 0,configs.length, numConfigs,0)) {
throw new RuntimeException("EGL error "+EGL14.eglGetError());
}
eglConfig = configs[0];
// 创建OpenGL上下文
int []contextAttribs = {
EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
EGL14.EGL_NONE
};
eglContext = EGL14.eglCreateContext(eglDisplay, eglConfig, EGL14.EGL_NO_CONTEXT, contextAttribs,0);
if(eglContext== EGL14.EGL_NO_CONTEXT) {
throw new RuntimeException("EGL error "+EGL14.eglGetError());
}
}
/**
* 销毁OpenGL环境
*/
private void destroyGL(){
EGL14.eglDestroyContext(eglDisplay, eglContext);
eglContext = EGL14.EGL_NO_CONTEXT;
eglDisplay = EGL14.EGL_NO_DISPLAY;
}
@Override
public synchronized void start() {
super.start();
new Handler(getLooper()).post(new Runnable() {
@Override
public void run() {
createGL()