move Building et al into Mods/

This commit is contained in:
Bob
2010-11-04 17:26:56 +13:00
committed by Chris Forbes
parent fdfa1ddf97
commit 480c5edd75
60 changed files with 322 additions and 285 deletions

View File

@@ -0,0 +1,94 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Graphics;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
class BibLayerInfo : ITraitInfo
{
public readonly string[] BibTypes = {"bib3", "bib2", "bib1"};
public readonly int[] BibWidths = {2,3,4};
public object Create(ActorInitializer init) { return new BibLayer(init.self, this); }
}
class BibLayer: IRenderOverlay, IWorldLoaded
{
World world;
BibLayerInfo info;
Dictionary<int2, TileReference<byte, byte>> tiles;
Sprite[][] bibSprites;
public BibLayer(Actor self, BibLayerInfo info)
{
this.info = info;
bibSprites = info.BibTypes.Select(x => SpriteSheetBuilder.LoadAllSprites(x)).ToArray();
self.World.ActorAdded +=
a => { if (a.HasTrait<Bib>()) DoBib(a,true); };
self.World.ActorRemoved +=
a => { if (a.HasTrait<Bib>()) DoBib(a,false); };
}
public void WorldLoaded(World w)
{
world = w;
tiles = new Dictionary<int2, TileReference<byte, byte>>();
}
public void DoBib(Actor b, bool isAdd)
{
var buildingInfo = b.Info.Traits.Get<BuildingInfo>();
var size = buildingInfo.Dimensions.X;
var bibOffset = buildingInfo.Dimensions.Y - 1;
int bib = Array.IndexOf(info.BibWidths,size);
if (bib < 0)
{
Log.Write("debug", "Cannot bib {0}-wide building {1}", size, b.Info.Name);
return;
}
for (int i = 0; i < 2 * size; i++)
{
var p = b.Location + new int2(i % size, i / size + bibOffset);
if (isAdd)
tiles[p] = new TileReference<byte, byte>((byte)((isAdd) ? bib + 1 : 0), (byte)i);
else
tiles.Remove(p);
}
}
public void Render( WorldRenderer wr )
{
var cliprect = Game.viewport.ShroudBounds( world );
cliprect = Rectangle.Intersect(Game.viewport.ViewBounds(), cliprect);
foreach (var kv in tiles)
{
if (!cliprect.Contains(kv.Key.X, kv.Key.Y))
continue;
if (world.LocalPlayer != null && !world.LocalPlayer.Shroud.IsExplored(kv.Key))
continue;
bibSprites[kv.Value.type - 1][kv.Value.image].DrawAt( wr,
Game.CellSize * kv.Key, "terrain");
}
}
}
public class BibInfo : TraitInfo<Bib> { }
public class Bib { }
}

View File

