如何封装 opengl 流程 -- 以为android-opengl-canvas例

https://www.jianshu.com/p/c45d11627c70

 

如何封装 opengl 流程 -- 以为android-opengl-canvas例

如何封装 opengl 流程 -- 以为android-opengl-canvas例 chillingvan 关注

 0.3 2016.11.14 10:05* 字数 625 阅读 4384评论 4喜欢 15

我们在 OpenGL绘制一张图片的流程--以android-openGL-canvas为例
里看到,要使用opengl进行绘制,要实现的流程相当地繁琐,那么我们能不能对其进行封装,使绘制更加简单呢?
接下来还是以 android-openGL-canvas 为例子进行说明。

在 OpenGL绘制一张图片的流程--以android-openGL-canvas为例 里面,提到了实现的3个流程,其中第一和第二个流程是初始化的流程,基本上只需要走一遍,所以我们可以考虑将这两个流程进行封装。
封装后的类就是
EglHelper
GLThread

EglHelper

EglHelper封装了 创建 eglContext 和 创建 surface 的功能,主要的实现代码是:

    public EGLContext start(EGLContext eglContext) {
        if (GLThread.LOG_EGL) {
            Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
        }
        /*
         * Get an EGL instance
         */
        mEgl = (EGL10) EGLContext.getEGL();

        /*
         * Get to the default display.
         */
        mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

        if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
            throw new RuntimeException("eglGetDisplay failed");
        }

        /*
         * We can now initialize EGL for that display
         */
        int[] version = new int[2];
        if (!mEgl.eglInitialize(mEglDisplay, version)) {
            throw new RuntimeException("eglInitialize failed");
        }
        mEglConfig = eglConfigChooser.chooseConfig(mEgl, mEglDisplay);

            /*
            * Create an EGL context. We want to do this as rarely as we can, because an
            * EGL context is a somewhat heavy object.
            */
        mEglContext = eglContextFactory.createContext(mEgl, mEglDisplay, mEglConfig, eglContext);
        if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
            mEglContext = null;
            throwEglException("createContext");
        }
        if (GLThread.LOG_EGL) {
            Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId());
        }

        mEglSurface = null;

        return mEglContext;
    }


    public boolean createSurface(Object surface) {
        if (GLThread.LOG_EGL) {
            Log.w("EglHelper", "createSurface()  tid=" + Thread.currentThread().getId());
        }
        /*
         * Check preconditions.
         */
        if (mEgl == null) {
            throw new RuntimeException("egl not initialized");
        }
        if (mEglDisplay == null) {
            throw new RuntimeException("eglDisplay not initialized");
        }
        if (mEglConfig == null) {
            throw new RuntimeException("mEglConfig not initialized");
        }

        /*
         *  The window size has changed, so we need to create a new
         *  surface.
         */
        destroySurfaceImp();

        /*
         * Create an EGL surface we can render into.
         */
        mEglSurface = eglWindowSurfaceFactory.createWindowSurface(mEgl,
                mEglDisplay, mEglConfig, surface);

        if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
            int error = mEgl.eglGetError();
            if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
                Log.e("EglHelper", "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
            }
            return false;
        }

        /*
         * Before we can issue GL commands, we need to make sure
         * the context is current and bound to a surface.
         */
        if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
            /*
             * Could not make the context current, probably because the underlying
             * SurfaceView surface has been destroyed.
             */
            logEglErrorAsWarning("EGLHelper", "eglMakeCurrent", mEgl.eglGetError());
            return false;
        }

        return true;
    }

可以看到两个方法的参数,说明EGLContext 和 surface 可以从外部传入。也就是说,可以和其它线程共享一个EGLContext,这样就可以使用其它线程绑定的texture了。而surface,是绘制的东西的承载者,可以是TextureView的SurfaceTexture,可以是GLSurfaceView的surfaceHolder,可以是MediaCodec的surface(用于录制视频);所以surface的类型是Object。

GLThread

GLThread是一个继承Thread的类,我们可以不在主线程进行绘制。

