void executeStack(StateStack& stack, SDL_Window& window, bool* pTerminator)
    {
        std::vector<const SDL_Event> events;
        SDL_Event e;

        bool localRunning = true;
        bool& running = pTerminator ? *pTerminator : localRunning;

        Uint64 t0 = SDL_GetPerformanceCounter();

        while (!stack.empty() && running == true)
        {
            while (SDL_PollEvent(&e) != 0)
            {
                if (e.type == SDL_QUIT)
                {
                    running = false;
                }
                events.push_back(e);
            }

            Uint64 now = SDL_GetPerformanceCounter();
            float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            tickStack(stack, events, dt);
            events.clear();

            SDL_GL_SwapWindow(&window);
            t0 = now;
        }
    }
Example #2
0
void Core::run()
{
    uint64_t frequency = SDL_GetPerformanceFrequency();
    uint64_t fixedStep = frequency / static_cast<uint64_t>(kStepRate);
    uint64_t maxTotalDelta = fixedStep * 6;
    uint64_t stepTime = SDL_GetPerformanceCounter();

    while(!done_)
    {
        uint64_t loopTime = SDL_GetPerformanceCounter();

        if(loopTime > stepTime + maxTotalDelta)
        {
            stepTime = loopTime - maxTotalDelta;
        }

        while(loopTime >= stepTime + fixedStep)
        {
            handleEvents();
            sessionManager_->handleBlobs();
            step(fp_t(1.0) / kStepRate);
            stepTime += fixedStep;
        }

#ifndef HEADLESS
        fp_t interp = static_cast<fp_t>(loopTime - stepTime) / static_cast<fp_t>(frequency);
        renderer_->render(interp);
#else
        // simulate ~83 without game logic
        SDL_Delay(12);
#endif
    }
}
Example #3
0
/*
================
Sys_DoubleTime
================
*/
double Sys_DoubleTime( void )
{
	static longtime_t g_PerformanceFrequency;
	static longtime_t g_ClockStart;
	longtime_t CurrentTime;
#ifdef XASH_SDL
	if( !g_PerformanceFrequency )
	{
		g_PerformanceFrequency = SDL_GetPerformanceFrequency();
		g_ClockStart = SDL_GetPerformanceCounter();
	}
	CurrentTime = SDL_GetPerformanceCounter();
	return (double)( CurrentTime - g_ClockStart ) / (double)( g_PerformanceFrequency );
#elif _WIN32
	if( !g_PerformanceFrequency )
	{
		g_PerformanceFrequency = GetPerformanceFrequency();
		g_ClockStart = GetPerformanceCounter();
	}
	CurrentTime = GetPerformanceCounter();
	return (double)( CurrentTime - g_ClockStart ) / (double)( g_PerformanceFrequency );

#else
	struct timespec ts;
	if( !g_PerformanceFrequency )
	{
		struct timespec res;
		if( !clock_getres(CLOCK_MONOTONIC, &res) )
			g_PerformanceFrequency = 1000000000LL/res.tv_nsec;
	}
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return (double) ts.tv_sec + (double) ts.tv_nsec/1000000000.0;
#endif
}
Example #4
0
int main(int argc, char *argv[])
{
	TankGame game;

	float tick_duration = 1000.0f / SDL_GetPerformanceFrequency();
	float frame_ticks = SDL_GetPerformanceFrequency() * 1.0f / 60.0f;
	auto timer = SDL_GetPerformanceCounter();

	if (game.initialize(false))
	{
		game.loadLevel01();

		for (int i = 0; i < 500; ++i)
		{
			if (game.getPlayerTank())
			{
				game.getPlayerTank()->turnTurret(0.02);
				if (i % 4 == 0) game.getPlayerTank()->fireBullet(5.0f);
			}
			
			game.updateLogic(1.0f/60.0);
			game.render();

			auto now = SDL_GetPerformanceCounter();
			float delay = frame_ticks - (float)(now - timer);
			if (delay > 0)
			{
				SDL_Delay(delay * tick_duration);
			}
			timer = SDL_GetPerformanceCounter();
		}
	}
}
Example #5
0
void OpenGlCamera::UpdateCamera(const Uint8 *keyboard_state, int *x, int *y) {
    double render_time = (SDL_GetPerformanceCounter() - last_call_time_) / (double)SDL_GetPerformanceFrequency();
    last_call_time_ = SDL_GetPerformanceCounter();

    // the mouse movement doesn't depend on the render_time (fps)
    this->camera_data_->AddRot((-*y) * 0.001f * this->camera_data_->camera_sensitivity, (-*x) * 0.001f * this->camera_data_->camera_sensitivity, 0.0f);

    /*if (keyboard_state[SDL_SCANCODE_Q])
        this->camera_data->AddRot(0.0f, 0.0f, +render_time * this->camera_data_->speed * 0.1f);
    if (keyboard_state[SDL_SCANCODE_E])
        this->camera_data->AddRot(0.0f, 0.0f, -render_time * this->camera_data_->speed * 0.1f);*/

    // Movement
    if (keyboard_state[SDL_SCANCODE_Q])
        this->camera_data_->AddPos(0.0f, 0.0f, -render_time * this->camera_data_->camera_speed);
    if (keyboard_state[SDL_SCANCODE_E])
        this->camera_data_->AddPos(0.0f, 0.0f, +render_time * this->camera_data_->camera_speed);

    if (keyboard_state[SDL_SCANCODE_W] || keyboard_state[SDL_SCANCODE_UP])
        this->camera_data_->AddPos(+render_time * this->camera_data_->camera_speed, 0.0f, 0.0f);
    if (keyboard_state[SDL_SCANCODE_A] || keyboard_state[SDL_SCANCODE_LEFT])
        this->camera_data_->AddPos(0.0f, +render_time * this->camera_data_->camera_speed, 0.0f);
    if (keyboard_state[SDL_SCANCODE_S] || keyboard_state[SDL_SCANCODE_DOWN])
        this->camera_data_->AddPos(-render_time * this->camera_data_->camera_speed, 0.0f, 0.0f);
    if (keyboard_state[SDL_SCANCODE_D] || keyboard_state[SDL_SCANCODE_RIGHT])
        this->camera_data_->AddPos(0.0f, -render_time * this->camera_data_->camera_speed, 0.0f);
}
Example #6
0
	void delay()
	{
		if (disabled)
			return;

		int64_t tickDelta = SDL_GetPerformanceCounter() - lastTickCount;
		int64_t toDelay = tpf - tickDelta;

		/* Compensate for the last delta
		 * to the ideal timestep */
		toDelay -= adj.idealDiff;

		if (toDelay < 0)
			toDelay = 0;

		delayTicks(toDelay);

		uint64_t now = lastTickCount = SDL_GetPerformanceCounter();
		int64_t diff = now - adj.last;
		adj.last = now;

		/* Recalculate our temporal position
		 * relative to the ideal timestep */
		adj.idealDiff = diff - tpf + adj.idealDiff;

		if (adj.resetFlag)
		{
			adj.idealDiff = 0;
			adj.resetFlag = false;
		}
	}
