Merge pull request #7275 from RoosterDragon/formatting

Formatted all files.
This commit is contained in:
Igor Popov
2015-01-07 13:56:04 +03:00
153 changed files with 740 additions and 698 deletions

View File

@@ -334,8 +334,9 @@ namespace OpenRA.Editor
{
var vX = (int)Math.Floor((mousePos.X - Offset.X) / Zoom);
var vY = (int)Math.Floor((mousePos.Y - Offset.Y) / Zoom);
return new CPos((vX + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize,
(vY + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize);
return new CPos(
(vX + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize,
(vY + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize);
}
public void DrawActor(SGraphics g, CPos p, ActorTemplate t, ColorPalette cp)

View File

@@ -91,7 +91,7 @@ namespace OpenRA
{
return (k & mod) == mod;
}
public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k)
where V : new()
{

View File

@@ -156,7 +156,7 @@ namespace OpenRA
else if (fieldType == typeof(decimal))
{
decimal res;
if (decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
if (decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
return res * (value.Contains('%') ? 0.01m : 1m);
return InvalidValueAction(value, fieldType, fieldName);
}
@@ -291,7 +291,7 @@ namespace OpenRA
if (Exts.TryParseIntegerInvariant(value, out rr)
&& Exts.TryParseIntegerInvariant(value, out rp)
&& Exts.TryParseIntegerInvariant(value, out ry))
return new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry));
return new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry));
}
return InvalidValueAction(value, fieldType, fieldName);

View File

@@ -390,7 +390,8 @@ namespace OpenRA.FileFormats
MulBignumWord(esi, globOne, tmp, 2 * len);
if ((*edi & 0x8000) == 0)
{
if (0 != SubBigNum((uint*)esi, (uint*)esi, g1, 0, (int)len))(*edi)--;
if (0 != SubBigNum((uint*)esi, (uint*)esi, g1, 0, (int)len))
(*edi)--;
}
}
}

View File

@@ -33,17 +33,17 @@ namespace OpenRA.FileFormats
Transforms = new float[16 * FrameCount * LimbCount];
for (var j = 0; j < FrameCount; j++)
for (var i = 0; i < LimbCount; i++)
{
// Convert to column-major matrices and add the final matrix row
var c = 16 * (LimbCount * j + i);
Transforms[c + 3] = 0;
Transforms[c + 7] = 0;
Transforms[c + 11] = 0;
Transforms[c + 15] = 1;
{
// Convert to column-major matrices and add the final matrix row
var c = 16 * (LimbCount * j + i);
Transforms[c + 3] = 0;
Transforms[c + 7] = 0;
Transforms[c + 11] = 0;
Transforms[c + 15] = 1;
for (var k = 0; k < 12; k++)
Transforms[c + ids[k]] = s.ReadFloat();
}
for (var k = 0; k < 12; k++)
Transforms[c + ids[k]] = s.ReadFloat();
}
}
public static HvaReader Load(string filename)

View File

@@ -44,9 +44,9 @@ namespace OpenRA.FileFormats
switch (line[0])
{
case ';': break;
case '[': currentSection = ProcessSection(line); break;
default: ProcessEntry(line, currentSection); break;
case ';': break;
case '[': currentSection = ProcessSection(line); break;
default: ProcessEntry(line, currentSection); break;
}
}
}

View File

@@ -175,8 +175,8 @@ namespace OpenRA.FileFormats
var jmp = int2.Swap(stream.ReadUInt32());
stream.Seek(jmp, SeekOrigin.Current);
type = stream.ReadASCII(4);
}
}
var length = int2.Swap(stream.ReadUInt32());
switch (type)
@@ -197,10 +197,10 @@ namespace OpenRA.FileFormats
}
compressed = type == "SND2";
break;
break;
default:
stream.ReadBytes((int)length);
break;
break;
}
// Chunks are aligned on even bytes; advance by a byte if the next one is null
@@ -230,7 +230,7 @@ namespace OpenRA.FileFormats
audioData = new byte[rightData.Length + leftData.Length];
var rightIndex = 0;
var leftIndex = 0;
var leftIndex = 0;
for (var i = 0; i < audioData.Length;)
{
audioData[i++] = leftData[leftIndex++];
@@ -273,28 +273,28 @@ namespace OpenRA.FileFormats
stream.Seek(length, SeekOrigin.Current);
type = stream.ReadASCII(4);
}
else
else
throw new NotSupportedException();
}
}
length = int2.Swap(stream.ReadUInt32());
switch (type)
{
case "VQFR":
DecodeVQFR(stream);
break;
break;
case "\0VQF":
stream.ReadByte();
DecodeVQFR(stream);
break;
case "VQFL":
break;
case "VQFL":
DecodeVQFR(stream, "VQFL");
break;
break;
default:
// Don't parse sound here.
stream.ReadBytes((int)length);
break;
break;
}
// Chunks are aligned on even bytes; advance by a byte if the next one is null
@@ -343,10 +343,10 @@ namespace OpenRA.FileFormats
if (parentType == "VQFL")
return;
break;
break;
case "CBF0":
cbf = s.ReadBytes(subchunkLength);
break;
break;
// frame-modifier chunk
case "CBP0":
@@ -366,7 +366,7 @@ namespace OpenRA.FileFormats
bytes.CopyTo(cbp, chunkBufferOffset);
chunkBufferOffset += subchunkLength;
currentChunkBuffer++;
break;
break;
// Palette
case "CPL0":
@@ -378,7 +378,7 @@ namespace OpenRA.FileFormats
palette[i] = (uint)((255 << 24) | (r << 16) | (g << 8) | b);
}
break;
break;
// Frame data
case "VPTZ":
@@ -390,9 +390,9 @@ namespace OpenRA.FileFormats
Array.Clear(origData, 0, origData.Length);
s.Read(fileBuffer, 0, subchunkLength);
if (fileBuffer[0] != 0)
vtprSize = Format80.DecodeInto(fileBuffer, origData);
vtprSize = Format80.DecodeInto(fileBuffer, origData);
else
Format80.DecodeInto(fileBuffer, origData, 1, true);
Format80.DecodeInto(fileBuffer, origData, 1, true);
return;
case "VPTR":
Array.Clear(origData, 0, origData.Length);
@@ -434,21 +434,21 @@ namespace OpenRA.FileFormats
{
case 0:
x += para_A;
break;
break;
case 1:
WriteBlock(para_B1, para_B2, ref x, ref y);
break;
break;
case 2:
WriteBlock(para_B1, 1, ref x, ref y);
for (var i = 0; i < para_B2; i++)
WriteBlock(origData[p++], 1, ref x, ref y);
break;
for (var i = 0; i < para_B2; i++)
WriteBlock(origData[p++], 1, ref x, ref y);
break;
case 3:
WriteBlock(para_A, 1, ref x, ref y);
break;
break;
case 5:
WriteBlock(para_A, origData[p++], ref x, ref y);
break;
break;
default:
throw new NotSupportedException();
}

View File

@@ -32,7 +32,7 @@ namespace OpenRA.FileFormats
public enum WaveType { Pcm = 0x1, ImaAdpcm = 0x11 }
public static WaveType Type { get; private set; }
public WavLoader(Stream s)
{
while (s.Position < s.Length)
@@ -92,7 +92,7 @@ namespace OpenRA.FileFormats
BitsPerSample = 16;
}
}
public static float WaveLength(Stream s)
{
s.Position = 12;

View File

@@ -75,8 +75,8 @@ namespace OpenRA.FileSystem
foreach (var file in contents)
using (var dataStream = File.Create(Path.Combine(path, file.Key)))
using (var writer = new BinaryWriter(dataStream))
writer.Write(file.Value);
using (var writer = new BinaryWriter(dataStream))
writer.Write(file.Value);
}
}
}

View File

