解决 glfw window freeze when resized

问题

至少在 windows 下,glfw window 在 resize 时整个窗口会停止渲染,直到 resize 结束

分析

windows 下的 event loop 在 window resize 时会阻塞,体现在 glfwPollEvents() 也阻塞了

方案

要把 render 和 window event loop 放在不同的线程,防止阻塞

Opengl

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <glad/gl.h>
#include <GLFW/glfw3.h>

#include <atomic>
#include <jthread>

struct Size {
	int width;
	int height;
}

GLFWwindow* window;
std::atomic<bool> _framebuffer_resized = false;

auto get_size(GLFWwindow* window) -> Size {
	int width;
	int height;
	glfwGetWindowSize(window, &width, &height);
	return { width, height };
} 

auto resize_framebuffer(GLFWwindow* window) -> void {
	const auto size = get_size(window);
	glViewport(0, 0, size.width, size.height);
}

int main() {
	GLFWwindow* window = glfwCreateWindow(800, 600, "title", nullptr, nullptr);
	gladLoadGLES2(glfwGetProcAddress);
	
	std::jthread render_thread { [&] {
		glfwMakeContextCurrent(window);
		resize_framebuffer(window);
		while(!glfwWindowShouldClose(window)) {
			if (_framebuffer_resized) {
				resize_framebuffer(window);
				_framebuffer_resized = false;
			}
			glfwSwapbuffers(window);
		}
	} };

	while(!glfwWindowShouldClose(window))
		glfwPollEvents();
}

Vulkan