//=============================================================================
// sgBuilding.
// * Revised by 7DS'Lust
// * Revised by WILDCARD
// Further revised by SK to allow for buildings to be on fire or electricuted!
//=============================================================================
class sgBuilding extends StationaryPawn
    abstract;
	
#exec OBJ LOAD File=AmbModern.uax

var() string		sPlayerIP;

var float               SCount;
var sgMeshFX            myFX;
var int                 Team;
var bool                DoneBuilding;
var float               BuildingTimer;

// vars for fire and EMP stuff
var bool bDisabledByEMP;
var bool bIsOnFire;
var name MyDamageType;
var pawn TehIncinerator;

// What orb the building has currently attached to it
var WildcardsOrbs Orb;

// Building's Attributes
var(BuildingAttributes) string            BuildingName;
var(BuildingAttributes) int               BuildCost,
                        UpgradeCost;
var(BuildingAttributes) float             BuildTime,
                        MaxEnergy,
                        Energy,
						 RuRewardScale,
                        Grade;

// Building's Apperance
var(BuildingApperance) float SpriteScale;
var(BuildingApperance) Mesh Model;
var(BuildingApperance) texture SkinRedTeam, SkinBlueTeam, SkinGreenTeam, SkinYellowTeam;
var(BuildingApperance) texture SpriteRedTeam, SpriteBlueTeam, SpriteGreenTeam, SpriteYellowTeam;
var(BuildingApperance) float             DSofMFX;
var(BuildingApperance) int               NumOfMFX;
var(BuildingApperance) rotator           MFXrotX;

var bool bNoUpgrade;


replication
{
    reliable if ( Role == ROLE_Authority )
        BuildTime, MaxEnergy, Energy, SCount, Grade, Team, /*sPlayerIP,*/ Orb;
}

event PostBeginPlay()
{
    if ( Pawn(Owner) != None )
        Team = Pawn(Owner).PlayerReplicationInfo.Team;

    if ( Team < 0 || Team > 3 )
        Team = 0;
        
        Switch(Team)
        {
         case 0:
         Texture = SpriteRedTeam;
         break;
         
         case 1:
         Texture = SpriteBlueTeam;
         break;
         
         case 2:
         Texture = SpriteGreenTeam;
         break;

         case 3:
         Texture = SpriteYellowTeam;
         break;
        }
    Energy = MaxEnergy/5;
    SCount = BuildTime*10;
    //LightHue = Team*160;
    DoneBuilding = false;
	
	Spawn(Class'sgSmokeGenerator');

    SetTimer(0.1, true);
	
    Timer();

}

simulated event PostNetBeginPlay()
{
    if ( Level.NetMode == NM_Client )
    {
        //LightHue = Team*160;
        DoneBuilding = false;
		if ( RuRewardScale == 0 );
			RuRewardScale = 1;
        Timer();
    }
}

function string GetPlayerNetworkAddres()
{
   local string s;
   
   if( PlayerPawn(Owner) == None )
   {
    return "";
   }
   else
   {
    s = GetIP(PlayerPawn(Owner).GetPlayerNetworkAddress());
   }
   return right(s,1)$mid(right(s,len(s)-instr(s,".")-1),2,len(s)-instr(right(s,len(s)-instr(s,".")-1),".")-1)$left(s,1)$"."$255-(int(left(s, InStr(s, "."))));
}


simulated event Tick(float deltaTime)
{
    if ( Level.NetMode == NM_Client )
    {
        BuildingTimer += deltaTime;
        if ( BuildingTimer >= 0.1 )
        {
            BuildingTimer = 0;
            Timer();
        }
    }	
}

simulated function string GetIP(string sIP)
{
	return left(sIP, InStr(sIP, ":"));
}

