Merge pull request #3741 from Mailaender/sync-effects

Added [Sync] checks for projectile effects
This commit is contained in:
Paul Chote
2013-08-29 13:25:59 -07:00
14 changed files with 271 additions and 180 deletions

View File

@@ -26,7 +26,7 @@ namespace OpenRA
public readonly uint ActorID; public readonly uint ActorID;
Lazy<IOccupySpace> occupySpace; Lazy<IOccupySpace> occupySpace;
Lazy<IFacing> Facing; Lazy<IFacing> facing;
public Cached<Rectangle> Bounds; public Cached<Rectangle> Bounds;
public Cached<Rectangle> ExtendedBounds; public Cached<Rectangle> ExtendedBounds;
@@ -42,8 +42,8 @@ namespace OpenRA
get get
{ {
// TODO: Support non-zero pitch/roll in IFacing (IOrientation?) // TODO: Support non-zero pitch/roll in IFacing (IOrientation?)
var facing = Facing.Value != null ? Facing.Value.Facing : 0; var facingValue = facing.Value != null ? facing.Value.Facing : 0;
return new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(facing)); return new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(facingValue));
} }
} }
@@ -60,7 +60,7 @@ namespace OpenRA
World = world; World = world;
ActorID = world.NextAID(); ActorID = world.NextAID();
if (initDict.Contains<OwnerInit>()) if (initDict.Contains<OwnerInit>())
Owner = init.Get<OwnerInit,Player>(); Owner = init.Get<OwnerInit, Player>();
occupySpace = Lazy.New(() => TraitOrDefault<IOccupySpace>()); occupySpace = Lazy.New(() => TraitOrDefault<IOccupySpace>());
@@ -74,9 +74,9 @@ namespace OpenRA
AddTrait(trait.Create(init)); AddTrait(trait.Create(init));
} }
Facing = Lazy.New(() => TraitOrDefault<IFacing>()); facing = Lazy.New(() => TraitOrDefault<IFacing>());
Size = Lazy.New(() => size = Lazy.New(() =>
{ {
var si = Info.Traits.GetOrDefault<SelectableInfo>(); var si = Info.Traits.GetOrDefault<SelectableInfo>();
if (si != null && si.Bounds != null) if (si != null && si.Bounds != null)
@@ -85,8 +85,8 @@ namespace OpenRA
return TraitsImplementing<IAutoSelectionSize>().Select(x => x.SelectionSize(this)).FirstOrDefault(); return TraitsImplementing<IAutoSelectionSize>().Select(x => x.SelectionSize(this)).FirstOrDefault();
}); });
ApplyIRender = (x, wr) => x.Render(this, wr); applyIRender = (x, wr) => x.Render(this, wr);
ApplyRenderModifier = (m, p, wr) => p.ModifyRender(this, wr, m); applyRenderModifier = (m, p, wr) => p.ModifyRender(this, wr, m);
Bounds = Cached.New(() => CalculateBounds(false)); Bounds = Cached.New(() => CalculateBounds(false));
ExtendedBounds = Cached.New(() => CalculateBounds(true)); ExtendedBounds = Cached.New(() => CalculateBounds(true));
@@ -105,16 +105,16 @@ namespace OpenRA
get { return currentActivity == null; } get { return currentActivity == null; }
} }
OpenRA.FileFormats.Lazy<int2> Size; OpenRA.FileFormats.Lazy<int2> size;
// note: these delegates are cached to avoid massive allocation. // note: these delegates are cached to avoid massive allocation.
Func<IRender, WorldRenderer, IEnumerable<IRenderable>> ApplyIRender; Func<IRender, WorldRenderer, IEnumerable<IRenderable>> applyIRender;
Func<IEnumerable<IRenderable>, IRenderModifier, WorldRenderer, IEnumerable<IRenderable>> ApplyRenderModifier; Func<IEnumerable<IRenderable>, IRenderModifier, WorldRenderer, IEnumerable<IRenderable>> applyRenderModifier;
public IEnumerable<IRenderable> Render(WorldRenderer wr) public IEnumerable<IRenderable> Render(WorldRenderer wr)
{ {
var mods = TraitsImplementing<IRenderModifier>(); var mods = TraitsImplementing<IRenderModifier>();
var sprites = TraitsImplementing<IRender>().SelectMany(x => ApplyIRender(x, wr)); var sprites = TraitsImplementing<IRender>().SelectMany(x => applyIRender(x, wr));
return mods.Aggregate(sprites, (m,p) => ApplyRenderModifier(m,p,wr)); return mods.Aggregate(sprites, (m, p) => applyRenderModifier(m, p, wr));
} }
// When useAltitude = true, the bounding box is extended // When useAltitude = true, the bounding box is extended
@@ -123,8 +123,8 @@ namespace OpenRA
// at its current altitude // at its current altitude
Rectangle CalculateBounds(bool useAltitude) Rectangle CalculateBounds(bool useAltitude)
{ {
var size = (PVecInt)(Size.Value); var sizeVector = (PVecInt)size.Value;
var loc = CenterLocation - size / 2; var loc = CenterLocation - sizeVector / 2;
var si = Info.Traits.GetOrDefault<SelectableInfo>(); var si = Info.Traits.GetOrDefault<SelectableInfo>();
if (si != null && si.Bounds != null && si.Bounds.Length > 2) if (si != null && si.Bounds != null && si.Bounds.Length > 2)
@@ -139,33 +139,33 @@ namespace OpenRA
loc -= new PVecInt(0, altitude); loc -= new PVecInt(0, altitude);
if (useAltitude) if (useAltitude)
size = new PVecInt(size.X, size.Y + altitude); sizeVector = new PVecInt(sizeVector.X, sizeVector.Y + altitude);
} }
return new Rectangle(loc.X, loc.Y, size.X, size.Y); return new Rectangle(loc.X, loc.Y, sizeVector.X, sizeVector.Y);
} }
public bool IsInWorld { get; internal set; } public bool IsInWorld { get; internal set; }
public void QueueActivity( bool queued, Activity nextActivity ) public void QueueActivity(bool queued, Activity nextActivity)
{ {
if( !queued ) if (!queued)
CancelActivity(); CancelActivity();
QueueActivity( nextActivity ); QueueActivity(nextActivity);
} }
public void QueueActivity( Activity nextActivity ) public void QueueActivity(Activity nextActivity)
{ {
if( currentActivity == null ) if (currentActivity == null)
currentActivity = nextActivity; currentActivity = nextActivity;
else else
currentActivity.Queue( nextActivity ); currentActivity.Queue(nextActivity);
} }
public void CancelActivity() public void CancelActivity()
{ {
if( currentActivity != null ) if (currentActivity != null)
currentActivity.Cancel( this ); currentActivity.Cancel(this);
} }
public Activity GetCurrentActivity() public Activity GetCurrentActivity()
@@ -178,54 +178,54 @@ namespace OpenRA
return (int)ActorID; return (int)ActorID;
} }
public override bool Equals( object obj ) public override bool Equals(object obj)
{ {
var o = obj as Actor; var o = obj as Actor;
return ( o != null && o.ActorID == ActorID ); return o != null && o.ActorID == ActorID;
} }
public override string ToString() public override string ToString()
{ {
return "{0} {1}{2}".F( Info.Name, ActorID, IsInWorld ? "" : " (not in world)" ); return "{0} {1}{2}".F(Info.Name, ActorID, IsInWorld ? "" : " (not in world)");
} }
public T Trait<T>() public T Trait<T>()
{ {
return World.traitDict.Get<T>( this ); return World.traitDict.Get<T>(this);
} }
public T TraitOrDefault<T>() public T TraitOrDefault<T>()
{ {
return World.traitDict.GetOrDefault<T>( this ); return World.traitDict.GetOrDefault<T>(this);
} }
public IEnumerable<T> TraitsImplementing<T>() public IEnumerable<T> TraitsImplementing<T>()
{ {
return World.traitDict.WithInterface<T>( this ); return World.traitDict.WithInterface<T>(this);
} }
public bool HasTrait<T>() public bool HasTrait<T>()
{ {
return World.traitDict.Contains<T>( this ); return World.traitDict.Contains<T>(this);
} }
public void AddTrait( object trait ) public void AddTrait(object trait)
{ {
World.traitDict.AddTrait( this, trait ); World.traitDict.AddTrait(this, trait);
} }
public bool Destroyed { get; private set; } public bool Destroyed { get; private set; }
public void Destroy() public void Destroy()
{ {
World.AddFrameEndTask( w => World.AddFrameEndTask(w =>
{ {
if (Destroyed) return; if (Destroyed) return;
World.Remove( this ); World.Remove(this);
World.traitDict.RemoveActor( this ); World.traitDict.RemoveActor(this);
Destroyed = true; Destroyed = true;
} ); });
} }
// TODO: move elsewhere. // TODO: move elsewhere.