主要的运行代码如下:

            while (true) {
                synchronized (sGLThreadManager) {
                    while (true) {
                        ...
                        mEglContext = mEglHelper.start(mEglContext);
                        ...
                        sGLThreadManager.wait();
                        ...
                    }
                } 
                ...
                mEglHelper.createSurface(mSurface))
                ...
                mRenderer.onSurfaceCreated(gl, mEglHelper.getEglConfig()); // OpenGL第三步流程,绘制流程
                ...
                mRenderer.onSurfaceChanged(gl, w, h); // OpenGL第三步流程,绘制流程
                ...
                mRenderer.onDrawFrame(gl); // OpenGL第三步流程,绘制流程
                ...
            }
  • 为了支持持续不断地刷新界面,也就是RENDERMODE_CONTINUOUSLY的renderMode模式,需要在这个线程里while(true)无限循环地运行
  • 为了支持需要时才刷新界面,也就是RENDERMODE_WHEN_DIRTY的renderMode模式,需要sGLThreadManager.wait();
    public void requestRender() {
        synchronized (sGLThreadManager) {
            mRequestRender = true;
            sGLThreadManager.notifyAll();
        }
    }
  • 其中synchronized (sGLThreadManager)的部分是用于线程之间通信,外部线程可以停止和恢复这个线程
    public void onResume() {
        synchronized (sGLThreadManager) {
            if (LOG_PAUSE_RESUME) {
                Log.i("GLThread", "onResume tid=" + getId());
            }
            mRequestPaused = false;
            mRequestRender = true;
            mRenderComplete = false;
            sGLThreadManager.notifyAll();
            while ((!mExited) && mPaused && (!mRenderComplete)) {
                if (LOG_PAUSE_RESUME) {
                    Log.i("Main thread", "onResume waiting for !mPaused.");
                }
                try {
                    sGLThreadManager.wait();
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public void onPause() {
        synchronized (sGLThreadManager) {
            if (LOG_PAUSE_RESUME) {
                Log.i("GLThread", "onPause tid=" + getId());
            }
            mRequestPaused = true;
            sGLThreadManager.notifyAll();
            while ((!mExited) && (!mPaused)) {
                if (LOG_PAUSE_RESUME) {
                    Log.i("Main thread", "onPause waiting for mPaused.");
                }
                try {
                    sGLThreadManager.wait();
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
  • 前文中提及的 EglHelper 和 GLThread 都是由GLSurfaceView里的内部类修改而来的,增加了从外部传入EGLContext和surface等功能,所以此处使用Builder模式,能够定制化地create一个GLThread对象。
    public static class Builder {
        private EGLConfigChooser configChooser;
        private EGLContextFactory eglContextFactory;
        private EGLWindowSurfaceFactory eglWindowSurfaceFactory;
        private GLSurfaceView.Renderer renderer;
        private GLWrapper mGLWrapper = null;
        private int eglContextClientVersion = 2;
        private int debugFlags = 0;
        private int renderMode = RENDERMODE_WHEN_DIRTY;
        private Object surface;
        private EGLContext eglContext = EGL10.EGL_NO_CONTEXT;

        public Builder setSurface(Object surface) {
            this.surface = surface;
            return this;
        }


        public Builder setEGLConfigChooser(boolean needDepth) {
            setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth, eglContextClientVersion));
            return this;
        }


        public Builder setEGLConfigChooser(EGLConfigChooser configChooser) {
            this.configChooser = configChooser;
            return this;
        }

        public Builder setEGLConfigChooser(int redSize, int greenSize, int blueSize,
                                           int alphaSize, int depthSize, int stencilSize) {
            setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
                    blueSize, alphaSize, depthSize, stencilSize, eglContextClientVersion));
            return this;
        }

        public Builder setEglContextFactory(EGLContextFactory eglContextFactory) {
            this.eglContextFactory = eglContextFactory;
            return this;
        }

        public Builder setEglWindowSurfaceFactory(EGLWindowSurfaceFactory eglWindowSurfaceFactory) {
            this.eglWindowSurfaceFactory = eglWindowSurfaceFactory;
            return this;
        }

        public Builder setRenderer(GLSurfaceView.Renderer renderer) {
            this.renderer = renderer;
            return this;
        }

        public Builder setmGLWrapper(GLWrapper mGLWrapper) {
            this.mGLWrapper = mGLWrapper;
            return this;
        }

        public Builder setEglContextClientVersion(int eglContextClientVersion) {
            this.eglContextClientVersion = eglContextClientVersion;
            return this;
        }

        public Builder setDebugFlags(int debugFlags) {
            this.debugFlags = debugFlags;
            return this;
        }

        public Builder setRenderMode(int renderMode) {
            this.renderMode = renderMode;
            return this;
        }

        public void setSharedEglContext(@NonNull EGLContext sharedEglContext) {
            this.eglContext = sharedEglContext;
        }

        public GLThread createGLThread() {
            if (renderer == null) {
                throw new NullPointerException("renderer has not been set");
            }
            if (surface == null && eglWindowSurfaceFactory == null) {
                throw new NullPointerException("surface has not been set");
            }
            if (configChooser == null) {
                configChooser = new SimpleEGLConfigChooser(true, eglContextClientVersion);
            }
            if (eglContextFactory == null) {
                eglContextFactory = new DefaultContextFactory(eglContextClientVersion);
            }
            if (eglWindowSurfaceFactory == null) {
                eglWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
            }
            return new GLThread(configChooser, eglContextFactory, eglWindowSurfaceFactory, renderer, mGLWrapper, debugFlags, renderMode, surface, eglContext);
        }
    }

主要关注点是configChooser, eglContextFactory, eglWindowSurfaceFactory,这3个变量分别定义了EGLConfig, EGLContext, EGLSurface。
以上就是第一第二步流程地封装。至于第三步流程,其实在 OpenGL绘制一张图片的流程--以android-openGL-canvas为例 里也已经引用了相关代码,总结就是封装成了GLES20Canvas ,有兴趣地可以进去查看。

下一篇文章会讲如何使用封装好的GLThread -- 实现一个代替GLSurfaceView的GLTextureView。

上一篇:python – 在matplotlib中显示Surface前面的轮廓


下一篇:微软新专利暗示:多功能Surface Pen触控笔可能问世