Example #7
0
uint64_t Sys_Microseconds( void )
{
	static Uint64 base = 0;	
	if( !base )
		base = SDL_GetPerformanceCounter();
	return 1000000ULL * ( SDL_GetPerformanceCounter() - base ) / freq;
}
Example #8
0
void GameTimer::Start( )
{
	m_Started 			= true;
	m_Paused 			= false;
	m_StartTicks 		= SDL_GetPerformanceCounter( );
	m_LastCheckedTicks 	= SDL_GetPerformanceCounter( );
	m_TicksPerSec 		= SDL_GetPerformanceFrequency( );
}
Example #9
0
void FrameCounter::TickFrame()
{
	m_frameTimes[m_overwritePos] = SDL_GetPerformanceCounter() - m_startTime;
	m_maxFrameTime = std::max( m_frameTimes[m_overwritePos], m_maxFrameTime );
	m_nrOfFrames++;
	m_nrOfFrames = std::min( m_nrOfFrames, FRAMECOUNTER_NR_OF_SAMPLES );
	m_overwritePos = ( m_overwritePos + 1 ) % FRAMECOUNTER_NR_OF_SAMPLES;
	m_startTime = SDL_GetPerformanceCounter();
}
Example #10
0
/// <summary>
/// Calculates the time elapsed since this function was last called and sets the internal delta time to this value.
/// If the timer is paused or has not yet been started it sets the internal delta time value to 0.
/// </summary>
void GameTimer::Tick( )
{
	if ( !m_Paused && m_Started )
	{
		m_DeltaTicks = SDL_GetPerformanceCounter( ) - m_LastCheckedTicks;
		m_DeltaTime = m_DeltaTicks / static_cast<float>(m_TicksPerSec);
	}
	else
		m_DeltaTime = 0.0;

	m_LastCheckedTicks = SDL_GetPerformanceCounter( );
}
Example #11
0
	FPSLimiter(uint16_t desiredFPS)
	    : lastTickCount(SDL_GetPerformanceCounter()),
	      tickFreq(SDL_GetPerformanceFrequency()),
	      tickFreqMS(tickFreq / 1000),
	      tickFreqNS((double) tickFreq / NS_PER_S),
	      disabled(false)
	{
		setDesiredFPS(desiredFPS);

		adj.last = SDL_GetPerformanceCounter();
		adj.idealDiff = 0;
		adj.resetFlag = false;
	}