@@ -218,7 +218,7 @@ namespace OpenRA.FileSystem
public int Priority { get { return 1000 + priority; } }
public string Name { get { return filename; } }
public void Write(Dictionary<string, byte[]> contents)
{
// Cannot modify existing mixfile - rename existing file and

View File

@@ -59,41 +59,41 @@ namespace OpenRA.FileSystem
{
switch (type)
{
case PackageHashType.Classic:
{
name = name.ToUpperInvariant();
if (name.Length % 4 != 0)
name = name.PadRight(name.Length + (4 - name.Length % 4), '\0');
var ms = new MemoryStream(Encoding.ASCII.GetBytes(name));
var reader = new BinaryReader(ms);
var len = name.Length >> 2;
uint result = 0;
while (len-- != 0)
result = ((result << 1) | (result >> 31)) + reader.ReadUInt32();
return result;
}
case PackageHashType.CRC32:
{
name = name.ToUpperInvariant();
var l = name.Length;
var a = l >> 2;
if ((l & 3) != 0)
case PackageHashType.Classic:
{
name += (char)(l - (a << 2));
var i = 3 - (l & 3);
while (i-- != 0)
name += name[a << 2];
name = name.ToUpperInvariant();
if (name.Length % 4 != 0)
name = name.PadRight(name.Length + (4 - name.Length % 4), '\0');
var ms = new MemoryStream(Encoding.ASCII.GetBytes(name));
var reader = new BinaryReader(ms);
var len = name.Length >> 2;
uint result = 0;
while (len-- != 0)
result = ((result << 1) | (result >> 31)) + reader.ReadUInt32();
return result;
}
return CRC32.Calculate(Encoding.ASCII.GetBytes(name));
}
case PackageHashType.CRC32:
{
name = name.ToUpperInvariant();
var l = name.Length;
var a = l >> 2;
if ((l & 3) != 0)
{
name += (char)(l - (a << 2));
var i = 3 - (l & 3);
while (i-- != 0)
name += name[a << 2];
}
default: throw new NotImplementedException("Unknown hash type `{0}`".F(type));
return CRC32.Calculate(Encoding.ASCII.GetBytes(name));
}
default: throw new NotImplementedException("Unknown hash type `{0}`".F(type));
}
}

View File

@@ -153,7 +153,7 @@ namespace OpenRA
if (worldRenderer != null)
worldRenderer.Dispose();
worldRenderer = new WorldRenderer(OrderManager.World);
using (new PerfTimer("LoadComplete"))
OrderManager.World.LoadComplete(worldRenderer);

View File

@@ -92,7 +92,8 @@ namespace OpenRA
if (constructOrderCache != null)
return constructOrderCache;
var source = Traits.WithInterface<ITraitInfo>().Select(i => new {
var source = Traits.WithInterface<ITraitInfo>().Select(i => new
{
Trait = i,
Type = i.GetType(),
Dependencies = PrerequisitesOf(i).ToList()

View File

@@ -23,10 +23,10 @@ namespace OpenRA.GameRules
[Desc("What types of targets are unaffected.", "Overrules ValidTargets.")]
public readonly string[] InvalidTargets = { };
[Desc("What diplomatic stances are affected.")]
public readonly Stance ValidStances = Stance.Ally | Stance.Neutral | Stance.Enemy;
[Desc("Can this warhead affect the actor that fired it.")]
public readonly bool AffectsParent = false;

View File

@@ -85,7 +85,7 @@ namespace OpenRA
}
public enum TextureScaleFilter { Nearest, Linear }
public interface ITexture : IDisposable
{
void SetData(Bitmap bitmap);

View File

@@ -83,7 +83,7 @@ namespace OpenRA.Graphics
var isAlly = actor.Owner.IsAlliedWith(actor.World.LocalPlayer)
|| (actor.EffectiveOwner != null && actor.EffectiveOwner.Disguised
&& actor.World.LocalPlayer.IsAlliedWith(actor.EffectiveOwner.Owner));
return isAlly ? Color.LimeGreen : actor.Owner.NonCombatant ? Color.Tan : Color.Red;
return isAlly ? Color.LimeGreen : actor.Owner.NonCombatant ? Color.Tan : Color.Red;
}
else
return health.DamageState == DamageState.Critical ? Color.Red :

View File

@@ -106,12 +106,12 @@ namespace OpenRA.Graphics
{
var mtx = new float[16];
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
{
mtx[4 * i + j] = 0;
for (var k = 0; k < 4; k++)
mtx[4 * i + j] += lhs[4 * k + j] * rhs[4 * i + k];
}
for (var j = 0; j < 4; j++)
{
mtx[4 * i + j] = 0;
for (var k = 0; k < 4; k++)
mtx[4 * i + j] += lhs[4 * k + j] * rhs[4 * i + k];
}
return mtx;
}
@@ -250,7 +250,7 @@ namespace OpenRA.Graphics
return null;
for (var i = 0; i < 16; i++)
mtx[i] *= 1 / det;
mtx[i] *= 1 / det;
return mtx;
}

View File

@@ -77,9 +77,10 @@ namespace OpenRA.Graphics
shader.SetMatrix("View", view);
}
public VoxelRenderProxy RenderAsync(WorldRenderer wr, IEnumerable<VoxelAnimation> voxels, WRot camera, float scale,
float[] groundNormal, WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor,
PaletteReference color, PaletteReference normals, PaletteReference shadowPalette)
public VoxelRenderProxy RenderAsync(
WorldRenderer wr, IEnumerable<VoxelAnimation> voxels, WRot camera, float scale,
float[] groundNormal, WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor,
PaletteReference color, PaletteReference normals, PaletteReference shadowPalette)
{
// Correct for inverted y-axis
var scaleTransform = Util.ScaleMatrix(scale, scale, scale);
@@ -202,7 +203,7 @@ namespace OpenRA.Graphics
var lightDirection = ExtractRotationVector(Util.MatrixMultiply(Util.MatrixInverse(t), lightTransform));
Render(rd, Util.MatrixMultiply(transform, t), lightDirection,
lightAmbientColor, lightDiffuseColor, color.Index, normals.Index);
lightAmbientColor, lightDiffuseColor, color.Index, normals.Index);
// Disable shadow normals by forcing zero diffuse and identity ambient light
Render(rd, Util.MatrixMultiply(shadow, t), lightDirection,
@@ -249,14 +250,16 @@ namespace OpenRA.Graphics
return tVec;
}
void Render(VoxelRenderData renderData,
float[] t, float[] lightDirection,
float[] ambientLight, float[] diffuseLight,
int colorPalette, int normalsPalette)
void Render(
VoxelRenderData renderData,
float[] t, float[] lightDirection,
float[] ambientLight, float[] diffuseLight,
int colorPalette, int normalsPalette)
{
shader.SetTexture("DiffuseTexture", renderData.Sheet.GetTexture());
shader.SetVec("PaletteRows", (colorPalette + 0.5f) / HardwarePalette.MaxPalettes,
(normalsPalette + 0.5f) / HardwarePalette.MaxPalettes);
shader.SetVec("PaletteRows",
(colorPalette + 0.5f) / HardwarePalette.MaxPalettes,
(normalsPalette + 0.5f) / HardwarePalette.MaxPalettes);
shader.SetMatrix("TransformMatrix", t);
shader.SetVec("LightDirection", lightDirection, 4);
shader.SetVec("AmbientLight", ambientLight, 3);

View File

@@ -270,8 +270,7 @@ namespace OpenRA
}
}
if (throwErrors)
if (noInherit.ContainsValue(false))
if (throwErrors && noInherit.ContainsValue(false))
throw new YamlException("Bogus yaml removals: {0}".F(
noInherit.Where(x => !x.Value).JoinWith(", ")));

View File

@@ -53,10 +53,10 @@ namespace OpenRA.Network
{
case "Handshake":
FieldLoader.Load(handshake, y.Value);
break;
break;
case "Client":
FieldLoader.Load(handshake.Client, y.Value);
break;
break;
}
}

View File

@@ -52,7 +52,7 @@ namespace OpenRA.Network
}
case "Message": // Server message
Game.AddChatLine(Color.White, "Server", order.TargetString);
Game.AddChatLine(Color.White, "Server", order.TargetString);
break;
case "Disconnected": /* reports that the target player disconnected */

View File

@@ -107,7 +107,7 @@ namespace OpenRA
var it = typeof(T);
return GetTypes().Where(t => t != it && it.IsAssignableFrom(t));
}
public IEnumerable<Type> GetTypes()
{
return assemblies.Select(ma => ma.First).Distinct()

View File

@@ -26,24 +26,24 @@ namespace OpenRA
static PlatformType GetCurrentPlatform()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
return PlatformType.Windows;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
return PlatformType.Windows;
try
{
var psi = new ProcessStartInfo("uname", "-s");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
var p = Process.Start(psi);
var kernelName = p.StandardOutput.ReadToEnd();
if (kernelName.Contains("Linux") || kernelName.Contains("BSD"))
return PlatformType.Linux;
if (kernelName.Contains("Darwin"))
return PlatformType.OSX;
}
catch { }
try
{
var psi = new ProcessStartInfo("uname", "-s");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
var p = Process.Start(psi);
var kernelName = p.StandardOutput.ReadToEnd();
if (kernelName.Contains("Linux") || kernelName.Contains("BSD"))
return PlatformType.Linux;
if (kernelName.Contains("Darwin"))
return PlatformType.OSX;
}
catch { }
return PlatformType.Unknown;
return PlatformType.Unknown;
}
public static string RuntimeVersion
@@ -58,7 +58,7 @@ namespace OpenRA
if (version == null)
return "Mono (unknown version) CLR {0}".F(Environment.Version);
return "Mono {0} CLR {1}".F(version.Invoke(null, null), Environment.Version);
return "Mono {0} CLR {1}".F(version.Invoke(null, null), Environment.Version);
}
}
@@ -75,16 +75,16 @@ namespace OpenRA
switch (CurrentPlatform)
{
case PlatformType.Windows:
dir += Path.DirectorySeparatorChar + "OpenRA";
break;
case PlatformType.OSX:
dir += "/Library/Application Support/OpenRA";
break;
case PlatformType.Linux:
default:
dir += "/.openra";
break;
case PlatformType.Windows:
dir += Path.DirectorySeparatorChar + "OpenRA";
break;
case PlatformType.OSX:
dir += "/Library/Application Support/OpenRA";
break;
case PlatformType.Linux:
default:
dir += "/.openra";
break;
}
if (!Directory.Exists(dir))