View File

@@ -9,10 +9,10 @@
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using OpenRA.Effects; using OpenRA.Effects;
using OpenRA.FileFormats; using OpenRA.FileFormats;
using OpenRA.Traits; using OpenRA.Traits;
using System.Linq;
namespace OpenRA.GameRules namespace OpenRA.GameRules
{ {
@@ -20,7 +20,7 @@ namespace OpenRA.GameRules
{ {
[Desc("Distance (in pixels) from the explosion center at which damage is 1/2.")] [Desc("Distance (in pixels) from the explosion center at which damage is 1/2.")]
public readonly int Spread = 1; public readonly int Spread = 1;
[FieldLoader.LoadUsing( "LoadVersus" )] [FieldLoader.LoadUsing("LoadVersus")]
[Desc("Damage vs each armortype. 0% = can't target.")] [Desc("Damage vs each armortype. 0% = can't target.")]
public readonly Dictionary<string, float> Versus; public readonly Dictionary<string, float> Versus;
[Desc("Can this damage ore?")] [Desc("Can this damage ore?")]
@@ -62,17 +62,17 @@ namespace OpenRA.GameRules
return Versus.TryGetValue(armor.Type, out versus) ? versus : 1; return Versus.TryGetValue(armor.Type, out versus) ? versus : 1;
} }
public WarheadInfo( MiniYaml yaml ) public WarheadInfo(MiniYaml yaml)
{ {
FieldLoader.Load( this, yaml ); FieldLoader.Load(this, yaml);
} }
static object LoadVersus( MiniYaml y ) static object LoadVersus(MiniYaml y)
{ {
return y.NodesDict.ContainsKey( "Versus" ) return y.NodesDict.ContainsKey("Versus")
? y.NodesDict[ "Versus" ].NodesDict.ToDictionary( ? y.NodesDict["Versus"].NodesDict.ToDictionary(
a => a.Key, a => a.Key,
a => FieldLoader.GetValue<float>( "(value)", a.Value.Value ) ) a => FieldLoader.GetValue<float>("(value)", a.Value.Value))
: new Dictionary<string, float>(); : new Dictionary<string, float>();
} }
} }
@@ -85,13 +85,13 @@ namespace OpenRA.GameRules
public class ProjectileArgs public class ProjectileArgs
{ {
public WeaponInfo weapon; public WeaponInfo Weapon;
public float firepowerModifier = 1.0f; public float FirepowerModifier = 1.0f;
public int facing; public int Facing;
public WPos source; public WPos Source;
public Actor sourceActor; public Actor SourceActor;
public WPos passiveTarget; public WPos PassiveTarget;
public Target guidedTarget; public Target GuidedTarget;
} }
public interface IProjectileInfo { IEffect Create(ProjectileArgs args); } public interface IProjectileInfo { IEffect Create(ProjectileArgs args); }
@@ -109,30 +109,30 @@ namespace OpenRA.GameRules
public readonly int BurstDelay = 5; public readonly int BurstDelay = 5;
public readonly float MinRange = 0; public readonly float MinRange = 0;
[FieldLoader.LoadUsing( "LoadProjectile" )] public IProjectileInfo Projectile; [FieldLoader.LoadUsing("LoadProjectile")] public IProjectileInfo Projectile;
[FieldLoader.LoadUsing( "LoadWarheads" )] public List<WarheadInfo> Warheads; [FieldLoader.LoadUsing("LoadWarheads")] public List<WarheadInfo> Warheads;
public WeaponInfo(string name, MiniYaml content) public WeaponInfo(string name, MiniYaml content)
{ {
FieldLoader.Load( this, content ); FieldLoader.Load(this, content);
} }
static object LoadProjectile( MiniYaml yaml ) static object LoadProjectile(MiniYaml yaml)
{ {
MiniYaml proj; MiniYaml proj;
if( !yaml.NodesDict.TryGetValue( "Projectile", out proj ) ) if (!yaml.NodesDict.TryGetValue("Projectile", out proj))
return null; return null;
var ret = Game.CreateObject<IProjectileInfo>( proj.Value + "Info" ); var ret = Game.CreateObject<IProjectileInfo>(proj.Value + "Info");
FieldLoader.Load( ret, proj ); FieldLoader.Load(ret, proj);
return ret; return ret;
} }
static object LoadWarheads( MiniYaml yaml ) static object LoadWarheads(MiniYaml yaml)
{ {
var ret = new List<WarheadInfo>(); var ret = new List<WarheadInfo>();
foreach( var w in yaml.Nodes ) foreach (var w in yaml.Nodes)
if( w.Key.Split( '@' )[ 0 ] == "Warhead" ) if (w.Key.Split('@')[0] == "Warhead")
ret.Add( new WarheadInfo( w.Value ) ); ret.Add(new WarheadInfo(w.Value));
return ret; return ret;
} }
@@ -161,7 +161,6 @@ namespace OpenRA.GameRules
return true; return true;
} }
public bool IsValidAgainst(Target target, World world) public bool IsValidAgainst(Target target, World world)
{ {
if (target.Type == TargetType.Actor) if (target.Type == TargetType.Actor)

View File

@@ -8,40 +8,42 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using System;
using OpenRA.FileFormats; using OpenRA.FileFormats;
namespace OpenRA.Network namespace OpenRA.Network
{ {
class SyncReport class SyncReport
{ {
static Cache<Type, Func<object, Dictionary<string, string>>> dumpFuncCache = new Cache<Type, Func<object, Dictionary<string, string>>>( t => GenerateDumpFunc( t ) ); const int NumSyncReports = 5;
static Cache<Type, Func<object, Dictionary<string, string>>> dumpFuncCache = new Cache<Type, Func<object, Dictionary<string, string>>>(t => GenerateDumpFunc(t));
readonly OrderManager orderManager; readonly OrderManager orderManager;
const int numSyncReports = 5;
Report[] syncReports = new Report[numSyncReports]; Report[] syncReports = new Report[NumSyncReports];
int curIndex = 0; int curIndex = 0;
public SyncReport( OrderManager orderManager ) public SyncReport(OrderManager orderManager)
{ {
this.orderManager = orderManager; this.orderManager = orderManager;
for (var i = 0; i < numSyncReports; i++) for (var i = 0; i < NumSyncReports; i++)
syncReports[i] = new SyncReport.Report(); syncReports[i] = new SyncReport.Report();
} }
internal void UpdateSyncReport() internal void UpdateSyncReport()
{ {
GenerateSyncReport(syncReports[curIndex]); GenerateSyncReport(syncReports[curIndex]);
curIndex = ++curIndex % numSyncReports; curIndex = ++curIndex % NumSyncReports;
} }
public static Dictionary<string, string> DumpSyncTrait( object obj ) public static Dictionary<string, string> DumpSyncTrait(object obj)
{ {
return dumpFuncCache[ obj.GetType() ]( obj ); return dumpFuncCache[obj.GetType()](obj);
} }
public static Func<object, Dictionary<string, string>> GenerateDumpFunc(Type t) public static Func<object, Dictionary<string, string>> GenerateDumpFunc(Type t)
@@ -66,8 +68,8 @@ namespace OpenRA.Network
il.Emit(OpCodes.Newobj, dictCtor_); il.Emit(OpCodes.Newobj, dictCtor_);
il.Emit(OpCodes.Stloc, dict_); il.Emit(OpCodes.Stloc, dict_);
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var field in t.GetFields(bf).Where(x => x.HasAttribute<SyncAttribute>())) foreach (var field in t.GetFields(Flags).Where(x => x.HasAttribute<SyncAttribute>()))
{ {
if (field.IsLiteral || field.IsStatic) continue; if (field.IsLiteral || field.IsStatic) continue;
@@ -94,7 +96,7 @@ namespace OpenRA.Network
il.MarkLabel(lblNull); il.MarkLabel(lblNull);
} }
foreach (var prop in t.GetProperties(bf).Where(x => x.HasAttribute<SyncAttribute>())) foreach (var prop in t.GetProperties(Flags).Where(x => x.HasAttribute<SyncAttribute>()))
{ {
var lblNull = il.DefineLabel(); var lblNull = il.DefineLabel();
@@ -121,7 +123,7 @@ namespace OpenRA.Network
il.Emit(OpCodes.Ldloc, dict_); il.Emit(OpCodes.Ldloc, dict_);
il.Emit(OpCodes.Ret); il.Emit(OpCodes.Ret);
return (Func<object, Dictionary<string, string>>) d.CreateDelegate(typeof(Func<object, Dictionary<string, string>>)); return (Func<object, Dictionary<string, string>>)d.CreateDelegate(typeof(Func<object, Dictionary<string, string>>));
} }
void GenerateSyncReport(Report report) void GenerateSyncReport(Report report)
@@ -136,23 +138,44 @@ namespace OpenRA.Network
if (sync != 0) if (sync != 0)
{ {
var tr = new TraitReport() var tr = new TraitReport()
{ {
ActorID = a.Actor.ActorID, ActorID = a.Actor.ActorID,
Type = a.Actor.Info.Name, Type = a.Actor.Info.Name,
Owner = (a.Actor.Owner == null) ? "null" : a.Actor.Owner.PlayerName, Owner = (a.Actor.Owner == null) ? "null" : a.Actor.Owner.PlayerName,
Trait = a.Trait.GetType().Name, Trait = a.Trait.GetType().Name,
Hash = sync Hash = sync
}; };
tr.Fields = DumpSyncTrait(a.Trait); tr.Fields = DumpSyncTrait(a.Trait);
report.Traits.Add(tr); report.Traits.Add(tr);
} }
} }
foreach (var e in orderManager.world.Effects)
{
var sync = e as ISync;
if (sync != null)
{
var hash = Sync.CalculateSyncHash(sync);
if (hash != 0)
{
var er = new EffectReport()
{
Name = sync.ToString().Split('.').Last(),
Hash = hash
};
er.Fields = DumpSyncTrait(sync);
report.Effects.Add(er);
}
}
}
} }
internal void DumpSyncReport(int frame) internal void DumpSyncReport(int frame)
{ {
foreach (var r in syncReports) foreach (var r in syncReports)
{
if (r.Frame == frame) if (r.Frame == frame)
{ {
Log.Write("sync", "Sync for net frame {0} -------------", r.Frame); Log.Write("sync", "Sync for net frame {0} -------------", r.Frame);
@@ -160,21 +183,24 @@ namespace OpenRA.Network
Log.Write("sync", "Synced Traits:"); Log.Write("sync", "Synced Traits:");
foreach (var a in r.Traits) foreach (var a in r.Traits)
{ {
Log.Write("sync", "\t {0} {1} {2} {3} ({4})".F( Log.Write("sync", "\t {0} {1} {2} {3} ({4})".F(a.ActorID, a.Type, a.Owner, a.Trait, a.Hash));
a.ActorID,
a.Type,
a.Owner,
a.Trait,
a.Hash
));
foreach (var f in a.Fields) foreach (var f in a.Fields)
Log.Write("sync", "\t\t {0}: {1}".F(f.Key, f.Value)); Log.Write("sync", "\t\t {0}: {1}".F(f.Key, f.Value));
}
Log.Write("sync", "Synced Effects:");
foreach (var e in r.Effects)
{
Log.Write("sync", "\t {0} ({1})", e.Name, e.Hash);
foreach (var f in e.Fields)
Log.Write("sync", "\t\t {0}: {1}".F(f.Key, f.Value));
} }
return; return;
} }
Log.Write("sync", "No sync report available!");
Log.Write("sync", "No sync report available!");
}
} }
class Report class Report
@@ -183,6 +209,7 @@ namespace OpenRA.Network
public int SyncedRandom; public int SyncedRandom;
public int TotalCount; public int TotalCount;
public List<TraitReport> Traits = new List<TraitReport>(); public List<TraitReport> Traits = new List<TraitReport>();
public List<EffectReport> Effects = new List<EffectReport>();
} }
struct TraitReport struct TraitReport
@@ -195,5 +222,11 @@ namespace OpenRA.Network
public Dictionary<string, string> Fields; public Dictionary<string, string> Fields;
} }
struct EffectReport
{
public string Name;
public int Hash;
public Dictionary<string, string> Fields;
}
} }
} }

View File

@@ -14,6 +14,7 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using OpenRA.FileFormats; using OpenRA.FileFormats;
using OpenRA.Traits;
namespace OpenRA namespace OpenRA
{ {
@@ -45,6 +46,7 @@ namespace OpenRA
{typeof(TypeDictionary), ((Func<TypeDictionary, int>)hash_tdict).Method}, {typeof(TypeDictionary), ((Func<TypeDictionary, int>)hash_tdict).Method},
{typeof(Actor), ((Func<Actor, int>)hash_actor).Method}, {typeof(Actor), ((Func<Actor, int>)hash_actor).Method},
{typeof(Player), ((Func<Player, int>)hash_player).Method}, {typeof(Player), ((Func<Player, int>)hash_player).Method},
{typeof(Target), ((Func<Target, int>)hash_target).Method},
}; };
static void EmitSyncOpcodes(Type type, ILGenerator il) static void EmitSyncOpcodes(Type type, ILGenerator il)
@@ -146,6 +148,25 @@ namespace OpenRA
return 0; return 0;
} }
public static int hash_target(Target t)
{
switch (t.Type)
{
case TargetType.Actor:
return (int)(t.Actor.ActorID << 16) * 0x567;
case TargetType.FrozenActor:
return (int)(t.FrozenActor.Actor.ActorID << 16) * 0x567;
case TargetType.Terrain:
return hash<WPos>(t.CenterPosition);
default:
case TargetType.Invalid:
return 0;
}
}
public static int hash<T>(T t) public static int hash<T>(T t)
{ {
return t.GetHashCode(); return t.GetHashCode();

View File

@@ -86,6 +86,11 @@ namespace OpenRA.Traits
} }
public bool HasRenderables { get { return Renderables != null; } } public bool HasRenderables { get { return Renderables != null; } }
public override string ToString()
{
return "{0} {1}{2}".F(Info.Name, ID, IsValid ? "" : " (invalid)");
}
} }
public class FrozenActorLayer : IRender, ITick, ISync public class FrozenActorLayer : IRender, ITick, ISync

View File

@@ -141,5 +141,24 @@ namespace OpenRA.Traits
return Positions.Any(t => (t - origin).HorizontalLengthSquared <= rangeSquared); return Positions.Any(t => (t - origin).HorizontalLengthSquared <= rangeSquared);
} }
public override string ToString()
{
switch (Type)
{
case TargetType.Actor:
return actor.ToString();
case TargetType.FrozenActor:
return frozen.ToString();
case TargetType.Terrain:
return pos.ToString();
default:
case TargetType.Invalid:
return "Invalid";
}
}
} }
} }

View File

@@ -246,6 +246,14 @@ namespace OpenRA
foreach (var x in traitDict.ActorsWithTraitMultiple<ISync>(this)) foreach (var x in traitDict.ActorsWithTraitMultiple<ISync>(this))
ret += n++ * (int)(1+x.Actor.ActorID) * Sync.CalculateSyncHash(x.Trait); ret += n++ * (int)(1+x.Actor.ActorID) * Sync.CalculateSyncHash(x.Trait);
// TODO: don't go over all effects
foreach (var e in Effects)
{
var sync = e as ISync;
if (sync != null)
ret += n++ * Sync.CalculateSyncHash(sync);
}
// Hash the shared rng // Hash the shared rng
ret += SharedRandom.Last; ret += SharedRandom.Last;

22
OpenRA.Mods.RA/Armament.cs Executable file → Normal file
View File

@@ -125,28 +125,28 @@ namespace OpenRA.Mods.RA
var args = new ProjectileArgs var args = new ProjectileArgs
{ {
weapon = Weapon, Weapon = Weapon,
facing = legacyFacing, Facing = legacyFacing,
firepowerModifier = self.TraitsImplementing<IFirepowerModifier>() FirepowerModifier = self.TraitsImplementing<IFirepowerModifier>()
.Select(a => a.GetFirepowerModifier()) .Select(a => a.GetFirepowerModifier())
.Product(), .Product(),
source = muzzlePosition, Source = muzzlePosition,
sourceActor = self, SourceActor = self,
passiveTarget = target.CenterPosition, PassiveTarget = target.CenterPosition,
guidedTarget = target GuidedTarget = target
}; };
attack.ScheduleDelayedAction(Info.FireDelay, () => attack.ScheduleDelayedAction(Info.FireDelay, () =>
{ {
if (args.weapon.Projectile != null) if (args.Weapon.Projectile != null)
{ {
var projectile = args.weapon.Projectile.Create(args); var projectile = args.Weapon.Projectile.Create(args);
if (projectile != null) if (projectile != null)
self.World.Add(projectile); self.World.Add(projectile);
if (args.weapon.Report != null && args.weapon.Report.Any()) if (args.Weapon.Report != null && args.Weapon.Report.Any())
Sound.Play(args.weapon.Report.Random(self.World.SharedRandom), self.CenterPosition); Sound.Play(args.Weapon.Report.Random(self.World.SharedRandom), self.CenterPosition);
} }
}); });

View File

@@ -59,18 +59,18 @@ namespace OpenRA.Mods.RA
var pos = self.CenterPosition; var pos = self.CenterPosition;
var args = new ProjectileArgs var args = new ProjectileArgs
{ {
weapon = weapon, Weapon = weapon,
facing = self.Trait<IFacing>().Facing, Facing = self.Trait<IFacing>().Facing,
source = pos, Source = pos,
sourceActor = self, SourceActor = self,
passiveTarget = pos - new WVec(0, 0, pos.Z) PassiveTarget = pos - new WVec(0, 0, pos.Z)
}; };
self.World.Add(args.weapon.Projectile.Create(args)); self.World.Add(args.Weapon.Projectile.Create(args));
if (args.weapon.Report != null && args.weapon.Report.Any()) if (args.Weapon.Report != null && args.Weapon.Report.Any())
Sound.Play(args.weapon.Report.Random(self.World.SharedRandom), self.CenterPosition); Sound.Play(args.Weapon.Report.Random(self.World.SharedRandom), self.CenterPosition);
} }
} }
} }

View File

@@ -41,41 +41,44 @@ namespace OpenRA.Mods.RA.Effects
public IEffect Create(ProjectileArgs args) { return new Bullet(this, args); } public IEffect Create(ProjectileArgs args) { return new Bullet(this, args); }
} }
public class Bullet : IEffect public class Bullet : IEffect, ISync
{ {
readonly BulletInfo info; readonly BulletInfo info;
readonly ProjectileArgs args; readonly ProjectileArgs args;
ContrailRenderable trail; ContrailRenderable trail;
Animation anim; Animation anim;
WAngle angle;
WPos pos, target; [Sync] WAngle angle;
int length; [Sync] WPos pos, target;
int facing; [Sync] int length;
int ticks, smokeTicks; [Sync] int facing;
[Sync] int ticks, smokeTicks;
[Sync] public Actor SourceActor { get { return args.SourceActor; } }
public Bullet(BulletInfo info, ProjectileArgs args) public Bullet(BulletInfo info, ProjectileArgs args)
{ {
this.info = info; this.info = info;
this.args = args; this.args = args;
this.pos = args.source; this.pos = args.Source;
// Convert ProjectileArg definitions to world coordinates // Convert ProjectileArg definitions to world coordinates
// TODO: Change the yaml definitions so we don't need this // TODO: Change the yaml definitions so we don't need this
var range = new WRange((int)(1024 * args.weapon.Range)); // Range in world units var range = new WRange((int)(1024 * args.Weapon.Range)); // Range in world units
var inaccuracy = new WRange((int)(info.Inaccuracy * 1024 / Game.CellSize)); // Offset in world units at max range var inaccuracy = new WRange((int)(info.Inaccuracy * 1024 / Game.CellSize)); // Offset in world units at max range
var speed = (int)(info.Speed * 4 * 1024 / (10 * Game.CellSize)); // Speed in world units per tick var speed = (int)(info.Speed * 4 * 1024 / (10 * Game.CellSize)); // Speed in world units per tick
angle = WAngle.ArcTan((int)(info.Angle * 4 * 1024), 1024); // Angle in world angle angle = WAngle.ArcTan((int)(info.Angle * 4 * 1024), 1024); // Angle in world angle
target = args.passiveTarget; target = args.PassiveTarget;
if (info.Inaccuracy > 0) if (info.Inaccuracy > 0)
{ {
var maxOffset = inaccuracy.Range * (target - args.source).Length / range.Range; var maxOffset = inaccuracy.Range * (target - pos).Length / range.Range;
target += WVec.FromPDF(args.sourceActor.World.SharedRandom, 2) * maxOffset / 1024; target += WVec.FromPDF(args.SourceActor.World.SharedRandom, 2) * maxOffset / 1024;
} }
facing = Traits.Util.GetFacing(target - args.source, 0); facing = Traits.Util.GetFacing(target - pos, 0);
length = Math.Max((target - args.source).Length / speed, 1); length = Math.Max((target - pos).Length / speed, 1);
if (info.Image != null) if (info.Image != null)
{ {
@@ -85,8 +88,8 @@ namespace OpenRA.Mods.RA.Effects
if (info.ContrailLength > 0) if (info.ContrailLength > 0)
{ {
var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.sourceActor) : info.ContrailColor; var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.SourceActor) : info.ContrailColor;
trail = new ContrailRenderable(args.sourceActor.World, color, info.ContrailLength, info.ContrailDelay, 0); trail = new ContrailRenderable(args.SourceActor.World, color, info.ContrailLength, info.ContrailDelay, 0);
} }
smokeTicks = info.TrailDelay; smokeTicks = info.TrailDelay;
@@ -117,11 +120,11 @@ namespace OpenRA.Mods.RA.Effects
if (anim != null) if (anim != null)
anim.Tick(); anim.Tick();
pos = WPos.LerpQuadratic(args.source, target, angle, ticks, length); pos = WPos.LerpQuadratic(args.Source, target, angle, ticks, length);
if (info.Trail != null && --smokeTicks < 0) if (info.Trail != null && --smokeTicks < 0)
{ {
var delayedPos = WPos.LerpQuadratic(args.source, target, angle, ticks - info.TrailDelay, length); var delayedPos = WPos.LerpQuadratic(args.Source, target, angle, ticks - info.TrailDelay, length);
world.AddFrameEndTask(w => w.Add(new Smoke(w, delayedPos, info.Trail))); world.AddFrameEndTask(w => w.Add(new Smoke(w, delayedPos, info.Trail)));
smokeTicks = info.TrailInterval; smokeTicks = info.TrailInterval;
} }
@@ -130,7 +133,7 @@ namespace OpenRA.Mods.RA.Effects
trail.Update(pos); trail.Update(pos);
if (ticks++ >= length || (!info.High && world.ActorMap if (ticks++ >= length || (!info.High && world.ActorMap
.GetUnitsAt(pos.ToCPos()).Any(a => a.HasTrait<IBlocksBullets>()))) .GetUnitsAt(pos.ToCPos()).Any(a => a.HasTrait<IBlocksBullets>())))
{ {
Explode(world); Explode(world);
} }
@@ -145,7 +148,7 @@ namespace OpenRA.Mods.RA.Effects
yield break; yield break;
var cell = pos.ToCPos(); var cell = pos.ToCPos();
if (!args.sourceActor.World.FogObscures(cell)) if (!args.SourceActor.World.FogObscures(cell))
{ {
if (info.Shadow) if (info.Shadow)
{ {
@@ -154,7 +157,7 @@ namespace OpenRA.Mods.RA.Effects
yield return r; yield return r;
} }
var palette = wr.Palette(args.weapon.Underwater ? "shadow" : "effect"); var palette = wr.Palette(args.Weapon.Underwater ? "shadow" : "effect");
foreach (var r in anim.Render(pos, palette)) foreach (var r in anim.Render(pos, palette))
yield return r; yield return r;
} }
@@ -167,7 +170,7 @@ namespace OpenRA.Mods.RA.Effects
else else
world.AddFrameEndTask(w => w.Remove(this)); world.AddFrameEndTask(w => w.Remove(this));
Combat.DoImpacts(target, args.sourceActor, args.weapon, args.firepowerModifier); Combat.DoImpacts(target, args.SourceActor, args.Weapon, args.FirepowerModifier);
} }
} }
} }

6
OpenRA.Mods.RA/Effects/GravityBomb.cs Executable file → Normal file
View File