@@ -0,0 +1,152 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class BuildingInfo : ITraitInfo
{
public readonly int Power = 0;
public readonly bool BaseNormal = true;
public readonly bool WaterBound = false;
public readonly int Adjacent = 2;
public readonly bool Capturable = false;
public readonly string Footprint = "x";
public readonly int2 Dimensions = new int2(1, 1);
public readonly bool Unsellable = false;
public readonly float RefundPercent = 0.5f;
public readonly string[] BuildSounds = {"placbldg.aud", "build5.aud"};
public readonly string[] SellSounds = {"cashturn.aud"};
public readonly string DamagedSound = "kaboom1.aud";
public readonly string DestroyedSound = "kaboom22.aud";
public object Create(ActorInitializer init) { return new Building(init); }
public bool IsCloseEnoughToBase(World world, Player p, string buildingName, int2 topLeft)
{
var buildingMaxBounds = Dimensions;
if( Rules.Info[ buildingName ].Traits.Contains<BibInfo>() )
buildingMaxBounds.Y += 1;
var scanStart = world.ClampToWorld( topLeft - new int2( Adjacent, Adjacent ) );
var scanEnd = world.ClampToWorld( topLeft + buildingMaxBounds + new int2( Adjacent, Adjacent ) );
var nearnessCandidates = new List<int2>();
for( int y = scanStart.Y ; y < scanEnd.Y ; y++ )
{
for( int x = scanStart.X ; x < scanEnd.X ; x++ )
{
var at = world.WorldActor.Trait<BuildingInfluence>().GetBuildingAt( new int2( x, y ) );
if( at != null && at.Owner.Stances[ p ] == Stance.Ally && at.Info.Traits.Get<BuildingInfo>().BaseNormal )
nearnessCandidates.Add( new int2( x, y ) );
}
}
var buildingTiles = FootprintUtils.Tiles( buildingName, this, topLeft ).ToList();
return nearnessCandidates
.Any( a => buildingTiles
.Any( b => Math.Abs( a.X - b.X ) <= Adjacent
&& Math.Abs( a.Y - b.Y ) <= Adjacent ) );
}
public void DrawBuildingGrid( WorldRenderer wr, World world, string name )
{
var position = Game.viewport.ViewToWorld(Viewport.LastMousePos).ToInt2();
var topLeft = position - FootprintUtils.AdjustForBuildingSize( this );
var cells = new Dictionary<int2, bool>();
// Linebuild for walls.
// Assumes a 1x1 footprint; weird things will happen for other footprints
if (Rules.Info[name].Traits.Contains<LineBuildInfo>())
{
foreach( var t in BuildingUtils.GetLineBuildCells( world, topLeft, name, this ) )
cells.Add( t, IsCloseEnoughToBase( world, world.LocalPlayer, name, t ) );
}
else
{
var res = world.WorldActor.Trait<ResourceLayer>();
var isCloseEnough = IsCloseEnoughToBase(world, world.LocalPlayer, name, topLeft);
foreach (var t in FootprintUtils.Tiles(name, this, topLeft))
cells.Add( t, isCloseEnough && world.IsCellBuildable(t, WaterBound) && res.GetResource(t) == null );
}
wr.uiOverlay.DrawGrid( wr, cells );
}
}
public class Building : INotifyDamage, IResolveOrder, IOccupySpace
{
readonly Actor self;
public readonly BuildingInfo Info;
[Sync]
readonly int2 topLeft;
readonly PowerManager PlayerPower;
public int2 PxPosition { get { return ( 2 * topLeft + Info.Dimensions ) * Game.CellSize / 2; } }
public Building(ActorInitializer init)
{
this.self = init.self;
this.topLeft = init.Get<LocationInit,int2>();
this.Info = self.Info.Traits.Get<BuildingInfo>();
this.PlayerPower = init.self.Owner.PlayerActor.Trait<PowerManager>();
var uim = init.world.WorldActor.Trait<UnitInfluence>();
uim.Add( init.self, this );
}
public int GetPowerUsage()
{
if (Info.Power <= 0)
return Info.Power;
var health = self.TraitOrDefault<Health>();
return health != null ? (Info.Power * health.HP / health.MaxHP) : Info.Power;
}
public void Damaged(Actor self, AttackInfo e)
{
// Power plants lose power with damage
if (Info.Power > 0)
PlayerPower.UpdateActor(self, GetPowerUsage());
if (e.DamageState == DamageState.Dead)
{
self.World.WorldActor.Trait<ScreenShaker>().AddEffect(10, self.CenterLocation, 1);
Sound.Play(Info.DestroyedSound, self.CenterLocation);
}
}
public void ResolveOrder(Actor self, Order order)
{
if (order.OrderString == "Sell")
{
self.CancelActivity();
self.QueueActivity(new Sell());
}
}
public int2 TopLeft
{
get { return topLeft; }
}
public IEnumerable<int2> OccupiedCells()
{
return FootprintUtils.UnpathableTiles( self.Info.Name, Info, TopLeft );
}
}
}

View File

@@ -0,0 +1,52 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class BuildingInfluenceInfo : ITraitInfo
{
public object Create( ActorInitializer init ) { return new BuildingInfluence( init.world ); }
}
public class BuildingInfluence
{
Actor[,] influence;
Map map;
public BuildingInfluence( World world )
{
map = world.Map;
influence = new Actor[map.MapSize.X, map.MapSize.Y];
world.ActorAdded +=
a => { if (a.HasTrait<Building>())
ChangeInfluence(a, a.Trait<Building>(), true); };
world.ActorRemoved +=
a => { if (a.HasTrait<Building>())
ChangeInfluence(a, a.Trait<Building>(), false); };
}
void ChangeInfluence( Actor a, Building building, bool isAdd )
{
foreach( var u in FootprintUtils.Tiles( a.Info.Name, a.Info.Traits.Get<BuildingInfo>(), a.Location ) )
if( map.IsInMap( u ) )
influence[ u.X, u.Y ] = isAdd ? a : null;
}
public Actor GetBuildingAt(int2 cell)
{
if (!map.IsInMap(cell)) return null;
return influence[cell.X, cell.Y];
}
}
}