View File

@@ -347,7 +347,7 @@ namespace OpenRA.Server
LobbyInfo.ClientPings.Add(clientPing);
Log.Write("server", "Client {0}: Accepted connection from {1}.",
newConn.PlayerIndex, newConn.Socket.RemoteEndPoint);
newConn.PlayerIndex, newConn.Socket.RemoteEndPoint);
foreach (var t in serverTraits.WithInterface<IClientJoined>())
t.ClientJoined(this, newConn);
@@ -451,20 +451,20 @@ namespace OpenRA.Server
switch (so.Name)
{
case "Command":
{
var handled = false;
foreach (var t in serverTraits.WithInterface<IInterpretCommand>())
if (handled = t.InterpretCommand(this, conn, GetClient(conn), so.Data))
break;
if (!handled)
{
Log.Write("server", "Unknown server command: {0}", so.Data);
SendOrderTo(conn, "Message", "Unknown server command: {0}".F(so.Data));
}
var handled = false;
foreach (var t in serverTraits.WithInterface<IInterpretCommand>())
if (handled = t.InterpretCommand(this, conn, GetClient(conn), so.Data))
break;
break;
}
if (!handled)
{
Log.Write("server", "Unknown server command: {0}", so.Data);
SendOrderTo(conn, "Message", "Unknown server command: {0}".F(so.Data));
}
break;
}
case "HandshakeResponse":
ValidateClient(conn, so.Data);
@@ -475,33 +475,33 @@ namespace OpenRA.Server
DispatchOrdersToClients(conn, 0, so.Serialize());
break;
case "Pong":
{
int pingSent;
if (!OpenRA.Exts.TryParseIntegerInvariant(so.Data, out pingSent))
{
Log.Write("server", "Invalid order pong payload: {0}", so.Data);
int pingSent;
if (!OpenRA.Exts.TryParseIntegerInvariant(so.Data, out pingSent))
{
Log.Write("server", "Invalid order pong payload: {0}", so.Data);
break;
}
var pingFromClient = LobbyInfo.PingFromClient(GetClient(conn));
if (pingFromClient == null)
return;
var history = pingFromClient.LatencyHistory.ToList();
history.Add(Game.RunTime - pingSent);
// Cap ping history at 5 values (25 seconds)
if (history.Count > 5)
history.RemoveRange(0, history.Count - 5);
pingFromClient.Latency = history.Sum() / history.Count;
pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2;
pingFromClient.LatencyHistory = history.ToArray();
SyncClientPing();
break;
}
var pingFromClient = LobbyInfo.PingFromClient(GetClient(conn));
if (pingFromClient == null)
return;
var history = pingFromClient.LatencyHistory.ToList();
history.Add(Game.RunTime - pingSent);
// Cap ping history at 5 values (25 seconds)
if (history.Count > 5)
history.RemoveRange(0, history.Count - 5);
pingFromClient.Latency = history.Sum() / history.Count;
pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2;
pingFromClient.LatencyHistory = history.ToArray();
SyncClientPing();
break;
}
}
}

View File

@@ -61,11 +61,11 @@ namespace OpenRA
engine = Game.Settings.Server.Dedicated ? "Null" : engine;
switch (engine)
{
case "AL": return new OpenAlSoundEngine();
case "Null": return new NullSoundEngine();
case "AL": return new OpenAlSoundEngine();
case "Null": return new NullSoundEngine();
default:
throw new InvalidOperationException("Unsupported sound engine: {0}".F(engine));
default:
throw new InvalidOperationException("Unsupported sound engine: {0}".F(engine));
}
}
@@ -373,7 +373,7 @@ namespace OpenRA
var type = mi.Voice.ToLowerInvariant();
return PlayPredefined(voicedUnit.World.Map.Rules, null, voicedUnit, type, phrase, variant, true, WPos.Zero, 1f, true);
}
public static bool PlayVoiceLocal(string phrase, Actor voicedUnit, string variant, WPos pos, float volume)
{
if (voicedUnit == null || phrase == null)

View File

@@ -28,9 +28,9 @@ namespace OpenRA
{
var path = Platform.SupportDir + "Logs";
Directory.CreateDirectory(path);
for (var i = 0;; i++)
yield return Path.Combine(path, i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename);
yield return Path.Combine(path, i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename);
}
public static void AddChannel(string channelName, string baseFilename)

View File

@@ -92,7 +92,7 @@ namespace OpenRA.Traits
};
foreach (var nd in self.TraitsImplementing<INotifyDamage>()
.Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyDamage>()))
.Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyDamage>()))
nd.Damaged(self, ai);
foreach (var nd in self.TraitsImplementing<INotifyDamageStateChanged>())
@@ -100,7 +100,7 @@ namespace OpenRA.Traits
if (Info.NotifyAppliedDamage && repairer != null && repairer.IsInWorld && !repairer.IsDead)
foreach (var nd in repairer.TraitsImplementing<INotifyAppliedDamage>()
.Concat(repairer.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>()))
.Concat(repairer.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>()))
nd.AppliedDamage(repairer, self, ai);
}
@@ -144,7 +144,7 @@ namespace OpenRA.Traits
if (Info.NotifyAppliedDamage && attacker != null && attacker.IsInWorld && !attacker.IsDead)
foreach (var nd in attacker.TraitsImplementing<INotifyAppliedDamage>()
.Concat(attacker.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>()))
nd.AppliedDamage(attacker, self, ai);
nd.AppliedDamage(attacker, self, ai);
if (hp == 0)
{

View File

@@ -101,15 +101,15 @@ namespace OpenRA.Traits
{
switch (Type)
{
case TargetType.Actor:
return actor.CenterPosition;
case TargetType.FrozenActor:
return frozen.CenterPosition;
case TargetType.Terrain:
return pos;
default:
case TargetType.Invalid:
throw new InvalidOperationException("Attempting to query the position of an invalid Target");
case TargetType.Actor:
return actor.CenterPosition;
case TargetType.FrozenActor:
return frozen.CenterPosition;
case TargetType.Terrain:
return pos;
default:
case TargetType.Invalid:
throw new InvalidOperationException("Attempting to query the position of an invalid Target");
}
}
}
@@ -122,20 +122,20 @@ namespace OpenRA.Traits
{
switch (Type)
{
case TargetType.Actor:
var targetable = actor.TraitOrDefault<ITargetable>();
if (targetable == null)
return new[] { actor.CenterPosition };
case TargetType.Actor:
var targetable = actor.TraitOrDefault<ITargetable>();
if (targetable == null)
return new[] { actor.CenterPosition };
var positions = targetable.TargetablePositions(actor);
return positions.Any() ? positions : new[] { actor.CenterPosition };
case TargetType.FrozenActor:
return new[] { frozen.CenterPosition };
case TargetType.Terrain:
return new[] { pos };
default:
case TargetType.Invalid:
return NoPositions;
var positions = targetable.TargetablePositions(actor);
return positions.Any() ? positions : new[] { actor.CenterPosition };
case TargetType.FrozenActor:
return new[] { frozen.CenterPosition };
case TargetType.Terrain:
return new[] { pos };
default:
case TargetType.Invalid:
return NoPositions;
}
}
}

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Traits
// depends on the order of pips in WorldRenderer.cs!
public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue, Ammo, AmmoEmpty }
public enum TagType { None, Fake, Primary }
[Flags]
public enum Stance
{
@@ -259,7 +259,7 @@ namespace OpenRA.Traits
}
public interface IRenderOverlay { void Render(WorldRenderer wr); }
public interface INotifyBecomingIdle { void OnBecomingIdle(Actor self); }
public interface INotifyBecomingIdle { void OnBecomingIdle(Actor self); }
public interface INotifyIdle { void TickIdle(Actor self); }
public interface IBlocksBullets { }

View File

@@ -63,16 +63,16 @@ namespace OpenRA
switch (components.Length)
{
case 2:
if (!Exts.TryParseIntegerInvariant(components[0], out cell) ||
!Exts.TryParseIntegerInvariant(components[1], out subcell))
case 2:
if (!Exts.TryParseIntegerInvariant(components[0], out cell) ||
!Exts.TryParseIntegerInvariant(components[1], out subcell))
return false;
break;
case 1:
if (!Exts.TryParseIntegerInvariant(components[0], out subcell))
return false;
break;
default: return false;
break;
case 1:
if (!Exts.TryParseIntegerInvariant(components[0], out subcell))
return false;
break;
default: return false;
}
// Propagate sign to fractional part

View File

@@ -28,8 +28,10 @@ namespace OpenRA
public static WRot operator -(WRot a, WRot b) { return new WRot(a.Roll - b.Roll, a.Pitch - b.Pitch, a.Yaw - b.Yaw); }
public static WRot operator -(WRot a) { return new WRot(-a.Roll, -a.Pitch, -a.Yaw); }
public static bool operator ==(WRot me, WRot other) { return me.Roll == other.Roll &&
me.Pitch == other.Pitch && me.Yaw == other.Yaw; }
public static bool operator ==(WRot me, WRot other)
{
return me.Roll == other.Roll && me.Pitch == other.Pitch && me.Yaw == other.Yaw;
}
public static bool operator !=(WRot me, WRot other) { return !(me == other); }

View File

@@ -52,7 +52,7 @@ namespace OpenRA.Widgets
// Equivalent to OnMouseUp, but without an input arg
public Action OnClick = () => { };
public Action OnDoubleClick = () => { };
public Action OnDoubleClick = () => { };
public Action<KeyInput> OnKeyPress = _ => { };
protected readonly Ruleset ModRules;
@@ -149,7 +149,7 @@ namespace OpenRA.Widgets
OnDoubleClick();
return YieldMouseFocus(mi);
}
}
}
else if (HasMouseFocus && mi.Event == MouseInputEvent.Up)
{
// Only fire the onMouseUp event if we successfully lost focus, and were pressed
@@ -197,8 +197,14 @@ namespace OpenRA.Widgets
tooltipContainer.Value.RemoveTooltip();
}
public override int2 ChildOrigin { get { return RenderOrigin +
(Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0)); } }
public override int2 ChildOrigin
{
get
{
return RenderOrigin +
(Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0));
}
}
public override void Draw()
{

View File

@@ -101,8 +101,7 @@ namespace OpenRA.Widgets
public void ShowDropDown<T>(string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
{
var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } };
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs()
{ { "substitutions", substitutions } });
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() { { "substitutions", substitutions } });
var itemTemplate = panel.Get<ScrollItemWidget>("TEMPLATE");
panel.RemoveChildren();
@@ -124,8 +123,7 @@ namespace OpenRA.Widgets
public void ShowDropDown<T>(string panelTemplate, int height, Dictionary<string, IEnumerable<T>> groups, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
{
var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } };
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs()
{ { "substitutions", substitutions } });
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() { { "substitutions", substitutions } });
var headerTemplate = panel.GetOrNull<ScrollItemWidget>("HEADER");
var itemTemplate = panel.Get<ScrollItemWidget>("TEMPLATE");

View File

@@ -61,22 +61,22 @@ namespace OpenRA.Widgets
switch (mi.Event)
{
case MouseInputEvent.Up:
isMoving = false;
YieldMouseFocus(mi);
break;
case MouseInputEvent.Up:
isMoving = false;
YieldMouseFocus(mi);
break;
case MouseInputEvent.Down:
isMoving = true;
/* TODO: handle snapping to ticks properly again */
/* TODO: handle nudge via clicking outside the thumb */
UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left));
break;
case MouseInputEvent.Move:
if (isMoving)
case MouseInputEvent.Down:
isMoving = true;
/* TODO: handle snapping to ticks properly again */
/* TODO: handle nudge via clicking outside the thumb */
UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left));
break;
break;
case MouseInputEvent.Move:
if (isMoving)
UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left));
break;
}
return ThumbRect.Contains(mi.Location);

View File

@@ -268,9 +268,10 @@ namespace OpenRA.Widgets
Bounds.Width - LeftMargin - RightMargin, Bounds.Bottom));
}
var color = disabled ? TextColorDisabled
: IsValid() ? TextColor
: TextColorInvalid;
var color =
disabled ? TextColorDisabled
: IsValid() ? TextColor
: TextColorInvalid;
font.DrawText(apparentText, textPos, color);
if (showCursor && HasKeyboardFocus)

View File

@@ -71,7 +71,7 @@ namespace OpenRA.Widgets
0,
0,
video.Width,
video.Height),
video.Height),
TextureChannel.Alpha);
var scale = Math.Min((float)RenderBounds.Width / video.Width, (float)RenderBounds.Height / video.Height * AspectRatio);
@@ -121,15 +121,15 @@ namespace OpenRA.Widgets
skippedFrames++;
}
if (skippedFrames > 1)
Log.Write("perf", "VqaPlayer : {0} skipped {1} frames at position {2}", cachedVideo, skippedFrames, video.CurrentFrame);
if (skippedFrames > 1)
Log.Write("perf", "VqaPlayer : {0} skipped {1} frames at position {2}", cachedVideo, skippedFrames, video.CurrentFrame);
}
Game.Renderer.RgbaSpriteRenderer.DrawSprite(
videoSprite,
videoOrigin,
videoSize);
if (DrawOverlay)
Game.Renderer.RgbaSpriteRenderer.DrawSprite(overlaySprite, videoOrigin, videoSize);
}

View File

@@ -485,7 +485,7 @@ namespace OpenRA.Widgets
public override string GetCursor(int2 pos) { return null; }
public override Widget Clone() { return new ContainerWidget(this); }
public Func<KeyInput, bool> OnKeyPress = _ => false;
public override bool HandleKeyPress(KeyInput e) { return OnKeyPress(e); }
public override bool HandleKeyPress(KeyInput e) { return OnKeyPress(e); }
}
public class WidgetArgs : Dictionary<string, object>

View File

@@ -47,7 +47,7 @@ namespace OpenRA
{
if (!args.ContainsKey("modRules"))
args = new WidgetArgs(args) { { "modRules", modData.DefaultRules } };
var widget = NewWidget(node.Key, args);
if (parent != null)

View File

@@ -105,7 +105,7 @@ namespace OpenRA.Widgets
// Background
if (ps.HasFlags(PanelSides.Center) && ss[8] != null)
FillRectWithSprite(new Rectangle(bounds.Left + marginLeft, bounds.Top + marginTop,
bounds.Width - marginWidth, bounds.Height - marginHeight),
bounds.Width - marginWidth, bounds.Height - marginHeight),
ss[8]);
// Left border

View File

@@ -81,7 +81,7 @@ namespace OpenRA.Widgets
var unit = World.ScreenMap.ActorsAt(xy)
.WithHighestSelectionPriority();
var newSelection2 = SelectActorsInBox(World, worldRenderer.Viewport.TopLeft, worldRenderer.Viewport.BottomRight,
var newSelection2 = SelectActorsInBox(World, worldRenderer.Viewport.TopLeft, worldRenderer.Viewport.BottomRight,
a => unit != null && a.Info.Name == unit.Info.Name && a.Owner == unit.Owner);
World.Selection.Combine(World, newSelection2, true, false);
@@ -98,7 +98,7 @@ namespace OpenRA.Widgets
}
// don't issue orders while selecting
if (mi.Button == MouseButton.Right && mi.Event == MouseInputEvent.Down && !hasBox)
if (mi.Button == MouseButton.Right && mi.Event == MouseInputEvent.Down && !hasBox)
ApplyOrders(World, xy, mi);
lastMousePosition = xy;

View File

