Class: RedBird::Timer

Inherits:
Data
  • Object
show all
Defined in:
ext/red_bird/timer.c,
ext/red_bird/timer.c

Overview

A Timer controls the speed of execution of a frame; it prevents that a frame run too quickly and give you compensation when a frame runs too slow.

When creating a new instance, you must define the maximum frame rate that you want; then, you should call #tick at every frame to get a delta time. The delta time is proportional to the frame rate defined during the creation of the instance or is higher when the last frame was slower than expected.

Author:

  • Frederico Linhares

Instance Method Summary collapse

Constructor Details

#initialize(max_fps) ⇒ Object

Parameters:

  • max_fps (Integer)

    the maximum of frames to be rendered per second.

Author:

  • Frederico Linhares



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'ext/red_bird/timer.c', line 64

VALUE
bird_cTimer_initialize(VALUE self, VALUE max_fps)
{
  struct bird_timer_data *ptr;

  if(!engine_initialized)
    rb_raise(rb_eRuntimeError, "%s",
             "can not create a RedBird::Timer instance before "
             "RedBird::Engine is started");

  RB_INTEGER_TYPE_P(max_fps);

  TypedData_Get_Struct(self, struct bird_timer_data, &bird_timer_type, ptr);
  ptr->max_frame_duration_ms = 1000 / NUM2INT(max_fps);
  ptr->max_frame_duration_sec = ptr->max_frame_duration_ms/1000.0;
  ptr->frame_start = SDL_GetTicks();

  return self;
}

Instance Method Details

#tickFloat

Every time you call this method, it compares the current time with the last time it was called; if the amount of time is inferior to the frame duration, it waits to ensure the frame has the exact duration expected; otherwise, it returns instantly and gives you a delta value that compensates for the extra duration of the last frame.

Returns:

  • (Float)

    represents the amount of time between this frame and the last frame, the higher, the higher amount of time has passed.

Author:

  • Frederico Linhares



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'ext/red_bird/timer.c', line 95

VALUE
bird_cTimer_tick(VALUE self)
{
  struct bird_timer_data *ptr;
  Uint32 frame_stop;
  Uint32 frame_duration;
  VALUE delta;

  TypedData_Get_Struct(self, struct bird_timer_data, &bird_timer_type, ptr);

  frame_stop = SDL_GetTicks();
  frame_duration = frame_stop - ptr->frame_start;

  // If frame take less time than maximum allowed.
  if(ptr->max_frame_duration_ms > frame_duration)
  {
    SDL_Delay(ptr->max_frame_duration_ms - frame_duration);
    delta = rb_float_new(ptr->max_frame_duration_sec);
  }
  // If frame take too long time.
  else
  {
    // SDL_GetTicks return time im miliseconds, so I need to divide by 1000 to
    // get the time in seconds.
    delta = rb_float_new((double)frame_duration/1000.0);
  }

  ptr->frame_start = frame_stop;

  return delta;
}