Example #12
0
void ImGui_ImplSDL2_NewFrame(SDL_Window* window)
{
    ImGuiIO& io = ImGui::GetIO();
    IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");

    // Setup display size (every frame to accommodate for window resizing)
    int w, h;
    int display_w, display_h;
    SDL_GetWindowSize(window, &w, &h);
    SDL_GL_GetDrawableSize(window, &display_w, &display_h);
    io.DisplaySize = ImVec2((float)w, (float)h);
    if (w > 0 && h > 0)
        io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);

    // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
    static Uint64 frequency = SDL_GetPerformanceFrequency();
    Uint64 current_time = SDL_GetPerformanceCounter();
    io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f);
    g_Time = current_time;

    ImGui_ImplSDL2_UpdateMousePosAndButtons();
    ImGui_ImplSDL2_UpdateMouseCursor();

    // Update game controllers (if enabled and available)
    ImGui_ImplSDL2_UpdateGamepads();
}
Example #13
0
void app::perf::dump(bool log)
{
    // Sample the timer.

    Uint64 current = SDL_GetPerformanceCounter();
    Uint64 persec  = SDL_GetPerformanceFrequency();

    // Calculate the timings.

    double d1 = double(current - local_start) / double(persec);
    double dn = double(current - total_start) / double(persec);
    double m1 = 1000.0 * d1 / local_frames;
    double mn = 1000.0 * dn / total_frames;
    int   fps = int(ceil(local_frames / d1));

    local_start = current;

    // Report to a string. Set the window title and log.

    std::ostringstream str;

    str << std::fixed << std::setprecision(1) << m1  << "ms "
                                       << "(" << mn  << "ms) "
                                              << fps << "fps";

    SDL_SetWindowTitle(window, str.str().c_str());

    if (log) std::cout << str.str() << std::endl;
}
Example #14
0
double
updateDeltaTime()
{
    Uint64 curTime;
    double deltaTime;

    if (prevTime == 0) {
        prevTime = SDL_GetPerformanceCounter();
    }

    curTime = SDL_GetPerformanceCounter();
    deltaTime = (double) (curTime - prevTime) / (double) SDL_GetPerformanceFrequency();
    prevTime = curTime;

    return deltaTime;
}
Example #15
0
void Clock::Initialize()
{
	DEBUGPRINTF( "Initializing Clock\n" );

	ShutDown();

#if BUILD_WINDOWS_NO_SDL
	LARGE_INTEGER Frequency;
	LARGE_INTEGER Counter;

	QueryPerformanceFrequency( &Frequency );
	QueryPerformanceCounter( &Counter );

	m_Resolution			= 1.0 / (double)Frequency.QuadPart;
	m_PhysicalBaseTime		= Counter.QuadPart;
#endif

#if BUILD_SDL
	Uint64 Frequency	= SDL_GetPerformanceFrequency();
	Uint64 Counter		= SDL_GetPerformanceCounter();

	m_Resolution			= 1.0 / static_cast<double>( Frequency );
	m_PhysicalBaseTime		= Counter;
#endif

	m_PhysicalDeltaTime		= 0;
	m_MachineDeltaTime		= 0.0f;
	m_GameDeltaTime			= 0.0f;

	m_PhysicalCurrentTime	= 0;
	m_MachineCurrentTime	= 0.0f;
	m_GameCurrentTime		= 0.0f;

	m_TickCount				= 0;
}
Example #16
0
int main(int _argc, char *_argv[])
{
    try
    {
        bool quit = false;
        SDLState sdl;
        DispatchStack &dispatch = DispatchStack::get();
        Game game;
        Update update;

        glEnable(GL_TEXTURE_2D);
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);

        update.ticksLast = SDL_GetPerformanceCounter();
        update.tickFrequency = SDL_GetPerformanceFrequency(); // Should really refresh this.

        while(!quit)
        {
            SDL_Event event;
            while(SDL_PollEvent(&event))
            {
                if(!dispatch.handleEvent(event)
                        && (event.type == SDL_QUIT))
                    quit = true;
            }

            update.ticksNow = SDL_GetPerformanceCounter();
            update.dt = float((update.ticksNow - update.ticksLast) / double(update.tickFrequency));
            dispatch.update(update);
            update.ticksLast = update.ticksNow;

            dispatch.handleIdle();
            SDL_Delay(0);
        }
    }
    catch(std::exception tExc)
    {
        std::cerr << "An exception occurred: " << tExc.what() << std::endl;
        return -1;
    }
    catch(...)
    {
        std::cerr << "An unknown exception occurred." << std::endl;
        return -2;
    }
}
Example #17
0
//===========================================================================
void Timer::SetPaused (bool paused) {
	// If unpausing, don't count all the previous time that's elapsed.
	if (m_paused && !paused) {
		m_sdlCounterLast = SDL_GetPerformanceCounter();
	}

	m_paused = paused;
}
Example #18
0
void GameTimer::Pause( )
{
	if ( !m_Paused && m_Started )
	{
		m_Paused = true;
		m_PausedTicks = SDL_GetPerformanceCounter( ) - m_StartTicks;
	}
}
Example #19
0
static uint64_t get_performance_counter()
{
	Assertion(Timer_inited, "This function can only be used when the timer system is initialized!");

	auto counter = SDL_GetPerformanceCounter();

	return counter - Timer_base_value;
}
Example #20
0
void SimKit::FPSTimeline::log_frame_end() {
    this->frame_end = SDL_GetPerformanceCounter();
    this->frame_recorded = true;

    this->past_frames[this->past_frames_ctr % SimKit::FPSTimeline::NUM_PAST_FRAMES] =
        ((float)(this->frame_end - this->frame_begin) / (float)SDL_GetPerformanceFrequency()) * MICROSECONDS_PER_SECOND;
    this->past_frames_ctr++;
};
Example #21
0
// ------------------------------------------------------------------------------------------------
// Timer Class
// ------------------------------------------------------------------------------------------------
cTimer::cTimer(const cTimer::timerState_t tState) {
	state = tState;
	dt = 0.0;

	now = SDL_GetPerformanceCounter();
	prev = now;
	cpuFreq = SDL_GetPerformanceFrequency();
}
 int ViewPanel::getContiniousValue(int interval) {
     int tick = SDL_GetPerformanceCounter() / interval % 512;
     if (tick > 255) {
         return 512 - tick;
     } else {
         return tick;
     }
 }
