java - OpenGL 和 AWT/Swing 用户界面

标签 java swing embedded awt opengl-es-3.0

我目前正在为嵌入式系统开发带有 OpenGL (LWJGL) 的 3D 查看器。 无需赘述,有一个用 Java/Swing 编写的应用程序,目前已在 Java+Swing 上完全实现了 UI 和逻辑。但我们决定,除了 2D 自上而下的图片之外,拥有 3D View 也会很酷,这就是我的用武之地。

我会说我必须使用 GLES 3.0 或 Opengl 2.1,并且我更喜欢 GLES,因为与 2.1 相比,它具有更多功能 我还有一个使用 GLFW 窗口系统(LWJGL 的默认设置)实现的独立应用程序,该应用程序在设备上运行良好 - 它不会滞后并提供不错的 FPS。同样,在 GLFW 窗口中运行时。

但现在我需要将它附加到 JFrame 最好,这就是我的问题开始的地方。基本上,我需要的是将 3D View 渲染为背景,然后在其顶部显示 Swing 按钮/面板和其他窗口(例如带有选项菜单)。

我已经实现了一种简单读取 FrameBuffer 并将其作为光栅图像绘制在 Canvas 上的基本算法。但这很慢。我得到了大约 10 FPS。

private void render()
{
    logic.Render(window);      //GLFW window
    window.update();

    ByteBuffer nativeBuffer = BufferUtils.createByteBuffer(GlobalSettings.WINDOW_WIDTH*GlobalSettings.WINDOW_HEIGHT*4);
    BufferedImage image = new BufferedImage(GlobalSettings.WINDOW_WIDTH,GlobalSettings.WINDOW_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
    GLES30.glReadPixels(0, 0, GlobalSettings.WINDOW_WIDTH,GlobalSettings.WINDOW_HEIGHT, GLES20.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, nativeBuffer);
    byte[] imgData = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
    nativeBuffer.get(imgData);

    Graphics g = canvas.getGraphics();
    g.drawImage(image, 0,0, GlobalSettings.WINDOW_WIDTH,GlobalSettings.WINDOW_HEIGHT, null);

}

我尝试过的另一件事是使用这个库 https://github.com/LWJGLX/lwjgl3-awt看来这个推荐很多。问题是,它使用了一些 OpenGL 3.1 功能,并且让它在 2.1 环境下正常工作是一项艰巨的任务。但至于 GLES - 我根本无法让它工作,而且我显然不能让它为 2.1 创建上下文,然后进一步使用 GLES 功能,所以它基本上破坏了我的整个渲染代码。 也许我只是做得不对,但无论如何 - 我无法让它为我工作。

这就是我的立场。我想我应该在这里寻求帮助。对我来说,在这一点上,我似乎必须完全为 OpenGL/GLFW 编写整个界面,并完全放弃 Swing。这一点都不理想 - 我什至想知道我们是否有这样的时间。

如果有办法让我的东西与 AWT 一起工作,请为我指明正确的方向。

最佳答案

我自己会发布答案。它在 Linux 桌面和嵌入式系统上都运行良好,据我所知,性能良好。

这个想法是采用 EGL 上下文和 GLES,并将 AWT Canvas 表面设置为上下文的直接目标。您不需要读取缓冲区然后将其绘制在 Canvas 上。 下面是我的 Window 类初始化。

private Canvas canvas;
private JAWTDrawingSurface ds;
public long display;
private long eglDisplay;
public long drawable;
private long surface;

public static final JAWT awt;
static {
    awt = JAWT.calloc();
    awt.version(JAWT_VERSION_1_4);
    if (!JAWT_GetAWT(awt))
        throw new AssertionError("GetAWT failed");
}

public void lock() throws AWTException {
    int lock = JAWT_DrawingSurface_Lock(ds, ds.Lock());
    if ((lock & JAWT_LOCK_ERROR) != 0)
        throw new AWTException("JAWT_DrawingSurface_Lock() failed");
}

public void unlock() throws AWTException {
    JAWT_DrawingSurface_Unlock(ds, ds.Unlock());
}

public void Init2()
{
    frame = new JFrame("AWT test");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.setPreferredSize(new Dimension(width, height));

    canvas = new Canvas();
    frame.add(canvas);

    frame.pack();
    frame.setVisible(true);
    frame.transferFocus();

    int error;

    System.out.println("Window init2() started");

    this.ds = JAWT_GetDrawingSurface(canvas, awt.GetDrawingSurface());
    //JAWTDrawingSurface ds = JAWT_GetDrawingSurface(canvas, awt.GetDrawingSurface());
    try
    {
        lock();
        try
        {
            JAWTDrawingSurfaceInfo dsi = JAWT_DrawingSurface_GetDrawingSurfaceInfo(ds, ds.GetDrawingSurfaceInfo());

            JAWTX11DrawingSurfaceInfo dsiWin = JAWTX11DrawingSurfaceInfo.create(dsi.platformInfo());

            int depth = dsiWin.depth();
            this.display = dsiWin.display();
            this.drawable = dsiWin.drawable();

            System.out.printf("EGL Display %d, drawable: \n", display, drawable);

            eglDisplay = eglGetDisplay(display);

            EGLCapabilities egl;
            try (MemoryStack stack = stackPush()) {
                IntBuffer major = stack.mallocInt(1);
                IntBuffer minor = stack.mallocInt(1);

                if (!eglInitialize(eglDisplay, major, minor)) {
                    throw new IllegalStateException(String.format("Failed to initialize EGL [0x%X]", eglGetError()));
                }

                egl = EGL.createDisplayCapabilities(eglDisplay, major.get(0), minor.get(0));
            }
            System.out.println("EGL caps created");

            IntBuffer attrib_list = BufferUtils.createIntBuffer(18);
            attrib_list.put(EGL_CONFORMANT).put(EGL_OPENGL_ES2_BIT);
            //attrib_list.put(EGL_ALPHA_MASK_SIZE).put(4);
            //attrib_list.put(EGL_ALPHA_SIZE).put(4);
            //attrib_list.put(EGL_RED_SIZE).put(5);
            //attrib_list.put(EGL_GREEN_SIZE).put(6);
            //attrib_list.put(EGL_BLUE_SIZE).put(5);
            //attrib_list.put(EGL_DEPTH_SIZE).put(4);
            //attrib_list.put(EGL_SURFACE_TYPE).put(EGL_WINDOW_BIT);
            attrib_list.put(EGL_NONE);
            attrib_list.flip();

            PointerBuffer fbConfigs = BufferUtils.createPointerBuffer(1);
            IntBuffer numConfigs = BufferUtils.createIntBuffer(1);

            boolean test2 = eglChooseConfig(eglDisplay, attrib_list, fbConfigs,numConfigs);

            if (fbConfigs == null || fbConfigs.capacity() == 0) {
                // No framebuffer configurations supported!
                System.out.println("No supported framebuffer configurations found");
            }

            long test = numConfigs.get(0);

            IntBuffer context_attrib_list = BufferUtils.createIntBuffer(18);
            context_attrib_list.put(EGL_CONTEXT_MAJOR_VERSION).put(3);
            context_attrib_list.put(EGL_CONTEXT_MINOR_VERSION).put(0);
            context_attrib_list.put(EGL_NONE);
            context_attrib_list.flip();

            long context = eglCreateContext(eglDisplay,fbConfigs.get(0),EGL_NO_CONTEXT,context_attrib_list);

            error = eglGetError();

            surface = eglCreateWindowSurface(eglDisplay,fbConfigs.get(0),drawable,(int[])null);

            error = eglGetError();

            eglMakeCurrent(eglDisplay,surface,surface,context);

            error = eglGetError();

            GLESCapabilities gles = GLES.createCapabilities();
            System.out.println("CLES caps created");
        }
        finally
        {
            unlock();
        }

    }
    catch (Exception e)
    {
        System.out.println("JAWT Failed");
    }

    // Render with OpenGL ES
    glClearColor(0f,0f,0f,1f);
    glfwSwapInterval(vSync);
    glEnable(GL_DEPTH_TEST);

    int[] range = new int[2];
    int[] precision = new int[2];
    glGetShaderPrecisionFormat(GL_FRAGMENT_SHADER, GL_HIGH_FLOAT, range, precision);

    System.out.println("Window context Initialized");
}

请注意,属性列表可以是您想要的任何内容,也可以什么都没有。实际上,当我没有指定 3.0 作为上下文的版本兼容性时,我遇到了 GLES 问题 - 由于某种原因它尝试使用 OpenGL ES-CL 1.1 但失败了。无论如何,只需指定次要和主要上下文版本即可修复此问题。 另请注意,这只是初始化。 JFrame 和 Canvas 在其他地方创建,然后 Canvas 传递给 Window 类构造函数。 另一个重要的事情是lock()/unlock()函数。如果没有它们,您将遇到大量 XCB 错误和崩溃 - 因为其他线程会在您绘制时尝试更新显示,从而导致冲突,并且 XCB 将崩溃。

此外,当您交换缓冲区时(即当您实际绘制帧缓冲区时),您需要锁定和解锁。

public void update()
{
    try
    {
        lock();
        eglSwapBuffers(eglDisplay, surface);
        unlock();
    }
    catch (Exception e)
    {
        System.out.println("Swap buffers failed");
    }
}

不要介意我当前的异常处理缺乏 - 我一找到解决方案就编辑我的答案,以免我以前的版本让人们感到困惑。

我还要感谢 lwjgl-awt 项目,它给了我想法。它不支持 EGL,所以我不得不对其进行一些修改,但我从那里获取了部分,所以值得赞扬的地方。 https://github.com/LWJGLX/lwjgl3-awt

为了比较,这里是 GLFW 版本。基本上,这是同一个类的初始化,但它只是做其他事情。然而,这里的窗口是直接在方法内部创建的。

public void Init()
{
    System.out.println("Window init() started");

    GLFWErrorCallback.createPrint().set();
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize glfw");
    }

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

    // GLFW setup for EGL & OpenGL ES
    glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    windowHandle = glfwCreateWindow(width, height, title, NULL, NULL);
    if (windowHandle == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    System.out.printf("Window handle created %d\n", windowHandle);

    SetCallbacks();

    // EGL capabilities
    displayHandle = glfwGetEGLDisplay();

    System.out.printf("EGL DisplayHandle %d\n", displayHandle);

    try (MemoryStack stack = stackPush()) {
        IntBuffer major = stack.mallocInt(1);
        IntBuffer minor = stack.mallocInt(1);

        if (!eglInitialize(displayHandle, major, minor)) {
            throw new IllegalStateException(String.format("Failed to initialize EGL [0x%X]", eglGetError()));
        }

        EGLCapabilities egl = EGL.createDisplayCapabilities(displayHandle, major.get(0), minor.get(0));
    }
    System.out.println("EGL caps created");

    // OpenGL ES capabilities
    glfwMakeContextCurrent(windowHandle);
    System.out.printf("Current context: %d.%d rev %d, Client_Context: %d\n",glfwGetWindowAttrib(windowHandle,GLFW_CONTEXT_VERSION_MAJOR),
            glfwGetWindowAttrib(windowHandle,GLFW_CONTEXT_VERSION_MINOR), glfwGetWindowAttrib(windowHandle,GLFW_CONTEXT_REVISION),
            glfwGetWindowAttrib(windowHandle,GLFW_CLIENT_API));

    GLESCapabilities gles = GLES.createCapabilities();
    System.out.println("CLES caps created");

    // Render with OpenGL ES
    //glfwShowWindow(windowHandle);
    glClearColor(0f,0f,0f,1f);
    glfwSwapInterval(vSync);
    glEnable(GL_DEPTH_TEST);

    int[] range = new int[2];
    int[] precision = new int[2];
    glGetShaderPrecisionFormat(GL_FRAGMENT_SHADER, GL_HIGH_FLOAT, range, precision);

    System.out.printf("Current context: %d.%d\n",glfwGetWindowAttrib(windowHandle,GLFW_CONTEXT_VERSION_MAJOR),
                                            glfwGetWindowAttrib(windowHandle,GLFW_CONTEXT_VERSION_MINOR));
}

关于java - OpenGL 和 AWT/Swing 用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59174586/

相关文章:

memory-management - 为什么我们不应该在嵌入式系统中动态分配不同大小的内存

arm - 从 Cortex M3 处理器的用户程序进入中断处理程序时使用哪个堆栈?

java - 删除链表中的重复值(Java中的递归)

java - Primefaces 3.5 selectOneRadio 以图像作为背景不起作用

java - 无法使用restFB 在我的墙上发帖

java - 为什么 Java Swing JProgressBar 在 Nimbu 外观和感觉中无法正常工作?

java - 关于如何在 Java swing 和 Awt 中绘制此布局的任何提示

java - 解决数组中的空元素

java - 似乎 JPanel 背景未在 FocusListener 中读取

database - 嵌入式的 "best"数据库是什么?