c++ - Is this a good way to lock a loop on 60 loops per second? -
i have game bullet physics physics engine, game online multiplayer though try source engine approach deal physics sync on net. in client use glfw fps limit working there default. (at least think it's because glfw). in server side there no graphics libraries need "lock" loop simulating world , stepping physics engine 60 "ticks" per second.
is right way lock loop run 60 times second? (a.k.a 60 "fps").
void world::run() { m_isrunning = true; long limit = (1 / 60.0f) * 1000; long previous = milliseconds_now(); while (m_isrunning) { long start = milliseconds_now(); long deltatime = start - previous; previous = start; std::cout << m_objects[0]->getobjectstate().position[1] << std::endl; m_dynamicsworld->stepsimulation(1 / 60.0f, 10); long end = milliseconds_now(); long dt = end - start; if (dt < limit) { std::this_thread::sleep_for(std::chrono::milliseconds(limit - dt)); } } }
is ok use std::thread task?
is way efficient enough?
will physics simulation steped 60 times second?
p.s
the milliseconds_now()
looks this:
long long milliseconds_now() { static large_integer s_frequency; static bool s_use_qpc = queryperformancefrequency(&s_frequency); if (s_use_qpc) { large_integer now; queryperformancecounter(&now); return (1000ll * now.quadpart) / s_frequency.quadpart; } else { return gettickcount(); } }
taken from: https://gamedev.stackexchange.com/questions/26759/best-way-to-get-elapsed-time-in-miliseconds-in-windows
if want limit rendering maximum fps of 60, simple :
each frame, check if game running fast, if wait, example:
while ( timelimitedloop ) { float framedelta = ( timenow - timelast ) timelast = timenow; each ( objectorcalculation myobjectorcalculation in allitemstoprocess ) { myobjectorcalculation->processthisin60thofsecond(framedelta); } render(); // if display needed }
please note if vertical sync enabled, rendering limited frequency of vertical refresh, perhaps 50 or 60 hz).
if, however, wish logic locked @ 60fps, that's different matter: have segregate display , logic code in such way logic runs @ maximum of 60 fps, , modify code can have fixed time-interval loop , variable time-interval loop (as above). sources @ "fixed timestep" , "variable timestep" ( link 1 link 2 , old trusty google search).
note on code: because using sleep whole duration of 1/60th of second - elapsed time can miss correct timing easily, change sleep loop running follows:
instead of
if (dt < limit) { std::this_thread::sleep_for(std::chrono::milliseconds(limit - dt)); }
change
while(dt < limit) { std::this_thread::sleep_for(std::chrono::milliseconds(limit - (dt/10.0))); // or 100.0 or whatever fine-grained step desire }
hope helps, let me know if need more info:)
Comments
Post a Comment