android - 确定 Android OpenGLES 中的最大/最小纹理大小限制

标签 android opengl-es android-activity glsurfaceview

我被指派为这个 Objective C GPUImage Framework 创建一个开源 Java 端口以便它可以在 Android 应用程序中使用。我将尽可能地重新创建它,所有变量名、函数名等都保持不变。我正处于开始阶段,我正在尝试移植 GPUImageOpenGLESContext.h 和 GPUImageOpenGLESContext.m(抱歉,会提供链接,但作为新用户我无法添加更多链接)。

我对这些方法有困难

+ (GLint)maximumTextureSizeForThisDevice;
{
    GLint maxTextureSize; 
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
    return maxTextureSize;
}

+ (GLint)maximumTextureUnitsForThisDevice;
{
    GLint maxTextureUnits; 
    glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
    return maxTextureUnits;
}

似乎在 Objective C 中,您可以简单地调用这些方法,但在 Java 中则不能。我做了一些搜索,发现大多数人说使用 GLSurfaceView,但这需要一个 Activity ,对吗?当我发现这个时我非常兴奋Get Maximum OpenGL ES 2.0 Texture Size Limit on Android ,但响应声称该代码不起作用。

所以,我的问题是,如何在不是 Activity 的类中获取最小和最大纹理?使用 GLSurfaceView?

如果有任何关于如何将其移植过来的建议,我也将不胜感激。我从未将任何东西从 Objective C 移植到 Java,所以任何建议都将不胜感激!

如果有帮助,这是我当前的代码:

public class GPUImageOpenGLESContext 
{
    private static GPUImageOpenGLESContext instance = null;

    EGLContext context;

    protected GPUImageOpenGLESContext()
    {
        // This is a protected empty method
        // that exists only to prevent
        // this singleton object from
        // multiple instantiation

        return;
    }

    public enum GPUImageRotationMode { 
            kGPUImageNoRotation, kGPUImageRotateLeft, kGPUImageRotateRight, kGPUImageFlipVertical,
            kGPUImageFlipHorizontal, kGPUImageRotateRightFlipVertical, kGPUImageRotate180
    }

    public GPUImageRotationMode GPUImageRotationSwapsWidthAndHeight(GPUImageRotationMode rotation)
    {
        // TODO: Implement GPUImageRotationSwapsWidthAndHeight macro as method
        //rotation = ((rotation) == kGPUImageRotateLeft || (rotation) == kGPUImageRotateRight || (rotation) == kGPUImageRotateRightFlipVertical)
        return rotation;
    }

    public static GPUImageOpenGLESContext sharedImageProcessingOpenGLESContext()
    {
        if (instance == null)
        {
            instance = new GPUImageOpenGLESContext();
        }
        return instance;
    }

    public static void useImageProcessingContext()
    {
         EGLContext imageProcessingContext = GPUImageOpenGLESContext.sharedImageProcessingOpenGLESContext().context;
         if (EGLContext.getEGL() != imageProcessingContext)
         {
             // In Objective C, this call would be here:
             // [EAGLContext setCurrentContext:imageProcessingContext]

             // Cannot figure out how to handle this.  For now, throws an exception.
             throw new RuntimeException("useImageProcessingContext not equal to EGLContext");
         }

         return;
    }

    public static int maximumTextureSizeForThisDevice()
    {
        int[] maxTextureSize = new int[1];

        // TODO: See if you can use gl. without an activity
        //GL10 gl = new GL10();
        //EGL gl = EGLContext.getEGL();

        //gl.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);

        return maxTextureSize[0];
    }

    public static int maximumTextureUnitsForThisDevice()
    {
        // TODO: Implement maximumTextureUnitsForThisDevice();
        return -1;
    }

    public static CGSize sizeThatFitsWithinATextureForSize(CGSize inputSize)
    {
        int maxTextureSize = maximumTextureSizeForThisDevice();

        if ((inputSize.width < maxTextureSize) && (inputSize.height < maxTextureSize))
        {
            return inputSize;
        }

        CGSize adjustedSize = new CGSize();
        if (inputSize.width > inputSize.height)
        {
            adjustedSize.width = (float)maxTextureSize;
            adjustedSize.height = ((float)maxTextureSize / inputSize.width) * inputSize.height;
        }
        else
        {
            adjustedSize.height = (float)maxTextureSize;
            adjustedSize.width = ((float)maxTextureSize / inputSize.height) * inputSize.width;
        }

        return adjustedSize;
    }

    public EGLContext getContext()
    {
        if (context == null)
        {
            // TODO: Implement getContext()
        }
    }

    public interface GPUImageInput
    {
        public void newFrameReadyAtTime(Time frameTime);
        public void setInputTextureAtIndex(int newInputTexture, int textureIndex);
        public int nextAvailableTextureIndex();
        public void setInputSizeAtIndex(CGSize newSize, int textureIndex);
        public void setInputRotationAtIndex(GPUImageRotationMode newInputRotation, int textureIndex);
        public CGSize maximumOutputSize();
        public void endProcessing();
        public boolean shouldIgnoreUpdatesToThisTarget();
    }
}

最佳答案