View File

@@ -0,0 +1,51 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class CanPowerDownInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new CanPowerDown(init); }
}
public class CanPowerDown : IResolveOrder, IDisable
{
[Sync]
bool disabled = false;
int normalPower = 0;
readonly PowerManager PowerManager;
readonly TechTree TechTree;
public CanPowerDown(ActorInitializer init)
{
PowerManager = init.self.Owner.PlayerActor.Trait<PowerManager>();
TechTree = init.self.Owner.PlayerActor.Trait<TechTree>();
normalPower = init.self.Info.Traits.Get<BuildingInfo>().Power;
}
public bool Disabled { get { return disabled; } }
public void ResolveOrder(Actor self, Order order)
{
if (order.OrderString == "PowerDown")
{
disabled = !disabled;
var eva = self.World.WorldActor.Info.Traits.Get<EvaAlertsInfo>();
Sound.PlayToPlayer(self.Owner, disabled ? eva.EnablePower : eva.DisablePower);
PowerManager.UpdateActor(self, disabled ? 0 : normalPower);
// Rebuild the tech tree; some support powers require active buildings
TechTree.Update();
}
}
}
}

View File

@@ -0,0 +1,24 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
// allow a nonstandard sell/repair value to avoid
// buy-sell exploits like c&c's PROC.
public class CustomSellValueInfo : TraitInfo<CustomSellValue>
{
public readonly int Value = 0;
}
public class CustomSellValue { }
}

View File

@@ -0,0 +1,64 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
namespace OpenRA.Mods.RA.Buildings
{
public static class FootprintUtils
{
public static IEnumerable<int2> Tiles( string name, BuildingInfo buildingInfo, int2 topLeft )
{
var dim = buildingInfo.Dimensions;
var footprint = buildingInfo.Footprint.Where(x => !char.IsWhiteSpace(x));
if (Rules.Info[ name ].Traits.Contains<BibInfo>())
{
dim.Y += 1;
footprint = footprint.Concat(new char[dim.X]);
}
return TilesWhere( name, dim, footprint.ToArray(), a => a != '_' ).Select( t => t + topLeft );
}
public static IEnumerable<int2> Tiles(Actor a)
{
return Tiles( a.Info.Name, a.Info.Traits.Get<BuildingInfo>(), a.Location );
}
public static IEnumerable<int2> UnpathableTiles( string name, BuildingInfo buildingInfo, int2 position )
{
var footprint = buildingInfo.Footprint.Where( x => !char.IsWhiteSpace( x ) ).ToArray();
foreach( var tile in TilesWhere( name, buildingInfo.Dimensions, footprint, a => a == 'x' ) )
yield return tile + position;
}
static IEnumerable<int2> TilesWhere( string name, int2 dim, char[] footprint, Func<char, bool> cond )
{
if( footprint.Length != dim.X * dim.Y )
throw new InvalidOperationException( "Invalid footprint for " + name );
int index = 0;
for( int y = 0 ; y < dim.Y ; y++ )
for( int x = 0 ; x < dim.X ; x++ )
if( cond( footprint[ index++ ] ) )
yield return new int2( x, y );
}
public static int2 AdjustForBuildingSize( BuildingInfo buildingInfo )
{
var dim = buildingInfo.Dimensions;
return new int2( dim.X / 2, dim.Y > 1 ? ( dim.Y + 1 ) / 2 : 0 );
}
}
}

View File

@@ -0,0 +1,21 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class LineBuildInfo : TraitInfo<LineBuild>
{
public readonly int Range = 5;
}
public class LineBuild {}
}

View File

