-- $LastChangedDate: 2009-12-06 21:22:01 -0600 (Sun, 06 Dec 2009) $
-- This chunk is called every timer-tick.
-- See module.txt for documentation and pitfalls.

-- Manipulator mode?
if ( sim.manipulatorMode ) then
    ManipulatorMode.Tick()
    return
end

-- Keyboard handler (before checking if paused else cannot unpause).
local keyEvent = sim.Keyboard:DequeueKey()
if ( keyEvent ) then
    Keyboard:Handler( keyEvent )
end

-- Paused?
if ( sim.Program:IfPaused() ) then
    return
end

-- Joystick handler.
Joystick:Handler()

-- Update sounds.
Sound:Tick()

-- Call registered timer-tick callbacks.
Timer:Tick()

-- Process commands from the simulator's "command queue".
CommandQueue:Process()  -- cmd.lua

-- CRITICAL: Collect garbage to induce freeing memory of 3D models
-- (which consume large amounts of memory).
local elapsedTime = sim.Base:GetElapsedTime()
if ( (not garbageCollectionTime) or (elapsedTime - garbageCollectionTime > 500) ) then
    garbageCollectionTime = elapsedTime  -- milliseconds
    collectgarbage()
end
