为了在Java线程进行OpenGL调用,需要为java线程初始化OpenGL环境,initOpenGL函数展示了初始化OpenGL环境的过程。在setupOpenGL方法中,在线程上先执行该调用即可。Java代码示例如下:
1 package com.thornbirds.unity; 2 3 public class PluginTexture { 4 5 private EGLDisplay mEGLDisplay; 6 private EGLConfig mEglConfig; 7 private EGLContext mEglContext; 8 private EGLSurface mEglSurface; 9 10 private void glLogE(String msg) { 11 Log.e(TAG, msg + ", err=" + GLES10.glGetError()); 12 } 13 14 private void initOpenGL() { 15 mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); 16 if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) { 17 glLogE("eglGetDisplay failed"); 18 return; 19 } 20 21 int[] version = new int[2]; 22 if (!EGL14.eglInitialize(mEGLDisplay, version, 0, version, 1)) { 23 mEGLDisplay = null; 24 glLogE("eglInitialize failed"); 25 return; 26 } 27 28 int[] eglConfigAttribList = new int[]{ 29 EGL14.EGL_RED_SIZE, 8, 30 EGL14.EGL_GREEN_SIZE, 8, 31 EGL14.EGL_BLUE_SIZE, 8, 32 EGL14.EGL_ALPHA_SIZE, 8, 33 EGL14.EGL_NONE 34 }; 35 int[] numEglConfigs = new int[1]; 36 EGLConfig[] eglConfigs = new EGLConfig[1]; 37 if (!EGL14.eglChooseConfig(mEGLDisplay, eglConfigAttribList, 0, eglConfigs, 0, 38 eglConfigs.length, numEglConfigs, 0)) { 39 glLogE("eglGetConfigs failed"); 40 return; 41 } 42 mEglConfig = eglConfigs[0]; 43 44 int[] eglContextAttribList = new int[]{ 45 EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, 46 EGL14.EGL_NONE 47 }; 48 mEglContext = EGL14.eglCreateContext(mEGLDisplay, mEglConfig, EGL14.EGL_NO_CONTEXT, 49 eglContextAttribList, 0); 50 if (mEglContext == EGL14.EGL_NO_CONTEXT) { 51 glLogE("eglCreateContext failed"); 52 return; 53 } 54 55 int[] surfaceAttribList = { 56 EGL14.EGL_WIDTH, 64, 57 EGL14.EGL_HEIGHT, 64, 58 EGL14.EGL_NONE 59 }; 60 // Java线程不进行实际绘制,因此创建PbufferSurface而非WindowSurface 61 mEglSurface = EGL14.eglCreatePbufferSurface(mEGLDisplay, mEglConfig, surfaceAttribList, 0); 62 if (mEglSurface == EGL14.EGL_NO_SURFACE) { 63 glLogE("eglCreatePbufferSurface failed"); 64 return; 65 } 66 67 if (!EGL14.eglMakeCurrent(mEGLDisplay, mEglSurface, mEglSurface, mEglContext)) { 68 glLogE("eglMakeCurrent failed"); 69 return; 70 } 71 GLES20.glFlush();