-- $LastChangedDate: 2010-05-25 21:26:05 -0400 (Tue, 25 May 2010) $
-- LEGAL: COPYRIGHT (C) 2010 JIM E. BROOKS WWW.PALOMINO3D.ORG
-- Play sounds.
-- See module.txt for documentation and pitfalls.
--
-- Note: This Lua code isn't as inefficient as it seems.
-- Although Lua calls C++ Sound::Play() every tick,
-- it will be a NOP if the same args are passed while it hasn't finished playing.
-- So this Lua code can be kept simple/brief by relying on the "anti-redundancy" of C++.

-----------
-- Sound --
-----------

Sound = {
    volumeThemeSong = 0.5,  -- 1.0 max volume
    volumeStall = 0.3,  -- this wave is loud
}

-- Monitor events that need sound.
function Sound:Tick()
    -- Update engine sound.
    local engineVolume = PlayerActor.aircraft:GetThrottle()  -- throttle equals volume {0.0,..,1.0}
    if ( engineVolume < 0.05 or PlayerActor:IfDestroyed() ) then
        PlayerActor.aircraft:StopEngineSound()
    else
        PlayerActor.aircraft:PlayEngineSound( engineVolume )
    end
    
    -- Update stall warning sound.
    if ( PlayerActor.aircraft:GetPhysics():IfStall() ) then
        sim.Sound:Play( "stall.wav.gz", sim.Sound.PLAY_LOOP, self.volumeStall )
    else
        sim.Sound:Stop( "stall.wav.gz" )
    end
end

-- Play theme song.
function Sound:PlayThemeSong()
    -- First test if song's volume was requested.
    if ( sim.argvMap["-song-volume"] ) then
        local idx = sim.GetArgvIdx( "-song-volume" )
        local songVolume = sim.argv[idx+1]
        if ( songVolume ) then
            self.volumeThemeSong = tonumber(songVolume) -- args was strings
        end
    end

    if ( sim.argvMap["-song"] ) then
        local idx = sim.GetArgvIdx( "-song" )
        local songName = sim.argv[idx+1]
        if ( songName ) then
            if ( sim.Sound:Play( songName, sim.Sound.PLAY_LOOP, self.volumeThemeSong ) ) then
                Log( "Theme song " .. songName .. " volume=" .. tostring(self.volumeThemeSong) )
            else
                Log( "WARNING: Failed to play theme song " .. songName )
            end
        end
    end
end
