【发布时间】:2020-04-13 22:31:13
【问题描述】:
如果您不熟悉 Gaffer on Games 文章“修复您的时间步长”,您可以在此处找到它: https://gafferongames.com/post/fix_your_timestep/
我正在构建一个游戏引擎,为了让 std::chrono 更加舒适,我一直在尝试使用 std::chrono 来实现一个固定的时间步长。似乎无法绕过它。这是我正在努力的伪代码:
double t = 0.0;
double dt = 0.01;
double currentTime = hires_time_in_seconds();
double accumulator = 0.0;
State previous;
State current;
while ( !quit )
{
double newTime = time();
double frameTime = newTime - currentTime;
if ( frameTime > 0.25 )
frameTime = 0.25;
currentTime = newTime;
accumulator += frameTime;
while ( accumulator >= dt )
{
previousState = currentState;
integrate( currentState, t, dt );
t += dt;
accumulator -= dt;
}
const double alpha = accumulator / dt;
State state = currentState * alpha +
previousState * ( 1.0 - alpha );
render( state );
}
目标:
- 我不希望渲染受帧率限制。我应该在繁忙的循环中渲染
- 我想要一个完全固定的时间步长,我用
float增量时间调用我的更新函数 - 不睡觉
我目前的尝试(半固定):
#include <algorithm>
#include <chrono>
#include <SDL.h>
namespace {
using frame_period = std::chrono::duration<long long, std::ratio<1, 60>>;
const float s_desiredFrameRate = 60.0f;
const float s_msPerSecond = 1000;
const float s_desiredFrameTime = s_msPerSecond / s_desiredFrameRate;
const int s_maxUpdateSteps = 6;
const float s_maxDeltaTime = 1.0f;
}
auto framePrev = std::chrono::high_resolution_clock::now();
auto frameCurrent = framePrev;
auto frameDiff = frameCurrent - framePrev;
float previousTicks = SDL_GetTicks();
while (m_mainWindow->IsOpen())
{
float newTicks = SDL_GetTicks();
float frameTime = newTicks - previousTicks;
previousTicks = newTicks;
// 32 ms in a frame would cause this to be .5, 16ms would be 1.0
float totalDeltaTime = frameTime / s_desiredFrameTime;
// Don't execute anything below
while (frameDiff < frame_period{ 1 })
{
frameCurrent = std::chrono::high_resolution_clock::now();
frameDiff = frameCurrent - framePrev;
}
using hr_duration = std::chrono::high_resolution_clock::duration;
framePrev = std::chrono::time_point_cast<hr_duration>(framePrev + frame_period{ 1 });
frameDiff = frameCurrent - framePrev;
// Time step
int i = 0;
while (totalDeltaTime > 0.0f && i < s_maxUpdateSteps)
{
float deltaTime = std::min(totalDeltaTime, s_maxDeltaTime);
m_gameController->Update(deltaTime);
totalDeltaTime -= deltaTime;
i++;
}
// ProcessCallbackQueue();
// ProcessSDLEvents();
// m_renderEngine->Render();
}
这个实现的问题
- 渲染、处理输入等与帧速率相关
- 我正在使用 SDL_GetTicks() 而不是 std::chrono
我的实际问题
- 如何将
SDL_GetTicks()替换为std::chrono::high_resolution_clock::now()?似乎无论我需要使用什么count(),但我从 Howard Hinnant 本人那里读到了这句话:
如果您使用 count(),并且/或者您的计时码中有转换因子,那么您就太努力了。 所以我想也许有更直观的方法。
- 如何将所有
floats 替换为实际的 std::chrono_literal 时间值,除了我将浮点 deltaTime 作为模拟修改器传递给更新函数的末尾?
【问题讨论】:
标签: c++ c++11 game-engine chrono game-loop