我知道这是一篇旧帖子,但您的问题是您没有正确初始化 EGLContext。

通常您希望使用 GLSurfaceView 或 TextureView 将您的 GL 内容实际包含在 View 层次结构中。 GLSurfaceView 将为您处理很多事情,例如正确创建 EGLContext 和管理渲染线程。 TextureView 需要更多的手动工作。

一旦您通过这些方式中的任何一种获得了上下文,您就可以使用:

GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, size, 0);

假设您已经绑定(bind)了 OpenGL ES 2.0 API。首先确保您已正确创建 EGLContext 并可以执行 EGL 和 GLES 调用,然后您应该能够查询最大纹理大小。

您可以在此处(https://groups.google.com/d/msg/android-developers/U5RXFGpAHPE/IqHeIeGXhr0J)查看 Romain Guy 关于使用 TextureView 的帖子,就像使用 GLSurfaceView 一样查看有关管理您自己的 EGLContext 的具体细节:

GLSurfaceView handles GL setup for you, which TextureView will not do. A TextureView can be used as the native window when you create an EGL surface. Here is an example (the interesting part is the call to eglCreateWindowSurface()):

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
    mRenderThread = new RenderThread(getResources(), surface);
    mRenderThread.start();
}

private static class RenderThread extends Thread {
    private static final String LOG_TAG = "GLTextureView";

    static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
    static final int EGL_OPENGL_ES2_BIT = 4;

    private volatile boolean mFinished;

    private final Resources mResources;
    private final SurfaceTexture mSurface;

    private EGL10 mEgl;
    private EGLDisplay mEglDisplay;
    private EGLConfig mEglConfig;
    private EGLContext mEglContext;
    private EGLSurface mEglSurface;
    private GL mGL;

    RenderThread(Resources resources, SurfaceTexture surface) {
        mResources = resources;
        mSurface = surface;
    }

    private static final String sSimpleVS =
            "attribute vec4 position;\n" +
            "attribute vec2 texCoords;\n" +
            "varying vec2 outTexCoords;\n" +
            "\nvoid main(void) {\n" +
            "    outTexCoords = texCoords;\n" +
            "    gl_Position = position;\n" +
            "}\n\n";
    private static final String sSimpleFS =
            "precision mediump float;\n\n" +
            "varying vec2 outTexCoords;\n" +
            "uniform sampler2D texture;\n" +
            "\nvoid main(void) {\n" +
            "    gl_FragColor = texture2D(texture, outTexCoords);\n" +
            "}\n\n";

    private static final int FLOAT_SIZE_BYTES = 4;
    private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
    private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
    private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
    private final float[] mTriangleVerticesData = {
            // X, Y, Z, U, V
            -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
             1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
            -1.0f,  1.0f, 0.0f, 0.0f, 1.0f,
             1.0f,  1.0f, 0.0f, 1.0f, 1.0f,
    };

