如何在 GLFW 窗口中以固定的 FPS 渲染?
How to render at a fixed FPS in a GLFW window?
我正在尝试以 60 FPS 的速度渲染,但我的场景渲染速度远高于 60 FPS。
这是我的渲染循环代码,这是以所需的 FPS 渲染的正确方法还是有更好的方法?
double lastTime = glfwGetTime(), timer = lastTime;
double deltaTime = 0, nowTime = 0;
int frames = 0, updates = 0;
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// - Measure time
nowTime = glfwGetTime();
deltaTime += (nowTime - lastTime) / limitFPS; // limitFPS = 1.0 / 60.0
lastTime = nowTime;
// - Only update at 60 frames / s
while (deltaTime >= 1.0) {
updates++;
deltaTime--;
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
w.render(); // Render function
frames++;
}
glfwPollEvents();
// - Reset after one second
if (glfwGetTime() - timer > 1.0) {
timer++;
}
glfwSwapBuffers(window);
}
根据上面评论中的讨论,您希望绘制最多 60 FPS,但您希望逻辑尽可能频繁地更新。正确?
这可以通过一个循环、一个计时器和一个 if 语句来实现:
const double fpsLimit = 1.0 / 60.0;
double lastUpdateTime = 0; // number of seconds since the last loop
double lastFrameTime = 0; // number of seconds since the last frame
// This while loop repeats as fast as possible
while (!glfwWindowShouldClose(window))
{
double now = glfwGetTime();
double deltaTime = now - lastUpdateTime;
glfwPollEvents();
// update your application logic here,
// using deltaTime if necessary (for physics, tweening, etc.)
// This if-statement only executes once every 60th of a second
if ((now - lastFrameTime) >= fpsLimit)
{
// draw your frame here
glfwSwapBuffers(window);
// only set lastFrameTime when you actually draw something
lastFrameTime = now;
}
// set lastUpdateTime every iteration
lastUpdateTime = now;
}
要尽可能频繁地执行的所有内容都应位于该while
循环的外部,并且要以每秒最多 60 次的速度执行的所有内容都应位于if
语句内。
如果循环执行迭代的时间超过 1/60 秒,则您的 FPS 和更新速率将下降到该工作负载/系统可实现的任何速率。
相关文章:
- OpenGL将纹理四边形渲染为(0,0)
- phytec phyBOARD iMX-6在从闪存而不是SD卡运行qt5 opengles应用程序时表现不佳(FPS减半
- 按需渲染帧
- 使用专用显卡进行 OpenGL 渲染时帧速率较低
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- dx11 渲染到纹理仅显示透明颜色
- 在 opengl 中渲染 obj 文件时出现黑窗口
- Qt 如何渲染 mainwidget
- C++ SDL2:如何将矩形渲染到多个视口中
- 纹理单位重叠?渲染了错误的纹理
- Qt OpenGL 渲染到纹理性能问题
- 使用 sfml 计算 FPS
- 从 OpenCV 3 切换到 OpenCV 4 会导致网络摄像头以最大 5 fps 的速度录制,而不是通常的 30 f
- SDL_ttf清除我之前和将来的所有渲染
- 向 vulkan 管道添加额外的 UBO 会停止所有几何体渲染
- 尝试渲染像素坐标时,简单线条渲染失败
- (C++) OpenGL 渲染瓦片映射会导致丢帧
- 使用计算着色器渲染到交换链
- 如何在 GLFW 窗口中以固定的 FPS 渲染?
- 渲染时间只等于fps的一半