Example #23
0
static real32_t sdl_get_seconds_elapsed(uint64_t prev_counter, uint64_t counter_freq)
{
	real32_t result;
	uint64_t current_counter;

	current_counter = SDL_GetPerformanceCounter();
	result = (real32_t)((real64_t)(current_counter - prev_counter) / (real64_t)counter_freq);
	return (result);
}
Example #24
0
void GameTimer::UnPause( )
{
	if ( m_Paused )
	{
		m_Paused = false;
		m_StartTicks = SDL_GetPerformanceCounter( ) - m_PausedTicks;
		m_PausedTicks = 0;
	}
}
Example #25
0
/**
 * \brief	Automatically profiles a scope, or you can call the Stop() function.
 * \para	name Identifier for the profiling entry.
 * \para	accumulation Wether or not to accumulate times over a frame
 * \para	mainThread (Optional) If this profiling is run on a separate thread set this to true.
 */
AutoProfiler::AutoProfiler (const rString& name, Profiler::PROFILER_CATEGORY category, bool accumulation, bool mainThread )
	: m_Name ( name ), m_MainThread ( mainThread ), m_Accumulation ( accumulation ), m_Category(category)
{
	if ( mainThread && !accumulation )
	{
		Profiler::ProfilerManager::GetInstance().StartEntry ( name );
	}
	m_StartTime = SDL_GetPerformanceCounter();
}
Example #26
0
uint32_t TimeCounterGetMsec()
{
	uint64_t perfCounter = SDL_GetPerformanceCounter();
    uint64_t perfFreq = SDL_GetPerformanceFrequency();

    uint32_t msec = ( uint32_t )( 1000000 * perfCounter / perfFreq );
    
	return msec;
}
Example #27
0
//
// Update Functions -------------------------------------------
//
cTimer *cTimer::tick(void) {
	if (state != RUNNING)
		return this;

	now = SDL_GetPerformanceCounter();
	dt = (now - prev) / (float) cpuFreq;
	prev = now;
	return this;
}
Example #28
0
int main() {
  double *fs = malloc(SIZE * sizeof (double));
  int i;
  Uint64 c, acc;

  srand(SEED);
  acc = 0;
  for (i = 0; i < SIZE; i++) {
    fs[i] = rand()/(double)RAND_MAX;
    fs[i] *= 2.0;
    fs[i] -= 1.0;
    c = SDL_GetPerformanceCounter();
    fs[i] = fclamp0(fs[i], D_MAX);
    acc += SDL_GetPerformanceCounter() - c;
  }
  free(fs);
  printf("%f secs\n", acc/(double) SDL_GetPerformanceFrequency());
  return 0;
}
Example #29
0
	void endTiming()
	{
		acc += SDL_GetPerformanceCounter() - ticks;

		if (++counter < iter)
			return;

		Debug() << "Avg. CPU time:" << ((double) acc / (iter * (perfFreq / 1000))) << "ms";
		acc = counter = 0;
	}
Example #30
0
void AutoProfiler::Stop()
{
	if ( m_Accumulation )
	{
		Profiler::ProfilerManager::GetInstance().IncrementAccumulationEntry( SDL_GetPerformanceCounter() - m_StartTime, m_Name, m_Category );
	}
	else
	{
		if ( m_MainThread )
		{
			Profiler::ProfilerManager::GetInstance().EndEntry ( SDL_GetPerformanceCounter() - m_StartTime, "", m_Category );
		}
		else
		{
			Profiler::ProfilerManager::GetInstance().EndEntry ( SDL_GetPerformanceCounter() - m_StartTime, m_Name, m_Category );
		}
	}
	m_Stopped = true;
}