@@ -0,0 +1,109 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class PowerManagerInfo : ITraitInfo
{
public readonly int AdviceInterval = 250;
public object Create(ActorInitializer init) { return new PowerManager(init, this); }
}
public class PowerManager : ITick
{
PowerManagerInfo Info;
Player Player;
Dictionary<Actor, int> PowerDrain = new Dictionary<Actor, int>();
[Sync] int totalProvided;
public int PowerProvided { get { return totalProvided; } }
[Sync] int totalDrained;
public int PowerDrained { get { return totalDrained; } }
public PowerManager(ActorInitializer init, PowerManagerInfo info)
{
Info = info;
Player = init.self.Owner;
init.world.ActorAdded += ActorAdded;
init.world.ActorRemoved += ActorRemoved;
}
void ActorAdded(Actor a)
{
if (a.Owner != Player || !a.HasTrait<Building>())
return;
PowerDrain.Add(a, a.Trait<Building>().GetPowerUsage());
UpdateTotals();
}
void ActorRemoved(Actor a)
{
if (a.Owner != Player || !a.HasTrait<Building>())
return;
PowerDrain.Remove(a);
UpdateTotals();
}
void UpdateTotals()
{
totalProvided = 0;
totalDrained = 0;
foreach (var kv in PowerDrain)
{
var p = kv.Value;
if (p > 0)
totalProvided += p;
else
totalDrained -= p;
}
}
public void UpdateActor(Actor a, int newPower)
{
if (a.Owner != Player || !a.HasTrait<Building>())
return;
PowerDrain[a] = newPower;
UpdateTotals();
}
int nextPowerAdviceTime = 0;
bool wasLowPower = false;
public void Tick(Actor self)
{
var lowPower = totalProvided < totalDrained;
if (lowPower && !wasLowPower)
nextPowerAdviceTime = 0;
wasLowPower = lowPower;
if (--nextPowerAdviceTime <= 0)
{
if (lowPower)
Player.GiveAdvice(Rules.Info["world"].Traits.Get<EvaAlertsInfo>().LowPower);
nextPowerAdviceTime = Info.AdviceInterval;
}
}
public PowerState PowerState
{
get {
if (PowerProvided >= PowerDrained) return PowerState.Normal;
if (PowerProvided > PowerDrained / 2) return PowerState.Low;
return PowerState.Critical;
}
}
}
}

View File

@@ -0,0 +1,81 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using OpenRA.Mods.RA.Effects;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class RepairableBuildingInfo : ITraitInfo, ITraitPrerequisite<HealthInfo>
{
public readonly float RepairPercent = 0.2f;
public readonly float RepairRate = 0.016f;
public readonly int RepairStep = 7;
public object Create(ActorInitializer init) { return new RepairableBuilding(init.self, this); }
}
public class RepairableBuilding : ITick, IResolveOrder
{
[Sync]
bool isRepairing = false;
Health Health;
RepairableBuildingInfo Info;
public RepairableBuilding(Actor self, RepairableBuildingInfo info)
{
Health = self.Trait<Health>();
Info = info;
}
public void ResolveOrder(Actor self, Order order)
{
if (order.OrderString == "Repair")
{
isRepairing = !isRepairing;
}
}
int remainingTicks;
public void Tick(Actor self)
{
if (!isRepairing) return;
if (remainingTicks == 0)
{
var csv = self.Info.Traits.GetOrDefault<CustomSellValueInfo>();
var buildingValue = csv != null ? csv.Value : self.Info.Traits.Get<ValuedInfo>().Cost;
var costPerHp = (Info.RepairPercent * buildingValue) / Health.MaxHP;
var hpToRepair = Math.Min(Info.RepairStep, Health.MaxHP - Health.HP);
var cost = (int)Math.Ceiling(costPerHp * hpToRepair);
if (!self.Owner.PlayerActor.Trait<PlayerResources>().TakeCash(cost))
{
remainingTicks = 1;
return;
}
self.World.AddFrameEndTask(w => w.Add(new RepairIndicator(self)));
self.InflictDamage(self, -hpToRepair, null);
if (Health.DamageState == DamageState.Undamaged)
{
isRepairing = false;
return;
}
remainingTicks = (int)(Info.RepairRate * 60 * 25);
}
else
--remainingTicks;
}
}
public class AllowsBuildingRepairInfo : TraitInfo<AllowsBuildingRepair> {}
public class AllowsBuildingRepair {}
}

