2017-04-15 48 views
1

我目前正在使用Java和LWJGL 3,并且正在为顶点数组对象,顶点缓冲对象等写东西。 现在,删除它是个好习惯这些对象在程序退出之前,所以我创建了一个应该清理的关闭钩子。LWJGL - OpenGL上下文在关机钩丢失

但是,当我在关闭钩子内调用OpenGL函数时,我得到一个非法状态异常,说明OpenGL上下文尚未初始化。

我写了一个测试程序,它再现了这种行为:

public static void main(String[] args) { 
    GLFW.glfwInit(); 
    long window = GLFW.glfwCreateWindow(100, 100, "", 0, 0); 

    Runtime.getRuntime().addShutdownHook(new Thread() { 
     public void run() { 
      GL15.glDeleteBuffers(0); 
      GLFW.glfwTerminate(); 
     } 
    }); 

    while (!GLFW.glfwWindowShouldClose(window)) { 
     GLFW.glfwPollEvents(); 
    } 
} 

堆栈跟踪:

Exception in thread "Thread-0" java.lang.IllegalStateException: No GLCapabilities instance set for the current thread. Possible solutions: 
a) Call GL.createCapabilities() after making a context current in the current thread. 
b) Call GL.setCapabilities() if a GLCapabilities instance already exists for the current context. 
at org.lwjgl.opengl.GL.getCapabilities(GL.java:241) 
at org.lwjgl.opengl.GL15.nglDeleteBuffers(GL15.java:152) 
at org.lwjgl.opengl.GL15.glDeleteBuffers(GL15.java:178) 
at core.Main$1.run(Main.java:11) 

有谁知道为什么上下文被自动销毁?

如果你需要任何额外的信息就这么说。

+0

关闭挂钩的目的是什么? 'glfwWindowShouldClose'不够好吗? –

+1

请注意,OpenGL上下文绑定到一个特定的线程。由于您正在产生一个新线程,因此您必须在使用之前绑定上下文。 – BDL

+0

@NicolBolas不,我想将此接口与其他类分离,所以我不想调用disposeAll方法或其他类。 – RagingRabbit

回答

1

OpenGL上下文总是与一个线程(或没有线程)关联。函数只能在上下文绑定的线程的特定上下文中调用。

由于关闭钩子启动一个新的线程,你必须在发出任何命令之前将OpenGL上下文绑定到该线程。