Skip to content

Instantly share code, notes, and snippets.

@Madsy
Created October 1, 2009 14:33
Show Gist options
  • Save Madsy/198992 to your computer and use it in GitHub Desktop.
Save Madsy/198992 to your computer and use it in GitHub Desktop.
typedef struct TimeInfo
{
uint32_t accum;
uint32_t delta_error_accum;
uint32_t previous_tick;
uint32_t globaltime;
uint32_t frequency; //like 1/60 in 15.16 fixedpoint
} TimeInfo;
void UpdateTimeAccum(TimeInfo* tinfo)
{
uint32_t delta, delta_error, tick;
uint32_t current_tick = SDL_GetTicks();
if(current_tick < tinfo->previous_tick)
tick = ((UINT_MAX - tinfo->previous_tick) + current_tick + 1) * 65536;
else
tick = (current_tick - tinfo->previous_tick) * 65536;
delta = tick / 1000;
delta_error = tick % 1000;
tinfo->delta_error_accum += delta_error;
while(tinfo->delta_error_accum >= 1000){
++delta;
tinfo->delta_error_accum -= 1000;
}
tinfo->accum += delta;
tinfo->previous_tick = current_tick;
}
void WorldThink(Object* objs, int count, TimeInfo* tinfo)
{
while(tinfo->accum >= tinfo->frequency){
tinfo->globaltime += tinfo->frequency;
for(int i=0; i<count; ++i)
UpdateObject(&objs[i], (float)globaltime / 65536.0f);
tinfo->accum -= tinfo->frequency;
}
}
void WorldDraw(Object* objs, int count, TimeInfo* tinfo)
{
for(int i=0; i<count; ++i){
ObjectState* s0 = objs[i].state[0]; //current state
ObjectState* s1 = objs[i].state[1]; //next state
float t = (float)tinfo->accum / tinfo->frequency; //leftover after the integration
ObjectState* drawstate = Interpolate(s0, s1, t);
DrawObject(objs[i], drawstate);
}
}
int main(int argc, const char* argv[])
{
Object objects[128];
TimeInfo tinfo;
/* initialize everything
...
*/
while(running)
{
UpdateTimeAccum(&tinfo);
WorldThink(objects, 128, &tinfo);
WorldDraw (objects, 128, &tinfo);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment