首页
学习
活动
专区
圈层
工具
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

编码着色器时OpenGL找不到上下文。:LWJGL

当使用LWJGL(Lightweight Java Game Library)进行OpenGL编程时,遇到“找不到上下文”的错误通常意味着OpenGL上下文尚未创建或已被销毁。以下是一些基础概念和相关解决方案:

基础概念

  1. OpenGL上下文
    • OpenGL上下文是一个包含了OpenGL状态信息的容器,包括渲染状态、缓冲区、纹理等。
    • 在进行任何OpenGL调用之前,必须先创建一个有效的OpenGL上下文。
  • LWJGL
    • LWJGL是一个用于Java的游戏开发库,提供了对OpenGL、OpenAL、Vulkan等图形和音频API的绑定。
    • 它允许Java开发者直接使用这些底层API进行高性能的游戏和图形应用开发。

可能的原因

  1. 上下文未创建
    • 在调用任何OpenGL函数之前,必须先创建一个窗口并为其分配一个OpenGL上下文。
  • 上下文已销毁
    • 如果窗口被关闭或程序退出,OpenGL上下文会被自动销毁。
  • 线程问题
    • OpenGL上下文通常只能在创建它的线程中使用。如果在其他线程中进行OpenGL调用,可能会导致找不到上下文的错误。

解决方案

以下是一个简单的LWJGL示例,展示了如何正确创建窗口和OpenGL上下文:

代码语言:txt
复制
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class HelloWorld {

    // The window handle
    private long window;

    public void run() {
        System.out.println("Hello LWJGL " + Version.getVersion() + "!");

        init();
        loop();

        // Free the window callbacks and destroy the window
        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);

        // Terminate GLFW and free the error callback
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }

    private void init() {
        // Setup an error callback. The default implementation
        // will print the error message in System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Initialize GLFW. Most GLFW functions will not work before doing this.
        if (!glfwInit()) {
            throw new IllegalStateException("Unable to initialize GLFW");
        }

        // Configure GLFW
        glfwDefaultWindowHints(); // optional, the current window hints are already the default
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable

        // Create the window
        window = glfwCreateWindow(300, 300, "Hello World", NULL, NULL);
        if (window == NULL) {
            throw new RuntimeException("Failed to create the GLFW window");
        }

        // Setup a key callback. It will be called every time a key is pressed, repeated or released.
        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
                glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
            }
        });

        // Get the thread stack and push a new frame
        try (MemoryStack stack = stackPush()) {
            IntBuffer pWidth = stack.mallocInt(1); // int*
            IntBuffer pHeight = stack.mallocInt(1); // int*

            // Get the window size passed to glfwCreateWindow
            glfwGetWindowSize(window, pWidth, pHeight);

            // Get the resolution of the primary monitor
            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            // Center the window
            glfwSetWindowPos(
                window,
                (vidmode.width() - pWidth.get(0)) / 2,
                (vidmode.height() - pHeight.get(0)) / 2
            );
        } // the stack frame is popped automatically

        // Make the OpenGL context current
        glfwMakeContextCurrent(window);
        // Enable v-sync
        glfwSwapInterval(1);

        // Make the window visible
        glfwShowWindow(window);
    }

    private void loop() {
        // This line is critical for LWJGL's interoperation with GLFW's
        // OpenGL context, or any context that is managed externally.
        // LWJGL detects the context that is current in the current thread,
        // creates the GLCapabilities instance and makes the OpenGL
        // bindings available for use.
        GL.createCapabilities();

        // Set the clear color
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        // Run the rendering loop until the user has attempted to close
        // the window or has pressed the ESCAPE key.
        while (!glfwWindowShouldClose(window)) {
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

            // Draw your scene here

            // Swap the color buffers
            glfwSwapBuffers(window);

            // Poll for window events. The key callback above will only be
            // invoked during this call.
            glfwPollEvents();
        }
    }

    public static void main(String[] args) {
        new HelloWorld().run();
    }
}

关键点总结

  1. 确保上下文创建
    • 在调用任何OpenGL函数之前,确保窗口已创建并且OpenGL上下文已分配。
  • 线程安全
    • 确保所有OpenGL调用都在创建上下文的同一线程中进行。
  • 错误处理
    • 使用适当的错误回调机制来捕获和处理初始化过程中的错误。

通过以上步骤,你应该能够解决“OpenGL找不到上下文”的问题。如果问题仍然存在,请检查是否有其他库或代码干扰了OpenGL上下文的创建和管理。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的文章

扫码

添加站长 进交流群

领取专属 10元无门槛券

手把手带您无忧上云

扫码加入开发者社群

热门标签

活动推荐

    运营活动

    活动名称
    广告关闭
    领券