context: #region Copyright & License Information
  /*
   * Copyright 2007-2016 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, either version 3 of
   * the License, or (at your option) any later version. For more
   * information, see COPYING.
   */
  #endregion
  
  using System;
  using System.Collections.Generic;
  using System.Drawing;
  using System.Linq;
  using OpenRA.Activities;
  using OpenRA.Mods.Common.Activities;
  using OpenRA.Primitives;
  using OpenRA.Traits;
  
  namespace OpenRA.Mods.Common.Traits
  {
  	[Flags]
  	public enum CellConditions
  	{
  		None = 0,
  		TransientActors,
  		BlockedByMovers,
  		All = TransientActors | BlockedByMovers
  	}
  
  	public static class CellConditionsExts
  	{
  		public static bool HasCellCondition(this CellConditions c, CellConditions cellCondition)
  		{
  			// PERF: Enum.HasFlag is slower and requires allocations.
  			return (c & cellCondition) == cellCondition;
  		}
  	}
  
  	[Desc("Unit is able to move.")]
  	public class MobileInfo : UpgradableTraitInfo, IMoveInfo, IPositionableInfo, IOccupySpaceInfo, IFacingInfo,
  		UsesInit<FacingInit>, UsesInit<LocationInit>, UsesInit<SubCellInit>
  	{
  		[FieldLoader.LoadUsing("LoadSpeeds", true)]
  		[Desc("Set Water: 0 for ground units and lower the value on rough terrain.")]
  		public readonly Dictionary<string, TerrainInfo> TerrainSpeeds;
  
  		[Desc("e.g. crate, wall, infantry")]
  		public readonly HashSet<string> Crushes = new HashSet<string>();
  
  		public readonly int WaitAverage = 5;
  
  		public readonly int WaitSpread = 2;
  
  		public readonly int InitialFacing = 0;
  
  		[Desc("Rate of Turning")]
  		public readonly int ROT = 255;
  
  		public readonly int Speed = 1;
  
  		public readonly bool OnRails = false;
  
  		[Desc("Allow multiple (infantry) units in one cell.")]
  		public readonly bool SharesCell = false;
  
  		[Desc("Can the actor be ordered to move in to shroud?")]
  		public readonly bool MoveIntoShroud = true;
  
  		public readonly string Cursor = "move";
  		public readonly string BlockedCursor = "move-blocked";
  
  		[VoiceReference] public readonly string Voice = "Action";
  
  		public override object Create(ActorInitializer init) { return new Mobile(init, this); }
  
  		static object LoadSpeeds(MiniYaml y)
  		{
  			var ret = new Dictionary<string, TerrainInfo>();
  			foreach (var t in y.ToDictionary()["TerrainSpeeds"].Nodes)
  			{
  				var speed = FieldLoader.GetValue<int>("speed", t.Value.Value);
  				var nodesDict = t.Value.ToDictionary();
  				var cost = nodesDict.ContainsKey("PathingCost")
  					? FieldLoader.GetValue<int>("cost", nodesDict["PathingCost"].Value)
  					: 10000 / speed;
  				ret.Add(t.Key, new TerrainInfo(speed, cost));
  			}
  
  			return ret;
  		}
  
  		TerrainInfo[] LoadTilesetSpeeds(TileSet tileSet)
  		{
  			var info = new TerrainInfo[tileSet.TerrainInfo.Length];
  			for (var i = 0; i < info.Length; i++)
  				info[i] = TerrainInfo.Impassable;
  
  			foreach (var kvp in TerrainSpeeds)
  			{
  				byte index;
  				if (tileSet.TryGetTerrainIndex(kvp.Key, out index))
  					info[index] = kvp.Value;
  			}
  
  			return info;
  		}
  
  		public class TerrainInfo
  		{
  			public static readonly TerrainInfo Impassable = new TerrainInfo();
  
  			public readonly int Cost;
  			public readonly int Speed;
  
  			public TerrainInfo()
  			{
  				Cost = int.MaxValue;
  				Speed = 0;
  			}
  
  			public TerrainInfo(int speed, int cost)
  			{
  				Speed = speed;
  				Cost = cost;
  			}
  		}
  
  		public struct WorldMovementInfo
  		{
  			internal readonly World World;
  			internal readonly TerrainInfo[] TerrainInfos;
  			internal WorldMovementInfo(World world, MobileInfo info)
  			{
  				// PERF: This struct allows us to cache the terrain info for the tileset used by the world.
  				// This allows us to speed up some performance-sensitive pathfinding calculations.
  				World = world;
  				TerrainInfos = info.TilesetTerrainInfo[world.TileSet];
  			}
  		}
  
  		public readonly Cache<TileSet, TerrainInfo[]> TilesetTerrainInfo;
  		public readonly Cache<TileSet, int> TilesetMovementClass;
  
  		public MobileInfo()
  		{
  			TilesetTerrainInfo = new Cache<TileSet, TerrainInfo[]>(LoadTilesetSpeeds);
  			TilesetMovementClass = new Cache<TileSet, int>(CalculateTilesetMovementClass);
  		}
  
  		public int MovementCostForCell(World world, CPos cell)
  		{
  			return MovementCostForCell(world.Map, TilesetTerrainInfo[world.TileSet], cell);
  		}
  
  		int MovementCostForCell(Map map, TerrainInfo[] terrainInfos, CPos cell)
  		{
  			if (!map.Contains(cell))
  				return int.MaxValue;
  
  			var index = map.GetTerrainIndex(cell);
  			if (index == byte.MaxValue)
  				return int.MaxValue;
  
  			return terrainInfos[index].Cost;
  		}
  
  		public int CalculateTilesetMovementClass(TileSet tileset)
  		{
  			/* collect our ability to cross *all* terraintypes, in a bitvector */
  			return TilesetTerrainInfo[tileset].Select(ti => ti.Cost < int.MaxValue).ToBits();
  		}
  
  		public int GetMovementClass(TileSet tileset)
  		{
  			return TilesetMovementClass[tileset];
  		}
  
  		static bool IsMovingInMyDirection(Actor self, Actor other)
  		{
  			if (!other.IsMoving()) return false;
  
  			var selfMobile = self.TraitOrDefault<Mobile>();
  			if (selfMobile == null) return false;
  
  			var otherMobile = other.TraitOrDefault<Mobile>();
  			if (otherMobile == null) return false;
  
  			// Sign of dot-product indicates (roughly) if vectors are facing in same or opposite directions:
  			var dp = CVec.Dot(selfMobile.ToCell - self.Location, otherMobile.ToCell - other.Location);
  
  			return dp > 0;
  		}
  
  		public int TileSetMovementHash(TileSet tileSet)
  		{
  			var terrainInfos = TilesetTerrainInfo[tileSet];
  
  			// Compute and return the hash using aggregate
  			return terrainInfos.Aggregate(terrainInfos.Length,
  				(current, terrainInfo) => unchecked(current * 31 + terrainInfo.Cost));
  		}
  
  		public bool CanEnterCell(World world, Actor self, CPos cell, Actor ignoreActor = null, CellConditions check = CellConditions.All)
  		{
  			if (MovementCostForCell(world, cell) == int.MaxValue)
  				return false;
  
  			return CanMoveFreelyInto(world, self, cell, ignoreActor, check);
  		}
  
  		// Determines whether the actor is blocked by other Actors
  		public bool CanMoveFreelyInto(World world, Actor self, CPos cell, Actor ignoreActor, CellConditions check)
  		{
  			if (!check.HasCellCondition(CellConditions.TransientActors))
  				return true;
  
  			if (SharesCell && world.ActorMap.HasFreeSubCell(cell))
  				return true;
  
  			// PERF: Avoid LINQ.
  			foreach (var otherActor in world.ActorMap.GetActorsAt(cell))
  				if (IsBlockedBy(self, otherActor, ignoreActor, check))
  					return false;
  
  			return true;
  		}
  
  		bool IsBlockedBy(Actor self, Actor otherActor, Actor ignoreActor, CellConditions check)
  		{
  			// We are not blocked by the actor we are ignoring.
  			if (otherActor == ignoreActor)
  				return false;
  
  			// If self is null, we don't have a real actor - we're just checking what would happen theoretically.
  			// In such a scenario - we'll just assume any other actor in the cell will block us by default.
  			// If we have a real actor, we can then perform the extra checks that allow us to avoid being blocked.
  			if (self == null)
  				return true;
  
  			// If the check allows: we are not blocked by allied units moving in our direction.
  			if (!check.HasCellCondition(CellConditions.BlockedByMovers) &&
  				self.Owner.Stances[otherActor.Owner] == Stance.Ally &&
  				IsMovingInMyDirection(self, otherActor))
  				return false;
  
  			// If there is a temporary blocker in our path, but we can remove it, we are not blocked.
  			var temporaryBlocker = otherActor.TraitOrDefault<ITemporaryBlocker>();
  			if (temporaryBlocker != null && temporaryBlocker.CanRemoveBlockage(otherActor, self))
  				return false;
  
  			// If we cannot crush the other actor in our way, we are blocked.
  			if (Crushes == null || Crushes.Count == 0)
  				return true;
  
  			// If the other actor in our way cannot be crushed, we are blocked.
  			// PERF: Avoid LINQ.
  			var crushables = otherActor.TraitsImplementing<ICrushable>();
  			var lacksCrushability = true;
  			foreach (var crushable in crushables)
  			{
  				lacksCrushability = false;
  				if (!crushable.CrushableBy(otherActor, self, Crushes))
  					return true;
  			}
  
  			// If there are no crushable traits at all, this means the other actor cannot be crushed - we are blocked.
  			if (lacksCrushability)
  				return true;
  
  			// We are not blocked by the other actor.
  			return false;
  		}
  
  		public WorldMovementInfo GetWorldMovementInfo(World world)
  		{
  			return new WorldMovementInfo(world, this);
  		}
  
  		public int MovementCostToEnterCell(WorldMovementInfo worldMovementInfo, Actor self, CPos cell, Actor ignoreActor = null, CellConditions check = CellConditions.All)
  		{
  			var cost = MovementCostForCell(worldMovementInfo.World.Map, worldMovementInfo.TerrainInfos, cell);
  			if (cost == int.MaxValue || !CanMoveFreelyInto(worldMovementInfo.World, self, cell, ignoreActor, check))
  				return int.MaxValue;
  			return cost;
  		}
  
  		public SubCell GetAvailableSubCell(
  			World world, Actor self, CPos cell, SubCell preferredSubCell = SubCell.Any, Actor ignoreActor = null, CellConditions check = CellConditions.All)
  		{
  			if (MovementCostForCell(world, cell) == int.MaxValue)
  				return SubCell.Invalid;
  
  			if (check.HasCellCondition(CellConditions.TransientActors))
  			{
  				Func<Actor, bool> checkTransient = otherActor => IsBlockedBy(self, otherActor, ignoreActor, check);
  
  				if (!SharesCell)
  					return world.ActorMap.AnyActorsAt(cell, SubCell.FullCell, checkTransient) ? SubCell.Invalid : SubCell.FullCell;
  
  				return world.ActorMap.FreeSubCell(cell, preferredSubCell, checkTransient);
  			}
  
  			if (!SharesCell)
  				return world.ActorMap.AnyActorsAt(cell, SubCell.FullCell) ? SubCell.Invalid : SubCell.FullCell;
  
  			return world.ActorMap.FreeSubCell(cell, preferredSubCell);
  		}
  
  		public int GetInitialFacing() { return InitialFacing; }
  
  		public IReadOnlyDictionary<CPos, SubCell> OccupiedCells(ActorInfo info, CPos location, SubCell subCell = SubCell.Any)
  		{
  			return new ReadOnlyDictionary<CPos, SubCell>(new Dictionary<CPos, SubCell>() { { location, subCell } });
  		}
  
  		bool IOccupySpaceInfo.SharesCell { get { return SharesCell; } }
  	}
  
  	public class Mobile : UpgradableTrait<MobileInfo>, IIssueOrder, IResolveOrder, IOrderVoice, IPositionable, IMove, IFacing, ISync,
  		IDeathActorInitModifier, INotifyAddedToWorld, INotifyRemovedFromWorld, INotifyBlockingMove
  	{
  		const int AverageTicksBeforePathing = 5;
  		const int SpreadTicksBeforePathing = 5;
  		internal int TicksBeforePathing = 0;
  
  		readonly Actor self;
  		readonly Lazy<IEnumerable<int>> speedModifiers;
  		public bool IsMoving { get; set; }
  
  		int facing;
  		CPos fromCell, toCell;
  		public SubCell FromSubCell, ToSubCell;
  
  		[Sync] public int Facing
  		{
  			get { return facing; }
  			set { facing = value; }
  		}
  
  		public int ROT { get { return Info.ROT; } }
  
  		[Sync] public WPos CenterPosition { get; private set; }
  		[Sync] public CPos FromCell { get { return fromCell; } }
  		[Sync] public CPos ToCell { get { return toCell; } }
  
  		[Sync] public int PathHash;	// written by Move.EvalPath, to temporarily debug this crap.
  
  		// Sets only the location (fromCell, toCell, FromSubCell, ToSubCell)
  		public void SetLocation(CPos from, SubCell fromSub, CPos to, SubCell toSub)
  		{
  			if (FromCell == from && ToCell == to && FromSubCell == fromSub && ToSubCell == toSub)
  				return;
  
  			RemoveInfluence();
  			fromCell = from;
  			toCell = to;
  			FromSubCell = fromSub;
  			ToSubCell = toSub;
  			AddInfluence();
  		}
  
  		public Mobile(ActorInitializer init, MobileInfo info)
  			: base(info)
  		{
  			self = init.Self;
  
  			speedModifiers = Exts.Lazy(() => self.TraitsImplementing<ISpeedModifier>().ToArray().Select(x => x.GetSpeedModifier()));
  
  			ToSubCell = FromSubCell = info.SharesCell ? init.World.Map.DefaultSubCell : SubCell.FullCell;
  			if (init.Contains<SubCellInit>())
  
gt: 				FromSubCell = ToSubCell = init.Get<SubCellInit, SubCell>();