View File

@@ -0,0 +1,33 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
class RequiresPowerInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new RequiresPower(init.self); }
}
class RequiresPower : IDisable
{
readonly PowerManager power;
public RequiresPower( Actor self )
{
power = self.Owner.PlayerActor.Trait<PowerManager>();
}
public bool Disabled
{
get { return power.PowerProvided < power.PowerDrained; }
}
}
}

View File

@@ -0,0 +1,75 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
class Sell : IActivity
{
IActivity NextActivity { get; set; }
bool started;
int framesRemaining;
void DoSell(Actor self)
{
var csv = self.Info.Traits.GetOrDefault<CustomSellValueInfo>();
var cost = csv != null ? csv.Value : self.Info.Traits.Get<ValuedInfo>().Cost;
var health = self.TraitOrDefault<Health>();
var refundFraction = self.Info.Traits.Get<BuildingInfo>().RefundPercent * (health == null ? 1f : health.HPFraction);
self.Owner.PlayerActor.Trait<PlayerResources>().GiveCash((int)(refundFraction * cost));
foreach (var ns in self.TraitsImplementing<INotifySold>())
ns.Sold(self);
self.Destroy();
}
public IActivity Tick(Actor self)
{
if( !started )
{
framesRemaining = self.Trait<RenderSimple>().anim.HasSequence("make")
? self.Trait<RenderSimple>().anim.GetSequence( "make" ).Length : 0;
foreach( var ns in self.TraitsImplementing<INotifySold>() )
ns.Selling( self );
started = true;
}
else if( framesRemaining <= 0 )
DoSell( self );
else
--framesRemaining;
return this;
}
public void Cancel(Actor self) { /* never gonna give you up.. */ }
public void Queue( IActivity activity )
{
if( NextActivity != null )
NextActivity.Queue( activity );
else
NextActivity = activity;
}
public IEnumerable<float2> GetCurrentPath()
{
yield break;
}
}
}

View File

@@ -0,0 +1,125 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class TechTreeInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new TechTree(init);}
}
public class TechTree
{
readonly List<Watcher> watchers = new List<Watcher>();
readonly Player player;
public TechTree(ActorInitializer init)
{
player = init.self.Owner;
init.world.ActorAdded += ActorChanged;
init.world.ActorRemoved += ActorChanged;
}
public void ActorChanged(Actor a)
{
if (a.Owner == player && a.HasTrait<Building>())
Update();
}
public void Update()
{
var buildings = GatherBuildings(player);
foreach(var w in watchers)
w.Update(buildings);
}
public void Add(string key, List<string> prerequisites, ITechTreeElement tte)
{
Add(key, prerequisites, false, tte);
}
// set requiresPowered = true to discard buildings that have an IDisabled active (eg manually powered down)
public void Add(string key, List<string> prerequisites, bool requiresPowered, ITechTreeElement tte)
{
watchers.Add(new Watcher( key, prerequisites, requiresPowered, tte ));
}
public void Remove(string key)
{
watchers.RemoveAll(x => x.key == key);
}
static Cache<string, List<Actor>> GatherBuildings( Player player )
{
var ret = new Cache<string, List<Actor>>( x => new List<Actor>() );
if (player == null)
return ret;
foreach( var b in player.World.Queries.OwnedBy[player].Where( x=>x.Info.Traits.Contains<BuildingInfo>() ) )
{
ret[ b.Info.Name ].Add( b );
var tt = b.Info.Traits.GetOrDefault<TooltipInfo>();
if( tt != null )
foreach( var alt in tt.AlternateName )
ret[ alt ].Add( b );
}
return ret;
}
class Watcher
{
public readonly string key;
// strings may be either actor type, or "alternate name" key
public readonly List<string> prerequisites;
public readonly ITechTreeElement watcher;
bool hasPrerequisites;
bool requiresPowered;
public Watcher(string key, List<string> prerequisites, bool requiresPowered, ITechTreeElement watcher)
{
this.key = key;
this.prerequisites = prerequisites;
this.watcher = watcher;
this.hasPrerequisites = false;
this.requiresPowered = requiresPowered;
}
public void Update(Cache<string, List<Actor>> buildings)
{
var nowHasPrerequisites = true;
foreach (var p in prerequisites)
if (!buildings.Keys.Contains(p) ||
(requiresPowered && buildings[p].All(b => b.TraitsImplementing<IDisable>().Any(d => d.Disabled))))
{
nowHasPrerequisites = false;
break;
}
if( nowHasPrerequisites && !hasPrerequisites )
watcher.PrerequisitesAvailable(key);
if( !nowHasPrerequisites && hasPrerequisites )
watcher.PrerequisitesUnavailable(key);
hasPrerequisites = nowHasPrerequisites;
}
}
}
public interface ITechTreeElement
{
void PrerequisitesAvailable(string key);
void PrerequisitesUnavailable(string key);
}
}