    @Override
    public void run() {
        initGL();

        FloatBuffer triangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length
                * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer();
        triangleVertices.put(mTriangleVerticesData).position(0);

        int texture = loadTexture(R.drawable.large_photo);
        int program = buildProgram(sSimpleVS, sSimpleFS);

        int attribPosition = glGetAttribLocation(program, "position");
        checkGlError();

        int attribTexCoords = glGetAttribLocation(program, "texCoords");
        checkGlError();

        int uniformTexture = glGetUniformLocation(program, "texture");
        checkGlError();

        glBindTexture(GL_TEXTURE_2D, texture);
        checkGlError();

        glUseProgram(program);
        checkGlError();

        glEnableVertexAttribArray(attribPosition);
        checkGlError();

        glEnableVertexAttribArray(attribTexCoords);
        checkGlError();

        glUniform1i(uniformTexture, texture);
        checkGlError();

        while (!mFinished) {
            checkCurrent();

            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            checkGlError();

            glClear(GL_COLOR_BUFFER_BIT);
            checkGlError();

            // drawQuad
            triangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
            glVertexAttribPointer(attribPosition, 3, GL_FLOAT, false,
                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);

            triangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
            glVertexAttribPointer(attribTexCoords, 3, GL_FLOAT, false,
                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);

            glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

            if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
                throw new RuntimeException("Cannot swap buffers");
            }
            checkEglError();

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // Ignore
            }
        }

        finishGL();
    }

    private int loadTexture(int resource) {
        int[] textures = new int[1];

        glActiveTexture(GL_TEXTURE0);
        glGenTextures(1, textures, 0);
        checkGlError();

        int texture = textures[0];
        glBindTexture(GL_TEXTURE_2D, texture);
        checkGlError();

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        Bitmap bitmap = BitmapFactory.decodeResource(mResources, resource);

        GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap, GL_UNSIGNED_BYTE, 0);
        checkGlError();

        bitmap.recycle();

        return texture;
    }

    private int buildProgram(String vertex, String fragment) {
        int vertexShader = buildShader(vertex, GL_VERTEX_SHADER);
        if (vertexShader == 0) return 0;

        int fragmentShader = buildShader(fragment, GL_FRAGMENT_SHADER);
        if (fragmentShader == 0) return 0;

        int program = glCreateProgram();
        glAttachShader(program, vertexShader);
        checkGlError();

        glAttachShader(program, fragmentShader);
        checkGlError();

        glLinkProgram(program);
        checkGlError();

        int[] status = new int[1];
        glGetProgramiv(program, GL_LINK_STATUS, status, 0);
        if (status[0] != GL_TRUE) {
            String error = glGetProgramInfoLog(program);
            Log.d(LOG_TAG, "Error while linking program:\n" + error);
            glDeleteShader(vertexShader);
            glDeleteShader(fragmentShader);
            glDeleteProgram(program);
            return 0;
        }

        return program;
    }

    private int buildShader(String source, int type) {
        int shader = glCreateShader(type);

        glShaderSource(shader, source);
        checkGlError();

        glCompileShader(shader);
        checkGlError();

        int[] status = new int[1];
        glGetShaderiv(shader, GL_COMPILE_STATUS, status, 0);
        if (status[0] != GL_TRUE) {
            String error = glGetShaderInfoLog(shader);
            Log.d(LOG_TAG, "Error while compiling shader:\n" + error);
            glDeleteShader(shader);
            return 0;
        }

        return shader;
    }

    private void checkEglError() {
        int error = mEgl.eglGetError();
        if (error != EGL10.EGL_SUCCESS) {
            Log.w(LOG_TAG, "EGL error = 0x" + Integer.toHexString(error));
        }
    }

    private void checkGlError() {
        int error = glGetError();
        if (error != GL_NO_ERROR) {
            Log.w(LOG_TAG, "GL error = 0x" + Integer.toHexString(error));
        }
    }

    private void finishGL() {
        mEgl.eglDestroyContext(mEglDisplay, mEglContext);
        mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
    }

    private void checkCurrent() {
        if (!mEglContext.equals(mEgl.eglGetCurrentContext()) ||
                !mEglSurface.equals(mEgl.eglGetCurrentSurface(EGL10.EGL_DRAW))) {
            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
                throw new RuntimeException("eglMakeCurrent failed "
                        + GLUtils.getEGLErrorString(mEgl.eglGetError()));
            }
        }
    }

    private void initGL() {
        mEgl = (EGL10) EGLContext.getEGL();

        mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
        if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
            throw new RuntimeException("eglGetDisplay failed "
                    + GLUtils.getEGLErrorString(mEgl.eglGetError()));
        }

        int[] version = new int[2];
        if (!mEgl.eglInitialize(mEglDisplay, version)) {
            throw new RuntimeException("eglInitialize failed " +
                    GLUtils.getEGLErrorString(mEgl.eglGetError()));
        }

        mEglConfig = chooseEglConfig();
        if (mEglConfig == null) {
            throw new RuntimeException("eglConfig not initialized");
        }

        mEglContext = createContext(mEgl, mEglDisplay, mEglConfig);

        mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, mSurface, null);

        if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
            int error = mEgl.eglGetError();
            if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
                Log.e(LOG_TAG, "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
                return;
            }
            throw new RuntimeException("createWindowSurface failed "
                    + GLUtils.getEGLErrorString(error));
        }

        if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
            throw new RuntimeException("eglMakeCurrent failed "
                    + GLUtils.getEGLErrorString(mEgl.eglGetError()));
        }

        mGL = mEglContext.getGL();
    }


    EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) {
        int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
        return egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);            
    }

    private EGLConfig chooseEglConfig() {
        int[] configsCount = new int[1];
        EGLConfig[] configs = new EGLConfig[1];
        int[] configSpec = getConfig();
        if (!mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, configsCount)) {
            throw new IllegalArgumentException("eglChooseConfig failed " +
                    GLUtils.getEGLErrorString(mEgl.eglGetError()));
        } else if (configsCount[0] > 0) {
            return configs[0];
        }
        return null;
    }

    private int[] getConfig() {
        return new int[] {
                EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                EGL10.EGL_RED_SIZE, 8,
                EGL10.EGL_GREEN_SIZE, 8,
                EGL10.EGL_BLUE_SIZE, 8,
                EGL10.EGL_ALPHA_SIZE, 8,
                EGL10.EGL_DEPTH_SIZE, 0,
                EGL10.EGL_STENCIL_SIZE, 0,
                EGL10.EGL_NONE
        };
    }

    void finish() {
        mFinished = true;
    }
}

您也可以选择 NDK 路线,这可能是从 Objective C 更直接的过渡。

关于android - 确定 Android OpenGLES 中的最大/最小纹理大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11442426/

相关文章:

android - 为什么我经常收到 ActivityNotFound 异常?

java - Android 上的重复快捷方式图标

android - Phonegap 应用程序 : Page layout breaks after input from keyboard

iphone - Quartz 2D/OpenGLES 图像上的几何变形(最好使用 CGImage)

iPhone : OpenGL ES : Detecting if you have tapped a object (cube) on screen

java - Activity 结果错误

android - setYLabelsColor() 等函数中 scale 参数的用途是什么?

Android重复provider权限问题

c++ - 加载多纹理 opengl es 2.0

android - 如何使布局垂直填充屏幕但在内容不适合时开始增长