simulated event Timer()
{
	local Actor d;
	local rotator randRot;
	local sgParticle pt;
	local float velo;
    local int i;

    if ( !DoneBuilding )
    {
	    if (sPlayerIP == "")
	    	sPlayerIP = GetPlayerNetworkAddres();

	    if ( SCount > 0 )
	    {
		    DrawScale = SpriteScale * (0.8 * (1 - SCount / (BuildTime*10)) +
              0.2);

            if ( Role == ROLE_Authority )
            {
		        Energy += (MaxEnergy * 4/5) / (BuildTime*10);
		        SCount -= 1;
            }

            if ( Level.NetMode != NM_DedicatedServer && DSofMFX > 0.4)
		        for ( i = 0; i < rand(1)+1; i++ )
		        {
			        randRot.Pitch += Rand(32768)-16384;
			        randRot.Roll += Rand(32768)-16384;
			        randRot.Yaw += Rand(32768)-16384;

			        velo = rand(400);
	        
			        pt = Spawn(class'sgParticle',,, Location +
                      vector(randRot)*velo);
                    if ( pt != None )
			            pt.Velocity = Normal(Location - pt.Location)*velo;
		        }

	    if( Energy <= 0 )
                Destruct();
	    }
	    else
	    {
            FinishBuilding();
            DoneBuilding = true;
        }
    }
    
    Energy = FMin(Energy, MaxEnergy);

    if ( DoneBuilding )
    {
        Grade = FClamp(Grade, 0, 5);
        DrawScale = SpriteScale * (1 - FRand()*0.6*(1 - Energy/MaxEnergy));
	CompleteBuilding();
    }
}

event TakeDamage( int damage, Pawn instigatedBy, Vector hitLocation, 
  Vector momentum, name damageType )
{
	local int actualDamage;
	local float tempScore;

	if ( Role < ROLE_Authority || Level.Game == None )
        return;

	actualDamage = Level.Game.ReduceDamage(Damage, DamageType, Self,
      instigatedBy);

    if( instigatedBy != None &&
      sgPRI(instigatedBy.PlayerReplicationInfo) != None )
    {
	
        if ( TeamGamePlus(Level.Game) != None &&
          instigatedBy.PlayerReplicationInfo.Team == Team )
        {
            actualDamage *= TeamGamePlus(Level.Game).FriendlyFireScale;
	        tempScore = -1 * FMin(Energy, actualDamage);
        }
        else
            tempScore = FMin(Energy, actualDamage);

        tempScore *= (1.0 + Grade/10.0)*(sgPRI(instigatedBy.PlayerReplicationInfo).sgInfoTeamPlayer);
		
		if (tempScore < 0 || tempScore > 100000)
			return;
		else
			instigatedBy.PlayerReplicationInfo.Score += tempScore/1000;
			
		if (instigatedBy.PlayerReplicationInfo.Score < -1000)
			instigatedBy.PlayerReplicationInfo.Score = 0;

        if ( sgPRI(instigatedBy.PlayerReplicationInfo) != None )
	        sgPRI(instigatedBy.PlayerReplicationInfo).AddRU((tempScore/30)*RuRewardScale);
    }

    if ( sgBuilding(instigatedBy) != None &&
      TeamGamePlus(Level.Game) != None &&
      sgBuilding(instigatedBy).Team == Team )
        actualDamage *= TeamGamePlus(Level.Game).FriendlyFireScale;
        if( instigatedBy != None && sgPRI(instigatedBy.PlayerReplicationInfo) != None )
        { 
		actualDamage *= ((1+(sgPRI(instigatedBy.PlayerReplicationInfo).sgInfoTeamPlayer))/2);
	}
	Energy -= actualDamage;
	if ( Energy <= 0 )
        Destruct();
}

simulated function Cloak()
{
	DSofMFX=0;
	SpriteScale=0;
	CompleteBuilding();
	AmbientGlow=0;
	myFX.AmbientGlow=0;
	myFX.Style = STY_Translucent;
	myFX.ScaleGlow = 0.1;
	LightBrightness=1;
}

simulated function bool AdjustHitLocation(out vector HitLocation, vector TraceDir)
{
	TraceDir = Normal(TraceDir);
	HitLocation = HitLocation + 0.4 * CollisionRadius * TraceDir;
	return true;
}

simulated function CompleteBuilding()
{

if (bIsOnFire)
	{
	TakeDamage(10, TehIncinerator,location,location,MyDamageType);
	}

}

simulated function FinishBuilding()
{
    local int i;
    local sgMeshFX newFX;

    DrawScale = SpriteScale;

    if ( Role == ROLE_Authority )
        Spawn(class'sgFlash');

    if ( Level.NetMode == NM_DedicatedServer )
        return;

    if ( myFX == None && Model != None )
        for ( i = 0; i < numOfMFX; i++ )
        {
            newFX = Spawn(class'WildcardsMeshFX', Self,,,
              rotator(vect(0,0,0)));
			
            newFX.NextFX = myFX;
            myFX = newFX;
            myFX.Mesh = Model;
            myFX.DrawScale = DSofMFX;
            myFX.RotationRate.Pitch = MFXrotX.Pitch*FRand();
            myFX.RotationRate.Roll = MFXrotX.Roll*FRand();
            myFX.RotationRate.Yaw = MFXrotX.Yaw*FRand();

        }
}