View File

@@ -0,0 +1,80 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public static class BuildingUtils
{
public static bool IsCellBuildable(this World world, int2 a, bool waterBound)
{
return world.IsCellBuildable(a, waterBound, null);
}
public static bool IsCellBuildable(this World world, int2 a, bool waterBound, Actor toIgnore)
{
if (world.WorldActor.Trait<BuildingInfluence>().GetBuildingAt(a) != null) return false;
if (world.WorldActor.Trait<UnitInfluence>().GetUnitsAt(a).Any(b => b != toIgnore)) return false;
if (waterBound)
return world.Map.IsInMap(a.X,a.Y) && world.GetTerrainInfo(a).IsWater;
return world.Map.IsInMap(a.X, a.Y) && world.GetTerrainInfo(a).Buildable;
}
public static bool CanPlaceBuilding(this World world, string name, BuildingInfo building, int2 topLeft, Actor toIgnore)
{
var res = world.WorldActor.Trait<ResourceLayer>();
return FootprintUtils.Tiles(name, building, topLeft).All(
t => world.Map.IsInMap(t.X, t.Y) && res.GetResource(t) == null &&
world.IsCellBuildable(t, building.WaterBound, toIgnore));
}
public static IEnumerable<int2> GetLineBuildCells(World world, int2 location, string name, BuildingInfo bi)
{
int range = Rules.Info[name].Traits.Get<LineBuildInfo>().Range;
var topLeft = location; // 1x1 assumption!
if (world.IsCellBuildable(topLeft, bi.WaterBound))
yield return topLeft;
// Start at place location, search outwards
// TODO: First make it work, then make it nice
var vecs = new[] { new int2(1, 0), new int2(0, 1), new int2(-1, 0), new int2(0, -1) };
int[] dirs = { 0, 0, 0, 0 };
for (int d = 0; d < 4; d++)
{
for (int i = 1; i < range; i++)
{
if (dirs[d] != 0)
continue;
int2 cell = topLeft + i * vecs[d];
if (world.IsCellBuildable(cell, bi.WaterBound))
continue; // Cell is empty; continue search
// Cell contains an actor. Is it the type we want?
if (world.Queries.WithTrait<LineBuild>().Any(a => (a.Actor.Info.Name == name && a.Actor.Location.X == cell.X && a.Actor.Location.Y == cell.Y)))
dirs[d] = i; // Cell contains actor of correct type
else
dirs[d] = -1; // Cell is blocked by another actor type
}
// Place intermediate-line sections
if (dirs[d] > 0)
for (int i = 1; i < dirs[d]; i++)
yield return topLeft + i * vecs[d];
}
}
}
}

View File

@@ -0,0 +1,38 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.Buildings
{
public class WallInfo : ITraitInfo, ITraitPrerequisite<BuildingInfo>
{
public readonly string[] CrushClasses = { };
public object Create(ActorInitializer init) { return new Wall(init.self, this); }
}
public class Wall : ICrushable, IBlocksBullets
{
readonly Actor self;
readonly WallInfo info;
public Wall(Actor self, WallInfo info)
{
this.self = self;
this.info = info;
self.World.WorldActor.Trait<UnitInfluence>().Add(self, self.Trait<Building>());
}
public IEnumerable<string> CrushClasses { get { return info.CrushClasses; } }
public void OnCrush(Actor crusher) { self.Kill(crusher); }
}
}