@@ -66,7 +66,7 @@ namespace OpenRA
public bool ShroudObscures(Actor a) { return RenderPlayer != null && !RenderPlayer.Shroud.IsExplored(a); }
public bool ShroudObscures(CPos p) { return RenderPlayer != null && !RenderPlayer.Shroud.IsExplored(p); }
public bool ShroudObscures(int u, int v) { return RenderPlayer != null && !RenderPlayer.Shroud.IsExplored(u, v); }
public Func<int, int, bool> FogObscuresTest(CellRegion region)
{
var rp = RenderPlayer;

View File

@@ -22,7 +22,7 @@ namespace OpenRA
{
static string processName = "OpenRA.Game.exe";
static Process gameProcess;
[STAThread]
static void Main(string[] args)
{
@@ -67,14 +67,14 @@ namespace OpenRA
Text = "OpenRA has encountered a fatal error and must close.{0}Refer to the crash logs and FAQ for more information.".F(Environment.NewLine),
TextAlign = ContentAlignment.TopCenter
};
var viewLogs = new Button
{
Location = new Point(10, 80),
Size = new Size(75, 23),
Text = "View Logs"
};
var viewFaq = new Button
{
Location = new Point(90, 80),
@@ -89,7 +89,7 @@ namespace OpenRA
Text = "Quit",
DialogResult = DialogResult.Cancel
};
form.Controls.Add(notice);
form.Controls.Add(viewLogs);
form.Controls.Add(viewFaq);

View File

@@ -53,7 +53,8 @@ namespace OpenRA.Mods.Cnc.Activities
state = State.Dock;
return Util.SequenceActivities(new Drag(self, startDock, endDock, 12), this);
case State.Dock:
ru.PlayCustomAnimation(self, "dock", () => {
ru.PlayCustomAnimation(self, "dock", () =>
{
ru.PlayCustomAnimRepeating(self, "dock-loop");
if (proc.IsInWorld && !proc.IsDead)
foreach (var nd in proc.TraitsImplementing<INotifyDocking>())

View File

@@ -108,7 +108,7 @@ namespace OpenRA.Mods.Common.Activities
if (dest == null)
{
var nearestAfld = ChooseAirfield(self, false);
self.CancelActivity();
if (nearestAfld != null)
return Util.SequenceActivities(new Fly(self, Target.FromActor(nearestAfld)), new FlyCircle());

View File

@@ -53,7 +53,7 @@ namespace OpenRA.Mods.Common.Activities
var type = Target.Type;
if (!Target.IsValidFor(self) || type == TargetType.FrozenActor)
return NextActivity;
if (attack.Info.AttackRequiresEnteringCell && !positionable.CanEnterCell(Target.Actor.Location, null, false))
return NextActivity;

View File

@@ -117,7 +117,7 @@ namespace OpenRA.Mods.Common.Activities
ReserveStatus TryReserveElseTryAlternateReserve(Actor self)
{
for (var tries = 0;;)
for (var tries = 0;;)
switch (Reserve(self))
{
case ReserveStatus.None:
@@ -255,7 +255,7 @@ namespace OpenRA.Mods.Common.Activities
// Check target validity if not exiting or done
if (nextState != State.Done && (target.Type != TargetType.Actor || !target.IsValidFor(self)))
AbortOrExit(self);
AbortOrExit(self);
// If no current activity, tick next activity
if (inner == null && FindAndTransitionToNextState(self) == State.Done)

View File

@@ -44,7 +44,7 @@ namespace OpenRA.Mods.Common.Activities
protected override void OnInside(Actor self)
{
self.World.AddFrameEndTask(w =>
self.World.AddFrameEndTask(w =>
{
if (self.IsDead || transport.IsDead || !cargo.CanLoad(transport, self))
return;

View File

@@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.Activities
{
if (IsCanceled)
return NextActivity;
var target = targets.ClosestTo(self);
if (target == null)
return this;

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Mods.Common.Commands
World world;
ChatCommands console;
public HelpCommand()
public HelpCommand()
{
helpDescriptions = new Dictionary<string, string>();
}

View File

@@ -41,7 +41,9 @@ namespace OpenRA.Mods.Common.Commands
{
case "pause":
world.IssueOrder(new Order("PauseGame", null, false)
{ TargetString = world.Paused ? "UnPause" : "Pause" });
{
TargetString = world.Paused ? "UnPause" : "Pause"
});
break;
case "surrender":
world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));

View File

@@ -92,7 +92,7 @@ namespace OpenRA.Mods.Common.Effects
var palette = r.Palette(palettePrefix + owner.InternalName);
foreach (var a in circles.Render(position, palette))
yield return a;
foreach (var a in arrow.Render(position + new WVec(0, 0, arrowHeight), palette))
yield return a;

View File

@@ -52,7 +52,7 @@ namespace OpenRA.Mods.Common.Effects
[Desc("Explodes when leaving the following terrain type, e.g., Water for torpedoes.")]
public readonly string BoundToTerrainType = "";
[Desc("Explodes when inside this proximity radius to target.",
"Note: If this value is lower than the missile speed, this check might",
"Note: If this value is lower than the missile speed, this check might",
"not trigger fast enough, causing the missile to fly past the target.")]
public readonly WRange CloseEnough = new WRange(298);

View File

@@ -32,9 +32,10 @@ namespace OpenRA.Mods.Common.Graphics
// Generated at render-time
VoxelRenderProxy renderProxy;
public VoxelRenderable(IEnumerable<VoxelAnimation> voxels, WPos pos, int zOffset, WRot camera, float scale,
WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor,
PaletteReference color, PaletteReference normals, PaletteReference shadow)
public VoxelRenderable(
IEnumerable<VoxelAnimation> voxels, WPos pos, int zOffset, WRot camera, float scale,
WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor,
PaletteReference color, PaletteReference normals, PaletteReference shadow)
{
this.voxels = voxels;
this.pos = pos;
@@ -58,30 +59,34 @@ namespace OpenRA.Mods.Common.Graphics
public IRenderable WithScale(float newScale)
{
return new VoxelRenderable(voxels, pos, zOffset, camera, newScale,
lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
return new VoxelRenderable(
voxels, pos, zOffset, camera, newScale,
lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
}
public IRenderable WithPalette(PaletteReference newPalette)
{
return new VoxelRenderable(voxels, pos, zOffset, camera, scale,
lightSource, lightAmbientColor, lightDiffuseColor,
newPalette, normalsPalette, shadowPalette);
return new VoxelRenderable(
voxels, pos, zOffset, camera, scale,
lightSource, lightAmbientColor, lightDiffuseColor,
newPalette, normalsPalette, shadowPalette);
}
public IRenderable WithZOffset(int newOffset)
{
return new VoxelRenderable(voxels, pos, newOffset, camera, scale,
lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
return new VoxelRenderable(
voxels, pos, newOffset, camera, scale,
lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
}
public IRenderable OffsetBy(WVec vec)
{
return new VoxelRenderable(voxels, pos + vec, zOffset, camera, scale,
lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
return new VoxelRenderable(
voxels, pos + vec, zOffset, camera, scale,
lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
}
public IRenderable AsDecoration() { return this; }

View File

@@ -20,7 +20,8 @@ namespace OpenRA.Mods.Common.Scripting
public class MapGlobal : ScriptGlobal
{
SpawnMapActors sma;
public MapGlobal(ScriptContext context) : base(context)
public MapGlobal(ScriptContext context)
: base(context)
{
sma = context.World.WorldActor.Trait<SpawnMapActors>();

View File

@@ -19,7 +19,8 @@ namespace OpenRA.Mods.Common.Scripting
public class MediaGlobal : ScriptGlobal
{
World world;
public MediaGlobal(ScriptContext context) : base(context)
public MediaGlobal(ScriptContext context)
: base(context)
{
world = context.World;
}

View File

@@ -413,7 +413,7 @@ namespace OpenRA.Mods.Common.Scripting
GetScriptTriggers(a).ClearAll();
}
[Desc("Removes the specified trigger from this actor." +
[Desc("Removes the specified trigger from this actor." +
"Note that the removal will only take effect at the end of a tick, " +
"so you must not add new triggers at the same time that you are calling this function.")]
public void Clear(Actor a, string triggerName)

View File

@@ -18,8 +18,11 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Scripting
{
public enum Trigger { OnIdle, OnDamaged, OnKilled, OnProduction, OnOtherProduction, OnPlayerWon, OnPlayerLost,
OnObjectiveAdded, OnObjectiveCompleted, OnObjectiveFailed, OnCapture, OnInfiltrated, OnAddedToWorld, OnRemovedFromWorld }
public enum Trigger
{
OnIdle, OnDamaged, OnKilled, OnProduction, OnOtherProduction, OnPlayerWon, OnPlayerLost,
OnObjectiveAdded, OnObjectiveCompleted, OnObjectiveFailed, OnCapture, OnInfiltrated, OnAddedToWorld, OnRemovedFromWorld
}
[Desc("Allows map scripts to attach triggers to this actor via the Triggers global.")]
public class ScriptTriggersInfo : ITraitInfo

View File

@@ -20,8 +20,8 @@ namespace OpenRA.Mods.Common.Server
{
public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame, IEndGame
{
const int MasterPingInterval = 60 * 3; // 3 minutes. server has a 5 minute TTL for games, so give ourselves a bit
// of leeway.
// 3 minutes. Server has a 5 minute TTL for games, so give ourselves a bit of leeway.
const int MasterPingInterval = 60 * 3;
public int TickTimeout { get { return MasterPingInterval * 10000; } }
public void Tick(S server)

View File

@@ -168,26 +168,26 @@ namespace OpenRA.Mods.Common.SpriteLoaders
{
case Format.Format20:
case Format.Format40:
{
if (h.RefImage.Data == null)
{
++recurseDepth;
Decompress(h.RefImage);
--recurseDepth;
if (h.RefImage.Data == null)
{
++recurseDepth;
Decompress(h.RefImage);
--recurseDepth;
}
h.Data = CopyImageData(h.RefImage.Data);
Format40.DecodeInto(shpBytes, h.Data, (int)(h.FileOffset - shpBytesFileOffset));
break;
}
h.Data = CopyImageData(h.RefImage.Data);
Format40.DecodeInto(shpBytes, h.Data, (int)(h.FileOffset - shpBytesFileOffset));
break;
}
case Format.Format80:
{
var imageBytes = new byte[Size.Width * Size.Height];
Format80.DecodeInto(shpBytes, imageBytes, (int)(h.FileOffset - shpBytesFileOffset));
h.Data = imageBytes;
break;
}
{
var imageBytes = new byte[Size.Width * Size.Height];
Format80.DecodeInto(shpBytes, imageBytes, (int)(h.FileOffset - shpBytesFileOffset));
h.Data = imageBytes;
break;
}
default:
throw new InvalidDataException();

View File

@@ -288,12 +288,12 @@ namespace OpenRA.Mods.Common.Traits
{
switch (order.OrderString)
{
case "Move":
case "Enter":
case "ReturnToBase":
case "Stop":
return "Move";
default: return null;
case "Move":
case "Enter":
case "ReturnToBase":
case "Stop":
return "Move";
default: return null;
}
}
}

View File

@@ -135,7 +135,7 @@ namespace OpenRA.Mods.Common.Traits
public Activity MoveIntoWorld(Actor self, CPos cell, SubCell subCell = SubCell.Any) { return new Fly(self, Target.FromCell(self.World, cell)); }
public Activity VisualMove(Actor self, WPos fromPos, WPos toPos) { return Util.SequenceActivities(new CallFunc(() => SetVisualPosition(self, fromPos)), new Fly(self, Target.FromPos(toPos))); }
public Activity MoveToTarget(Actor self, Target target) { return new Fly(self, target, WRange.FromCells(3), WRange.FromCells(5)); }
public Activity MoveToTarget(Actor self, Target target) { return new Fly(self, target, WRange.FromCells(3), WRange.FromCells(5)); }
public Activity MoveIntoTarget(Actor self, Target target) { return new Land(target); }
}
}

View File

@@ -33,8 +33,11 @@ namespace OpenRA.Mods.Common.Traits
public override string[] TargetTypes
{
get { return (self.CenterPosition.Z > 0) ? info.TargetTypes
: info.GroundedTargetTypes; }
get
{
return (self.CenterPosition.Z > 0) ? info.TargetTypes
: info.GroundedTargetTypes;
}
}
}
}

View File

@@ -32,7 +32,7 @@ namespace OpenRA.Mods.Common.Traits
[Desc("Has to be defined here and in weapons.yaml.")]
public readonly string Weapon = null;
public readonly string Turret = "primary";
[Desc("Time (in frames) until the weapon can fire again.")]
[Desc("Time (in frames) until the weapon can fire again.")]
public readonly int FireDelay = 0;
[Desc("Muzzle position relative to turret or body. (forward, right, up) triples")]

View File

@@ -113,12 +113,12 @@ namespace OpenRA.Mods.Common.Traits
{
switch (target.Type)
{
case TargetType.Actor:
return new Order("Attack", self, queued) { TargetActor = target.Actor };
case TargetType.FrozenActor:
return new Order("Attack", self, queued) { ExtraData = target.FrozenActor.ID };
case TargetType.Terrain:
return new Order("Attack", self, queued) { TargetLocation = self.World.Map.CellContaining(target.CenterPosition) };
case TargetType.Actor:
return new Order("Attack", self, queued) { TargetActor = target.Actor };
case TargetType.FrozenActor:
return new Order("Attack", self, queued) { ExtraData = target.FrozenActor.ID };
case TargetType.Terrain:
return new Order("Attack", self, queued) { TargetLocation = self.World.Map.CellContaining(target.CenterPosition) };
}
}
@@ -255,13 +255,13 @@ namespace OpenRA.Mods.Common.Traits
{
switch (target.Type)
{
case TargetType.Actor:
case TargetType.FrozenActor:
return CanTargetActor(self, target, modifiers, ref cursor);
case TargetType.Terrain:
return CanTargetLocation(self, self.World.Map.CellContaining(target.CenterPosition), othersAtTarget, modifiers, ref cursor);
default:
return false;
case TargetType.Actor:
case TargetType.FrozenActor:
return CanTargetActor(self, target, modifiers, ref cursor);
case TargetType.Terrain:
return CanTargetLocation(self, self.World.Map.CellContaining(target.CenterPosition), othersAtTarget, modifiers, ref cursor);
default:
return false;
}
}

View File

@@ -84,10 +84,10 @@ namespace OpenRA.Mods.Common.Traits
readonly AttackCharge attack;
readonly Target target;
public ChargeAttack(AttackCharge attack, Target target)
{
public ChargeAttack(AttackCharge attack, Target target)
{
this.attack = attack;
this.target = target;
this.target = target;
}
public override Activity Tick(Actor self)
@@ -109,10 +109,10 @@ namespace OpenRA.Mods.Common.Traits
readonly AttackCharge attack;
readonly Target target;
public ChargeFire(AttackCharge attack, Target target)
{
public ChargeFire(AttackCharge attack, Target target)
{
this.attack = attack;
this.target = target;
this.target = target;
}
public override Activity Tick(Actor self)

View File

@@ -33,7 +33,7 @@ namespace OpenRA.Mods.Common.Traits
[Desc("Disable production when there are more than this many of this actor on the battlefield. Set to 0 to disable.")]
public readonly int BuildLimit = 0;
[Desc("What the unit should start doing. Warning: If this is not a harvester", "it will break if you use FindResources.")]
[Desc("What the unit should start doing. Warning: If this is not a harvester", "it will break if you use FindResources.")]
public readonly string InitialActivity = null;
// TODO: UI fluff; doesn't belong here

View File

@@ -35,12 +35,12 @@ namespace OpenRA.Mods.Common.Traits
public void Killed(Actor self, AttackInfo e)
{
if (!rs.DefaultAnimation.HasSequence("dead")) return;
if (rs.DefaultAnimation.GetSequence("dead").Length > 1)
rs.DefaultAnimation.Play("dead");
else
rs.DefaultAnimation.PlayRepeating("dead");
self.World.AddFrameEndTask(
w => w.Add(
new DelayedAction(info.LingerTime,

View File

@@ -40,10 +40,13 @@ namespace OpenRA.Mods.Common.Traits
// the one we're playing in.
return new DisposableAction(
() => { reservedFor = null; reservedForAircraft = null; },
() => Game.RunAfterTick(
() => { if (Game.IsCurrentWorld(self.World)) throw new InvalidOperationException(
"Attempted to finalize an undisposed DisposableAction. {0} ({1}) reserved {2} ({3})"
.F(forActor.Info.Name, forActor.ActorID, self.Info.Name, self.ActorID)); }));
() => Game.RunAfterTick(() =>
{
if (Game.IsCurrentWorld(self.World))
throw new InvalidOperationException(
"Attempted to finalize an undisposed DisposableAction. {0} ({1}) reserved {2} ({3})".F(
forActor.Info.Name, forActor.ActorID, self.Info.Name, self.ActorID));
}));
}
public static bool IsReserved(Actor a)

View File

@@ -117,7 +117,7 @@ namespace OpenRA.Mods.Common.Traits
lastPos = self.Location;
}
}
public bool IsVisible(Actor self, Player viewer)
{
if (!Cloaked || self.Owner.IsAlliedWith(viewer))

View File

@@ -44,7 +44,7 @@ namespace OpenRA.Mods.Common.Traits
{
var info = self.Info.Traits.Get<GivesBountyInfo>();
if (e.Attacker == null || e.Attacker.Destroyed) return;
if (e.Attacker == null || e.Attacker.Destroyed) return;
if (!info.Stances.Contains(e.Attacker.Owner.Stances[self.Owner])) return;

View File

@@ -51,7 +51,7 @@ namespace OpenRA.Mods.Common.Traits
{
if (available == wasAvailable)
return;
if (available)
foreach (var u in info.Upgrades)
manager.GrantUpgrade(self, u, this);

View File

@@ -12,7 +12,7 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[Desc("This actor can be targeted by the Hunt activity.")]
public class HuntableInfo : TraitInfo<Huntable> { }
public class Huntable { }
[Desc("This actor can be targeted by the Hunt activity.")]
public class HuntableInfo : TraitInfo<Huntable> { }
public class Huntable { }
}

View File

@@ -12,8 +12,8 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[Desc("Allows automatic targeting of disguised actors.")]
class IgnoresDisguiseInfo : TraitInfo<IgnoresDisguise> { }
[Desc("Allows automatic targeting of disguised actors.")]
class IgnoresDisguiseInfo : TraitInfo<IgnoresDisguise> { }
class IgnoresDisguise { }
class IgnoresDisguise { }
}

View File

@@ -184,7 +184,7 @@ namespace OpenRA.Mods.Common.Traits
// Neutral/enemy units are blockers. Allied units that are moving are not blockers.
if (canIgnoreMovingAllies && self.Owner.Stances[a.Owner] == Stance.Ally && IsMovingInMyDirection(self, a)) continue;
// Non-sharable unit can enter a cell with shareable units only if it can crush all of them.
if (needsCellExclusively)
return false;
@@ -218,7 +218,7 @@ namespace OpenRA.Mods.Common.Traits
// Neutral/enemy units are blockers. Allied units that are moving are not blockers.
if (canIgnoreMovingAllies && self.Owner.Stances[a.Owner] == Stance.Ally && IsMovingInMyDirection(self, a))
return false;
// Non-sharable unit can enter a cell with shareable units only if it can crush all of them.
if (needsCellExclusively)
return true;
@@ -252,7 +252,7 @@ namespace OpenRA.Mods.Common.Traits
const int AverageTicksBeforePathing = 5;
const int SpreadTicksBeforePathing = 5;
internal int TicksBeforePathing = 0;
readonly Actor self;
public readonly MobileInfo Info;
public bool IsMoving { get; set; }

View File

@@ -36,13 +36,13 @@ namespace OpenRA.Mods.Common.Traits
public class MissionObjectivesInfo : ITraitInfo
{
[Desc("Set this to true if multiple cooperative players have a distinct set of " +
"objectives that each of them has to complete to win the game. This is mainly " +
"useful for multiplayer coop missions. Do not use this for skirmish team games.")]
"objectives that each of them has to complete to win the game. This is mainly " +
"useful for multiplayer coop missions. Do not use this for skirmish team games.")]
public readonly bool Cooperative = false;
[Desc("If set to true, this setting causes the game to end immediately once the first " +
"player (or team of cooperative players) fails or completes his objectives. If " +
"set to false, players that fail their objectives will stick around and become observers.")]
"player (or team of cooperative players) fails or completes his objectives. If " +
"set to false, players that fail their objectives will stick around and become observers.")]
public readonly bool EarlyGameOver = false;
[Desc("Delay between the game over condition being met, and the game actually ending, in milliseconds.")]
@@ -245,8 +245,8 @@ namespace OpenRA.Mods.Common.Traits
}
[Desc("Provides game mode progress information for players.",
"Goes on WorldActor - observers don't have a player it can live on.",
"Current options for PanelName are 'SKIRMISH_STATS' and 'MISSION_OBJECTIVES'.")]
"Goes on WorldActor - observers don't have a player it can live on.",
"Current options for PanelName are 'SKIRMISH_STATS' and 'MISSION_OBJECTIVES'.")]
public class ObjectivesPanelInfo : ITraitInfo
{
public string PanelName = null;

View File

@@ -28,7 +28,7 @@ namespace OpenRA.Mods.Common.Traits
public double MapControl;
public int OrderCount;
public int EarnedThisMinute
public int EarnedThisMinute
{
get
{

View File

@@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common.Traits
{
this.info = info;
var race = init.Contains<RaceInit>() ? init.Get<RaceInit, string>() : init.Self.Owner.Country.Race;
var race = init.Contains<RaceInit>() ? init.Get<RaceInit, string>() : init.Self.Owner.Country.Race;
Update(init.Self.Owner, race);
}

View File

@@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Traits
PlayerPower = self.Owner.PlayerActor.Trait<PowerManager>();
powerModifiers = Exts.Lazy(() => self.TraitsImplementing<IPowerModifier>().ToArray());
}
protected override void UpgradeEnabled(Actor self) { PlayerPower.UpdateActor(self); }
protected override void UpgradeDisabled(Actor self) { PlayerPower.UpdateActor(self); }
public void AddedToWorld(Actor self) { PlayerPower.UpdateActor(self); }

View File

@@ -25,7 +25,7 @@ namespace OpenRA.Mods.Common.Traits
{
var t = init.Actor.Traits.WithInterface<TurretedInfo>()
.FirstOrDefault();
// Show the correct turret facing
var anim = new Animation(init.World, image, () => t.InitialFacing);
anim.PlayRepeating("idle");

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Mods.Common.Traits
[Desc("Custom palette name")]
public readonly string Palette = "effect";
public object Create(ActorInitializer init) { return new WithBuildingExplosion(this); }
}

View File

@@ -31,7 +31,7 @@ namespace OpenRA.Mods.Common.Traits
this.info = info;
renderSimple = self.Trait<RenderSimple>();
}
public void BuildingPlaced(Actor self)
{
renderSimple.PlayCustomAnim(self, info.Sequence);

View File

@@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Traits
var building = self.Trait<Building>();
if (!building.SkipMakeAnimation)
{
renderBuilding.PlayCustomAnimThen(self, info.Sequence, () =>
renderBuilding.PlayCustomAnimThen(self, info.Sequence, () =>
{
building.NotifyBuildingComplete(self);
});

View File

@@ -38,9 +38,10 @@ namespace OpenRA.Mods.Common.Traits
anim = new Animation(self.World, rs.GetImage(self));
anim.PlayFetchIndex(info.Sequence,
() => playerResources.ResourceCapacity != 0
? ((10 * anim.CurrentSequence.Length - 1) * playerResources.Resources) / (10 * playerResources.ResourceCapacity)
: 0);
() =>
playerResources.ResourceCapacity != 0 ?
((10 * anim.CurrentSequence.Length - 1) * playerResources.Resources) / (10 * playerResources.ResourceCapacity) :
0);
rs.Add("resources_{0}".F(info.Sequence), new AnimationWithOffset(
anim, null, () => !buildComplete, 1024));

View File

@@ -45,7 +45,7 @@ namespace OpenRA.Mods.Common.Traits
if (health.HP >= Info.HealIfBelow * health.MaxHP)
return;
if (damageTicks > 0)
{
--damageTicks;

View File

@@ -36,7 +36,7 @@ namespace OpenRA.Mods.Common.Traits
public void AppliedDamage(Actor self, Actor damaged, AttackInfo e)
{
// Don't notify suicides
if (e.DamageState == DamageState.Dead && damaged != e.Attacker)
if (e.DamageState == DamageState.Dead && damaged != e.Attacker)
{
if (self.World.WorldTick - lastAnnounce > info.Interval * 25)
Sound.PlayVoice("Kill", self, self.Owner.Country.Race);

View File

@@ -18,7 +18,7 @@ namespace OpenRA.Mods.Common.Traits
{
[Desc("Death notification voice.")]
public readonly string DeathSound = "Die";
[Desc("Multiply volume with this factor.")]
public readonly float VolumeMultiplier = 1f;

View File

@@ -99,8 +99,8 @@ namespace OpenRA.Mods.Common.Traits
// Select only the tiles that are within range from the requested SubCell
// This assumes that the SubCell does not change during the path traversal
var tilesInRange = world.Map.FindTilesInCircle(targetCell, range.Range / 1024 + 1)
.Where(t => (world.Map.CenterOfCell(t) - target).LengthSquared <= rangeSquared
&& mi.CanEnterCell(self.World, self, t));
.Where(t => (world.Map.CenterOfCell(t) - target).LengthSquared <= rangeSquared &&
mi.CanEnterCell(self.World, self, t));
// See if there is any cell within range that does not involve a cross-domain request
// Really, we only need to check the circle perimeter, but it's not clear that would be a performance win

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Mods.Common.Traits
public readonly string FogPalette = "fog";
[Desc("Bitfield of shroud directions for each frame. Lower four bits are",
"corners clockwise from TL; upper four are edges clockwise from top")]
"corners clockwise from TL; upper four are edges clockwise from top")]
public readonly int[] Index = new[] { 12, 9, 8, 3, 1, 6, 4, 2, 13, 11, 7, 14 };
[Desc("Use the upper four bits when calculating frame")]

View File

@@ -1,12 +1,12 @@
#region Copyright & License Information
/*
/*
* Copyright 2007-2014 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 COPYING.
*/
#endregion
#endregion
using System;
using System.Collections.Generic;

View File

@@ -284,7 +284,7 @@ namespace OpenRA.Mods.Common.UtilityCommands
if (o != 255 && overlayResourceMapping.ContainsKey(redAlertOverlayNames[o]))
res = overlayResourceMapping[redAlertOverlayNames[o]];
var cell = new CPos(i, j);
map.MapResources.Value[cell] = new ResourceTile(res.First, res.Second);

View File

@@ -351,7 +351,7 @@ namespace OpenRA.Mods.Common.UtilityCommands
var powerFields = new List<MiniYamlNode> { new MiniYamlNode("Amount", power.Value) };
actorTraits.Add(new MiniYamlNode("Power", new MiniYaml("", powerFields)));
if (FieldLoader.GetValue<int>("Power", power.Value.Value) > 0)
actorTraits.Add(new MiniYamlNode("ScaleWithHealth", ""));
}
@@ -528,7 +528,7 @@ namespace OpenRA.Mods.Common.UtilityCommands
if (engineVersion < 20140913)
{
var spawnsCorpseRemoval = node.Value.Nodes.FirstOrDefault(n => n.Key == "SpawnsCorpse");
if (depth == 0 && node.Value.Nodes.Any(n => n.Key.StartsWith("RenderInfantry")) && spawnsCorpseRemoval == null)
node.Value.Nodes.Add(new MiniYamlNode("WithDeathAnimation", new MiniYaml("")));
@@ -732,13 +732,13 @@ namespace OpenRA.Mods.Common.UtilityCommands
ConvertAngle(ref node.Value.Value);
break;
case "Speed":
{
if (parent.Value.Value == "Missile")
ConvertPxToRange(ref node.Value.Value, 1, 5);
if (parent.Value.Value == "Bullet")
ConvertPxToRange(ref node.Value.Value, 2, 5);
break;
}
{
if (parent.Value.Value == "Missile")
ConvertPxToRange(ref node.Value.Value, 1, 5);
if (parent.Value.Value == "Bullet")
ConvertPxToRange(ref node.Value.Value, 2, 5);
break;
}
default:
break;

View File

@@ -171,25 +171,25 @@ namespace OpenRA.Mods.Common.Widgets
switch (mi.Event)
{
case MouseInputEvent.Up:
isMoving = false;
YieldMouseFocus(mi);
break;
case MouseInputEvent.Up:
isMoving = false;
YieldMouseFocus(mi);
break;
case MouseInputEvent.Down:
isMoving = true;
SetValueFromPx(mi.Location - RenderOrigin);
OnChange();
break;
case MouseInputEvent.Move:
if (isMoving)
{
case MouseInputEvent.Down:
isMoving = true;
SetValueFromPx(mi.Location - RenderOrigin);
OnChange();
}
break;
break;
case MouseInputEvent.Move:
if (isMoving)
{
SetValueFromPx(mi.Location - RenderOrigin);
OnChange();
}
break;
}
return true;

View File

@@ -86,7 +86,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
}
var playerWidget = panel.GetOrNull<VqaPlayerWidget>("PLAYER");
if (playerWidget != null)
if (playerWidget != null)
playerWidget.IsVisible = () => isVideoLoaded;
var paletteDropDown = panel.GetOrNull<DropDownButtonWidget>("PALETTE_SELECTOR");
@@ -118,22 +118,22 @@ namespace OpenRA.Mods.Common.Widgets.Logic
frameSlider = panel.Get<SliderWidget>("FRAME_SLIDER");
if (frameSlider != null)
{
frameSlider.OnChange += x =>
frameSlider.OnChange += x =>
{
if (!isVideoLoaded)
currentFrame = (int)Math.Round(x);
if (!isVideoLoaded)
currentFrame = (int)Math.Round(x);
};
frameSlider.GetValue = () => isVideoLoaded ? player.Video.CurrentFrame : currentFrame;
frameSlider.IsDisabled = () => isVideoLoaded;
frameSlider.IsDisabled = () => isVideoLoaded;
}
var frameText = panel.GetOrNull<LabelWidget>("FRAME_COUNT");
if (frameText != null)
{
frameText.GetText = () =>
isVideoLoaded ?
"{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) :
frameText.GetText = () =>
isVideoLoaded ?
"{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) :
"{0} / {1}".F(currentFrame + 1, currentSprites.Length);
}
@@ -186,7 +186,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{
nextButton.OnClick = () =>
{
if (!isVideoLoaded)
if (!isVideoLoaded)
nextButton.OnClick = SelectNextFrame;
};
@@ -211,12 +211,12 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var closeButton = panel.GetOrNull<ButtonWidget>("CLOSE_BUTTON");
if (closeButton != null)
closeButton.OnClick = () =>
closeButton.OnClick = () =>
{
if (isVideoLoaded)
player.Stop();
Ui.CloseWindow();
onExit();
onExit();
};
}
@@ -290,7 +290,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
player = null;
isVideoLoaded = false;
}
if (string.IsNullOrEmpty(filename))
return false;
@@ -325,8 +325,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
Func<IFolder, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) =>
{
var item = ScrollItemWidget.Setup(itemTemplate,
() => assetSource == source,
() => { assetSource = source; PopulateAssetList(); });
() => assetSource == source,
() => { assetSource = source; PopulateAssetList(); });
item.Get<LabelWidget>("LABEL").GetText = () => source != null ? Platform.UnresolvePath(source.Name) : "All Packages";
return item;
};
@@ -359,7 +359,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
}
}
}
bool ShowPaletteDropdown(DropDownButtonWidget dropdown, World world)
{
Func<PaletteFromFile, ScrollItemWidget, ScrollItemWidget> setupItem = (palette, itemTemplate) =>

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
public DisconnectWatcherLogic(Widget widget, OrderManager orderManager)
{
var disconnected = false;
widget.Get<LogicTickerWidget>("DISCONNECT_WATCHER").OnTick = () =>
widget.Get<LogicTickerWidget>("DISCONNECT_WATCHER").OnTick = () =>
{
if (disconnected || orderManager.Connection.ConnectionState != ConnectionState.NotConnected)
return;

View File

@@ -126,7 +126,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var textBox = key.Get<HotkeyEntryWidget>("HOTKEY");
textBox.Key = (Hotkey)field.GetValue(ks);
textBox.OnLoseFocus = () => field.SetValue(ks, textBox.Key);
textBox.OnLoseFocus = () => field.SetValue(ks, textBox.Key);
parent.AddChild(key);
}
@@ -536,8 +536,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
Func<string, ScrollItemWidget, ScrollItemWidget> setupItem = (o, itemTemplate) =>
{
var item = ScrollItemWidget.Setup(itemTemplate,
() => s.MouseScroll == options[o],
() => s.MouseScroll = options[o]);
() => s.MouseScroll == options[o],
() => s.MouseScroll = options[o]);
item.Get<LabelWidget>("LABEL").GetText = () => o;
return item;
};

View File

@@ -274,7 +274,7 @@ namespace OpenRA.Mods.Common.Widgets
var stride = radarSheet.Size.Width;
var dx = actorSprite.Bounds.Left - world.Map.Bounds.Left;
var dy = actorSprite.Bounds.Top - world.Map.Bounds.Top;
Array.Clear(radarData, 4 * (actorSprite.Bounds.Top * stride + actorSprite.Bounds.Left), 4 * actorSprite.Bounds.Height * stride);
unsafe

View File

@@ -96,8 +96,9 @@ namespace OpenRA.Mods.Common.Widgets
}
}
else
Game.Renderer.LineRenderer.FillRect(new Rectangle(b.X, (int)float2.Lerp(b.Bottom, b.Top, providedFrac),
b.Width, (int)(providedFrac * b.Height)), color);
Game.Renderer.LineRenderer.FillRect(new Rectangle(
b.X, (int)float2.Lerp(b.Bottom, b.Top, providedFrac),
b.Width, (int)(providedFrac * b.Height)), color);
var x = (b.Left + b.Right - indicator.Size.X) / 2;
var y = float2.Lerp(b.Bottom, b.Top, usedFrac) - indicator.Size.Y / 2;

View File

@@ -96,7 +96,7 @@ namespace OpenRA.Mods.D2k.Activities
{
state = State.MoveToCarryable;
return this;
}
}
else
{
// We got cancelled
@@ -177,7 +177,7 @@ namespace OpenRA.Mods.D2k.Activities
c.Dropped();
state = State.Done;
return Util.SequenceActivities(new Wait(10), this);
return Util.SequenceActivities(new Wait(10), this);
case State.Done:

View File

@@ -25,7 +25,7 @@ namespace OpenRA.Mods.D2k.Traits
public readonly long Offset = 0;
public readonly bool AllowModifiers = true;
public readonly bool InvertColor = false;
public object Create(ActorInitializer init) { return new PaletteFromR8(this); }
}

View File

@@ -94,7 +94,7 @@ namespace OpenRA.Mods.D2k.Traits
}));
wormsPresent++;
return spawnPoint.CenterPosition;
}

Some files were not shown because too many files have changed in this diff Show More