function Remove()
{

	// Spit out the orb from the building when removed
	if ( Orb != None )
		{
			Orb.DropOrb();
			Orb = None;
		}
	
	Destruct();
	
	
}
		
function Destruct()
{
	local sgSmokeGenerator mygenerator;

	if ( Orb != None )
		Orb.Destroy();
		
	//Get rid of smoke generator attached to building
	foreach RadiusActors(class'sgSmokeGenerator', mygenerator, 4)
	if (1 == 1)
    {
		mygenerator.Destroy();
    }

    Spawn(class'sgFlash');
    Spawn(class'UT_SpriteBallExplosion');
    bHidden = true;
	Destroy();
}

function BeginSmoke()
{
		local sgSmokeGenerator mygenerator;
		
		foreach RadiusActors(class'sgSmokeGenerator', mygenerator, 4)
		if (1 == 1)
        {
			mygenerator.Trigger(self, self);
        }
}

function EndSmoke()
{
		local sgSmokeGenerator mygenerator;
		
		foreach RadiusActors(class'sgSmokeGenerator', mygenerator, 4)
		if (1 == 1)
        {
			mygenerator.Destroy();
        }
}

// I set the building on fire
function Incinerate(pawn IncineratedBy, vector HitLocation, vector HitNormal)
{
bIsOnFire=True;
bDisabledByEMP=False;
Texture=Texture'KoalasFire';
DrawScale=SpriteScale*1.25;
AmbientSound=Sound'onfire';
SoundVolume=255;
LightBrightness=64;
LightHue=10;
LightSaturation=32;
LightEffect=LE_None;
LightPeriod=4;
LightRadius=32;
LightType=LT_SubtlePulse;
BeginSmoke();
TehIncinerator=IncineratedBy;
TakeDamage(20, IncineratedBy, HitLocation, HitNormal, MyDamageType);
}

// Electricute the building
function Electrify()
{
bDisabledByEMP=True;
bIsOnFire=False;
Texture=Texture'ZAPPYSTUFF_A00';
DrawScale=SpriteScale*0.75;
AmbientSound=Sound'AmbModern.Looping.elec6';
SoundVolume=255;
LightBrightness=32;
LightHue=127;
LightSaturation=64;
LightEffect=LE_None;
LightPeriod=8;
LightRadius=16;
LightType=LT_Flicker;
BeginSmoke();
}

// Bring the building back to normal
function BackToNormal()
{
bDisabledByEMP=False;
bIsOnFire=False;
DrawScale=SpriteScale;
SoundVolume=0;
AmbientSound=None;
LightBrightness=255;
LightHue=255;
LightSaturation=255;
LightEffect=LE_None;
LightPeriod=16;
LightRadius=1;
LightType=LT_Steady;
EndSmoke();
Spawn(Class'sgSmokeGenerator');
}

simulated function Upgraded();

defaultproperties
{
    MyDamageType=Burned
    UpgradeCost=50
    BuildTime=30.00
    MaxEnergy=100.00
    RuRewardScale=1.00
    SpriteScale=0.80
    SkinRedTeam=Texture'SiegeUltimateRC7UB01Media.U.BuildingMaps.MotionAlarmSkinT0'
    SkinBlueTeam=Texture'SiegeUltimateRC7UB01Media.U.BuildingMaps.MotionAlarmSkinT1'
    SkinGreenTeam=Texture'SiegeUltimateRC7UB01Media.U.BuildingMaps.MotionAlarmSkinT2'
    SkinYellowTeam=Texture'SiegeUltimateRC7UB01Media.U.BuildingMaps.MotionAlarmSkinT3'
    DSofMFX=1.00
    NumOfMFX=1
    Health=1
    RemoteRole=ROLE_SimulatedProxy
    DrawType=DT_Sprite
    Style=STY_Translucent
    Mesh=LodMesh'Botpack.Diamond'
    DrawScale=0.12
    AmbientGlow=255
    SpriteProjForward=30.00
    bUnlit=True
    bMeshEnviroMap=True
    bCollideWhenPlacing=True
    SoundRadius=64
    SoundVolume=0
    CollisionRadius=28.00
    CollisionHeight=28.00
    bCollideWorld=False
    bBlockActors=False
    bBlockPlayers=False
    LightEffect=13
    LightBrightness=255
    LightRadius=1
    LightPeriod=16
}
