Advertisement
runewalsh

Не зависит от фпс!1

Aug 14th, 2012
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include "windows.h"
  3. #include "math.h"
  4. #pragma comment(lib, "winmm.lib")
  5. #define clamp(x, a, b) (max(min(x, b), a))
  6.  
  7. LARGE_INTEGER __qpcFreq;
  8.  
  9. void initTimer()
  10. {
  11.     QueryPerformanceFrequency(&__qpcFreq);
  12.     timeBeginPeriod(1);
  13. }
  14.  
  15. void doneTimer()
  16. {
  17.     timeEndPeriod(1);
  18. }
  19.  
  20. double getTime()
  21. {
  22.     LARGE_INTEGER counter;
  23.     QueryPerformanceCounter(&counter);
  24.     return (double) counter.QuadPart / (double) __qpcFreq.QuadPart;
  25. }
  26.  
  27. class World
  28. {
  29. public:
  30.     void Update(double dt)
  31.     {
  32.         // двигаешь всё с dt
  33.     }
  34.     void Draw()
  35.     {
  36.         // ...
  37.     }
  38. };
  39.  
  40. const double MIN_DT = 0.001;
  41. const double MAX_DT = 0.1;
  42. const double REQUIRED_FPS = 100;
  43. const double REQUIRED_DT = 1.0 / REQUIRED_FPS;
  44.  
  45. int _tmain(int argc, _TCHAR* argv[])
  46. {
  47.     initTimer();
  48.     World world = World();
  49.     double prevTime = getTime();
  50.  
  51.     for(;;)
  52.     {
  53.         double curTime = getTime();
  54.         double dt = clamp(curTime - prevTime, MIN_DT, MAX_DT);
  55.         prevTime = curTime;
  56.  
  57.         world.Update(dt);
  58.         world.Draw();
  59.  
  60.         double timePassed = clamp(getTime() - curTime, 0.0, 0.5);
  61.         if (timePassed < REQUIRED_DT) Sleep((int)(1000.0 * (REQUIRED_DT - timePassed) + 0.5));
  62.     }
  63.  
  64.     doneTimer();
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement