Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

123 linhas
2.3 KiB

  1. //
  2. // Deus Hax (working title)
  3. // Copyright (c) 2010 Sam Hocevar <sam@hocevar.net>
  4. //
  5. #if defined HAVE_CONFIG_H
  6. # include "config.h"
  7. #endif
  8. #include <cstdlib>
  9. #include <cstdio>
  10. #include <stdint.h>
  11. #if defined __linux__
  12. # include <sys/time.h>
  13. # include <unistd.h>
  14. #elif defined _WIN32
  15. # define WIN32_LEAN_AND_MEAN
  16. # include <windows.h>
  17. # include <SDL.h> // FIXME: this should not be needed
  18. #else
  19. # include <SDL.h>
  20. #endif
  21. #include "timer.h"
  22. /*
  23. * Timer implementation class
  24. */
  25. class TimerData
  26. {
  27. friend class Timer;
  28. private:
  29. TimerData()
  30. {
  31. #if defined __linux__
  32. gettimeofday(&tv0, NULL);
  33. #elif defined _WIN32
  34. LARGE_INTEGER tmp;
  35. QueryPerformanceFrequency(&tmp);
  36. seconds_per_cycle = 1.0f / tmp.QuadPart;
  37. QueryPerformanceCounter(&cycles0);
  38. #else
  39. SDL_Init(SDL_INIT_TIMER);
  40. ticks0 = SDL_GetTicks();
  41. #endif
  42. }
  43. float GetSeconds(bool update)
  44. {
  45. float ret;
  46. #if defined __linux__
  47. struct timeval tv;
  48. gettimeofday(&tv, NULL);
  49. ret = 1e-6f * (tv.tv_usec - tv0.tv_usec) + (tv.tv_sec - tv0.tv_sec);
  50. if (update)
  51. tv0 = tv;
  52. #elif defined _WIN32
  53. LARGE_INTEGER cycles;
  54. QueryPerformanceCounter(&cycles);
  55. ret = seconds_per_cycle * (cycles.QuadPart - cycles0.QuadPart);
  56. if (update)
  57. cycles0 = cycles;
  58. #else
  59. Uint32 ticks = SDL_GetTicks();
  60. ret = 1e-3f * (ticks - ticks0);
  61. if (update)
  62. ticks0 = ticks;
  63. #endif
  64. return ret;
  65. }
  66. void WaitSeconds(float seconds)
  67. {
  68. #if defined __linux__
  69. usleep((int)(seconds * 1000000.0f));
  70. #elif defined _WIN32
  71. /* FIXME: use native Win32 stuff */
  72. SDL_Delay((int)(seconds * 1000.0f + 0.5f));
  73. #else
  74. SDL_Delay((int)(seconds * 1000.0f + 0.5f));
  75. #endif
  76. }
  77. #if defined __linux__
  78. struct timeval tv0;
  79. #elif defined _WIN32
  80. float seconds_per_cycle;
  81. LARGE_INTEGER cycles0;
  82. #else
  83. Uint32 ticks0;
  84. #endif
  85. };
  86. /*
  87. * Timer public class
  88. */
  89. Timer::Timer()
  90. {
  91. data = new TimerData();
  92. }
  93. Timer::~Timer()
  94. {
  95. delete data;
  96. }
  97. float Timer::GetSeconds()
  98. {
  99. return data->GetSeconds(true);
  100. }
  101. void Timer::WaitSeconds(float seconds)
  102. {
  103. float sleep = seconds - data->GetSeconds(false);
  104. if (sleep > 1e-4f)
  105. data->WaitSeconds(sleep);
  106. }