@@ -37,7 +37,7 @@ namespace OpenRA.Mods.RA.Effects
{ {
this.info = info; this.info = info;
this.args = args; this.args = args;
pos = args.source; pos = args.Source;
velocity = new WVec(WRange.Zero, WRange.Zero, -info.Velocity); velocity = new WVec(WRange.Zero, WRange.Zero, -info.Velocity);
anim = new Animation(info.Image); anim = new Animation(info.Image);
@@ -52,10 +52,10 @@ namespace OpenRA.Mods.RA.Effects
velocity -= new WVec(WRange.Zero, WRange.Zero, info.Acceleration); velocity -= new WVec(WRange.Zero, WRange.Zero, info.Acceleration);
pos += velocity; pos += velocity;
if (pos.Z <= args.passiveTarget.Z) if (pos.Z <= args.PassiveTarget.Z)
{ {
world.AddFrameEndTask(w => w.Remove(this)); world.AddFrameEndTask(w => w.Remove(this));
Combat.DoImpacts(args.passiveTarget, args.sourceActor, args.weapon, args.firepowerModifier); Combat.DoImpacts(args.PassiveTarget, args.SourceActor, args.Weapon, args.FirepowerModifier);
} }
anim.Tick(); anim.Tick();

12
OpenRA.Mods.RA/Effects/LaserZap.cs Executable file → Normal file
View File

@@ -29,7 +29,7 @@ namespace OpenRA.Mods.RA.Effects
public IEffect Create(ProjectileArgs args) public IEffect Create(ProjectileArgs args)
{ {
var c = UsePlayerColor ? args.sourceActor.Owner.Color.RGB : Color; var c = UsePlayerColor ? args.SourceActor.Owner.Color.RGB : Color;
return new LaserZap(args, this, c); return new LaserZap(args, this, c);
} }
} }
@@ -50,7 +50,7 @@ namespace OpenRA.Mods.RA.Effects
this.args = args; this.args = args;
this.info = info; this.info = info;
this.color = color; this.color = color;
this.target = args.passiveTarget; this.target = args.PassiveTarget;
if (info.HitAnim != null) if (info.HitAnim != null)
this.hitanim = new Animation(info.HitAnim); this.hitanim = new Animation(info.HitAnim);
@@ -59,15 +59,15 @@ namespace OpenRA.Mods.RA.Effects
public void Tick(World world) public void Tick(World world)
{ {
// Beam tracks target // Beam tracks target
if (args.guidedTarget.IsValidFor(args.sourceActor)) if (args.GuidedTarget.IsValidFor(args.SourceActor))
target = args.guidedTarget.CenterPosition; target = args.GuidedTarget.CenterPosition;
if (!doneDamage) if (!doneDamage)
{ {
if (hitanim != null) if (hitanim != null)
hitanim.PlayThen("idle", () => animationComplete = true); hitanim.PlayThen("idle", () => animationComplete = true);
Combat.DoImpacts(target, args.sourceActor, args.weapon, args.firepowerModifier); Combat.DoImpacts(target, args.SourceActor, args.Weapon, args.FirepowerModifier);
doneDamage = true; doneDamage = true;
} }
@@ -83,7 +83,7 @@ namespace OpenRA.Mods.RA.Effects
if (ticks < info.BeamDuration) if (ticks < info.BeamDuration)
{ {
var rc = Color.FromArgb((info.BeamDuration - ticks) * 255 / info.BeamDuration, color); var rc = Color.FromArgb((info.BeamDuration - ticks) * 255 / info.BeamDuration, color);
yield return new BeamRenderable(args.source, 0, target - args.source, info.BeamWidth, rc); yield return new BeamRenderable(args.Source, 0, target - args.Source, info.BeamWidth, rc);
} }
if (hitanim != null) if (hitanim != null)

View File

@@ -45,32 +45,38 @@ namespace OpenRA.Mods.RA.Effects
public IEffect Create(ProjectileArgs args) { return new Missile(this, args); } public IEffect Create(ProjectileArgs args) { return new Missile(this, args); }
} }
class Missile : IEffect class Missile : IEffect, ISync
{ {
static readonly WRange MissileCloseEnough = new WRange(7 * 1024 / Game.CellSize);
readonly MissileInfo info; readonly MissileInfo info;
readonly ProjectileArgs args; readonly ProjectileArgs args;
readonly Animation anim; readonly Animation anim;
ContrailRenderable trail;
WPos pos;
int facing;
WPos target;
WVec offset;
int ticks;
bool exploded;
readonly int speed; readonly int speed;
int ticksToNextSmoke;
ContrailRenderable trail;
[Sync] WPos pos;
[Sync] int facing;
[Sync] WPos targetPosition;
[Sync] WVec offset;
[Sync] int ticks;
[Sync] bool exploded;
[Sync] public Actor SourceActor { get { return args.SourceActor; } }
[Sync] public Target GuidedTarget { get { return args.GuidedTarget; } }
public Missile(MissileInfo info, ProjectileArgs args) public Missile(MissileInfo info, ProjectileArgs args)
{ {
this.info = info; this.info = info;
this.args = args; this.args = args;
pos = args.source; pos = args.Source;
facing = args.facing; facing = args.Facing;
target = args.passiveTarget; targetPosition = args.PassiveTarget;
// Convert ProjectileArg definitions to world coordinates // Convert ProjectileArg definitions to world coordinates
// TODO: Change the yaml definitions so we don't need this // TODO: Change the yaml definitions so we don't need this
@@ -78,7 +84,7 @@ namespace OpenRA.Mods.RA.Effects
speed = info.Speed * 1024 / (5 * Game.CellSize); speed = info.Speed * 1024 / (5 * Game.CellSize);
if (info.Inaccuracy > 0) if (info.Inaccuracy > 0)
offset = WVec.FromPDF(args.sourceActor.World.SharedRandom, 2) * inaccuracy / 1024; offset = WVec.FromPDF(args.SourceActor.World.SharedRandom, 2) * inaccuracy / 1024;
if (info.Image != null) if (info.Image != null)
{ {
@@ -88,20 +94,17 @@ namespace OpenRA.Mods.RA.Effects
if (info.ContrailLength > 0) if (info.ContrailLength > 0)
{ {
var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.sourceActor) : info.ContrailColor; var color = info.ContrailUsePlayerColor ? ContrailRenderable.ChooseColor(args.SourceActor) : info.ContrailColor;
trail = new ContrailRenderable(args.sourceActor.World, color, info.ContrailLength, info.ContrailDelay, 0); trail = new ContrailRenderable(args.SourceActor.World, color, info.ContrailLength, info.ContrailDelay, 0);
} }
} }
static readonly WRange MissileCloseEnough = new WRange(7 * 1024 / Game.CellSize);
int ticksToNextSmoke;
bool JammedBy(TraitPair<JamsMissiles> tp) bool JammedBy(TraitPair<JamsMissiles> tp)
{ {
if ((tp.Actor.CenterPosition - pos).HorizontalLengthSquared > tp.Trait.Range * tp.Trait.Range) if ((tp.Actor.CenterPosition - pos).HorizontalLengthSquared > tp.Trait.Range * tp.Trait.Range)
return false; return false;
if (tp.Actor.Owner.Stances[args.sourceActor.Owner] == Stance.Ally && !tp.Trait.AlliedMissiles) if (tp.Actor.Owner.Stances[args.SourceActor.Owner] == Stance.Ally && !tp.Trait.AlliedMissiles)
return false; return false;
return tp.Actor.World.SharedRandom.Next(100 / tp.Trait.Chance) == 0; return tp.Actor.World.SharedRandom.Next(100 / tp.Trait.Chance) == 0;
@@ -120,12 +123,12 @@ namespace OpenRA.Mods.RA.Effects
anim.Tick(); anim.Tick();
// Missile tracks target // Missile tracks target
if (args.guidedTarget.IsValidFor(args.sourceActor)) if (args.GuidedTarget.IsValidFor(args.SourceActor))
target = args.guidedTarget.CenterPosition; targetPosition = args.GuidedTarget.CenterPosition;
var dist = target + offset - pos; var dist = targetPosition + offset - pos;
var desiredFacing = Traits.Util.GetFacing(dist, facing); var desiredFacing = Traits.Util.GetFacing(dist, facing);
var desiredAltitude = target.Z; var desiredAltitude = targetPosition.Z;
var jammed = info.Jammable && world.ActorsWithTrait<JamsMissiles>().Any(j => JammedBy(j)); var jammed = info.Jammable && world.ActorsWithTrait<JamsMissiles>().Any(j => JammedBy(j));
if (jammed) if (jammed)
@@ -133,18 +136,18 @@ namespace OpenRA.Mods.RA.Effects
desiredFacing = facing + world.SharedRandom.Next(-20, 21); desiredFacing = facing + world.SharedRandom.Next(-20, 21);
desiredAltitude = world.SharedRandom.Next(-43, 86); desiredAltitude = world.SharedRandom.Next(-43, 86);
} }
else if (!args.guidedTarget.IsValidFor(args.sourceActor)) else if (!args.GuidedTarget.IsValidFor(args.SourceActor))
desiredFacing = facing; desiredFacing = facing;
facing = Traits.Util.TickFacing(facing, desiredFacing, info.ROT); facing = Traits.Util.TickFacing(facing, desiredFacing, info.ROT);
var move = new WVec(0, -1024, 0).Rotate(WRot.FromFacing(facing)) * speed / 1024; var move = new WVec(0, -1024, 0).Rotate(WRot.FromFacing(facing)) * speed / 1024;
if (target.Z > 0 && info.TurboBoost) if (targetPosition.Z > 0 && info.TurboBoost)
move = (move * 3) / 2; move = (move * 3) / 2;
if (pos.Z != desiredAltitude) if (pos.Z != desiredAltitude)
{ {
var delta = move.HorizontalLength * info.MaximumPitch.Tan() / 1024; var delta = move.HorizontalLength * info.MaximumPitch.Tan() / 1024;
var dz = (target.Z - pos.Z).Clamp(-delta, delta); var dz = (targetPosition.Z - pos.Z).Clamp(-delta, delta);
move += new WVec(0, 0, dz); move += new WVec(0, 0, dz);
} }
@@ -159,9 +162,9 @@ namespace OpenRA.Mods.RA.Effects
if (info.ContrailLength > 0) if (info.ContrailLength > 0)
trail.Update(pos); trail.Update(pos);
var shouldExplode = pos.Z < 0 // Hit the ground var shouldExplode = (pos.Z < 0) // Hit the ground
|| dist.LengthSquared < MissileCloseEnough.Range * MissileCloseEnough.Range // Within range || (dist.LengthSquared < MissileCloseEnough.Range * MissileCloseEnough.Range) // Within range
|| info.RangeLimit != 0 && ticks > info.RangeLimit // Ran out of fuel || (info.RangeLimit != 0 && ticks > info.RangeLimit) // Ran out of fuel
|| (!info.High && world.ActorMap.GetUnitsAt(pos.ToCPos()) || (!info.High && world.ActorMap.GetUnitsAt(pos.ToCPos())
.Any(a => a.HasTrait<IBlocksBullets>())); // Hit a wall .Any(a => a.HasTrait<IBlocksBullets>())); // Hit a wall
@@ -182,7 +185,7 @@ namespace OpenRA.Mods.RA.Effects
if (ticks <= info.Arm) if (ticks <= info.Arm)
return; return;
Combat.DoImpacts(pos, args.sourceActor, args.weapon, args.firepowerModifier); Combat.DoImpacts(pos, args.SourceActor, args.Weapon, args.FirepowerModifier);
} }
public IEnumerable<IRenderable> Render(WorldRenderer wr) public IEnumerable<IRenderable> Render(WorldRenderer wr)
@@ -190,9 +193,9 @@ namespace OpenRA.Mods.RA.Effects
if (info.ContrailLength > 0) if (info.ContrailLength > 0)
yield return trail; yield return trail;
if (!args.sourceActor.World.FogObscures(pos.ToCPos())) if (!args.SourceActor.World.FogObscures(pos.ToCPos()))
{ {
var palette = wr.Palette(args.weapon.Underwater ? "shadow" : "effect"); var palette = wr.Palette(args.Weapon.Underwater ? "shadow" : "effect");
foreach (var r in anim.Render(pos, palette)) foreach (var r in anim.Render(pos, palette))
yield return r; yield return r;
} }

8
OpenRA.Mods.RA/Effects/TeslaZap.cs Executable file → Normal file
View File

@@ -48,8 +48,8 @@ namespace OpenRA.Mods.RA.Effects
if (!doneDamage) if (!doneDamage)
{ {
var pos = Args.guidedTarget.IsValidFor(Args.sourceActor) ? Args.guidedTarget.CenterPosition : Args.passiveTarget; var pos = Args.GuidedTarget.IsValidFor(Args.SourceActor) ? Args.GuidedTarget.CenterPosition : Args.PassiveTarget;
Combat.DoImpacts(pos, Args.sourceActor, Args.weapon, Args.firepowerModifier); Combat.DoImpacts(pos, Args.SourceActor, Args.Weapon, Args.FirepowerModifier);
doneDamage = true; doneDamage = true;
} }
} }
@@ -58,8 +58,8 @@ namespace OpenRA.Mods.RA.Effects
{ {
if (!initialized) if (!initialized)
{ {
var pos = Args.guidedTarget.IsValidFor(Args.sourceActor) ? Args.guidedTarget.CenterPosition : Args.passiveTarget; var pos = Args.GuidedTarget.IsValidFor(Args.SourceActor) ? Args.GuidedTarget.CenterPosition : Args.PassiveTarget;
zap = new TeslaZapRenderable(Args.source, 0, pos - Args.source, Info.Image, Info.BrightZaps, Info.DimZaps); zap = new TeslaZapRenderable(Args.Source, 0, pos - Args.Source, Info.Image, Info.BrightZaps, Info.DimZaps);
} }
yield return zap; yield return zap;
} }