--------------------------------------------------------------------------------
-- Jorge Eremiev - May 21, 2008
--
-- Particle system used in the level selector
--------------------------------------------------------------------------------

--[[ INITIALIZATION PHASE ]] 

-- Create our custom variables
pVelocity = Allocate(2); 
pAge = Allocate(1);

if not initialColor then
   initialColor = Color(1, 1, 1, 0.6); 
end

if not finalColor then
   finalColor = Color(1, 1, 1, 0);
end
lifetime = 350;

fadeInTime = 0.1 * lifetime;
fadeOutTime = 0.6 * lifetime;
deathTime = 0.3 * lifetime;

-- Set the particles texture
SetTexture("level_select_particle");
SetBlendMode(kBlendAdditiveAlpha);

-- The maximun number of particles available
SetNumParticles(10);

--[[ ACTION PHASE ]]

-- Give initial values to some of the variables
fScale = 0.15;
pScale:Init(fScale);
pPosition:Init(fRange(Vec2(-1, -1), Vec2(1, 1)));
pVelocity:Init(fRange(Vec2(-150, -150), Vec2(150, 150)));


-- Update the particles velocity and position
pVelocity:Anim(pVelocity + fTimeScale(fRange(Vec2(-20, -1), Vec2(20, -30))));
pPosition:Anim(pPosition + fTimeScale(pVelocity));

-- Update the particles age
pAge:Anim(pAge + fAge());

-- Set the particles color according to its age
pColor:Anim(fFade(pAge, finalColor, fadeInTime, initialColor, fadeOutTime, initialColor, deathTime, finalColor));

-- Make the particle bigger
pScale:Anim(pScale + fTimeScale(0.25));

-- Kill the particle if it's too old
Anim(fExpire(fGreater(pAge, lifetime)));

-- This variable must be changed from C++, when the worker starts working
gActive = true;
local creationTimer
createTimer = true

-- Define the Update function
function Update(seconds)
   if gActive then                   
      CreateParticles(seconds * 600);
       
      if createTimer then 
         creationTimer = NewTimeout(0.03) 
         createTimer = false
      end   
      end                           
      
      if creationTimer then
         if creationTimer(seconds) then
            gActive = false;
         end
      end
end
