Replace F extension with string interpolation

This commit is contained in:
teinarss
2021-04-24 17:46:24 +02:00
committed by reaperrr
parent 1385aca783
commit 10676be377
300 changed files with 752 additions and 799 deletions

View File

@@ -95,7 +95,7 @@ namespace OpenRA.Activities
public Activity TickOuter(Actor self) public Activity TickOuter(Actor self)
{ {
if (State == ActivityState.Done) if (State == ActivityState.Done)
throw new InvalidOperationException("Actor {0} attempted to tick activity {1} after it had already completed.".F(self, GetType())); throw new InvalidOperationException($"Actor {self} attempted to tick activity {GetType()} after it had already completed.");
if (State == ActivityState.Queued) if (State == ActivityState.Queued)
{ {
@@ -105,7 +105,7 @@ namespace OpenRA.Activities
} }
if (!firstRunCompleted) if (!firstRunCompleted)
throw new InvalidOperationException("Actor {0} attempted to tick activity {1} before running its OnFirstRun method.".F(self, GetType())); throw new InvalidOperationException($"Actor {self} attempted to tick activity {GetType()} before running its OnFirstRun method.");
// Only run the parent tick when the child is done. // Only run the parent tick when the child is done.
// We must always let the child finish on its own before continuing. // We must always let the child finish on its own before continuing.

View File

@@ -125,7 +125,7 @@ namespace OpenRA
.FirstOrDefault(i => i.Count() > 1); .FirstOrDefault(i => i.Count() > 1);
if (duplicateInit != null) if (duplicateInit != null)
throw new InvalidDataException("Duplicate initializer '{0}'".F(duplicateInit.Key.Name)); throw new InvalidDataException($"Duplicate initializer '{duplicateInit.Key.Name}'");
var init = new ActorInitializer(this, initDict); var init = new ActorInitializer(this, initDict);
@@ -250,7 +250,7 @@ namespace OpenRA
continue; continue;
if (creationActivity != null) if (creationActivity != null)
throw new InvalidOperationException("More than one enabled ICreationActivity trait: {0} and {1}".F(creationActivity.GetType().Name, ica.GetType().Name)); throw new InvalidOperationException($"More than one enabled ICreationActivity trait: {creationActivity.GetType().Name} and {ica.GetType().Name}");
var activity = ica.GetCreationActivity(); var activity = ica.GetCreationActivity();
if (activity == null) if (activity == null)
@@ -592,7 +592,7 @@ namespace OpenRA
public int RevokeCondition(int token) public int RevokeCondition(int token)
{ {
if (!conditionTokens.TryGetValue(token, out var condition)) if (!conditionTokens.TryGetValue(token, out var condition))
throw new InvalidOperationException("Attempting to revoke condition with invalid token {0} for {1}.".F(token, this)); throw new InvalidOperationException($"Attempting to revoke condition with invalid token {token} for {this}.");
conditionTokens.Remove(token); conditionTokens.Remove(token);
UpdateConditionState(condition, token, true); UpdateConditionState(condition, token, true);
@@ -632,7 +632,7 @@ namespace OpenRA
public LuaValue ToString(LuaRuntime runtime) public LuaValue ToString(LuaRuntime runtime)
{ {
return "Actor ({0})".F(this); return $"Actor ({this})";
} }
public bool HasScriptProperty(string name) public bool HasScriptProperty(string name)

View File

@@ -90,7 +90,7 @@ namespace OpenRA
public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out CPos a) || !right.TryGetClrValue(out CVec b)) if (!left.TryGetClrValue(out CPos a) || !right.TryGetClrValue(out CVec b))
throw new LuaException("Attempted to call CPos.Add(CPos, CVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call CPos.Add(CPos, CVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
return new LuaCustomClrObject(a + b); return new LuaCustomClrObject(a + b);
} }
@@ -99,7 +99,7 @@ namespace OpenRA
{ {
var rightType = right.WrappedClrType(); var rightType = right.WrappedClrType();
if (!left.TryGetClrValue(out CPos a)) if (!left.TryGetClrValue(out CPos a))
throw new LuaException("Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); throw new LuaException($"Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})");
if (rightType == typeof(CPos)) if (rightType == typeof(CPos))
{ {
@@ -112,7 +112,7 @@ namespace OpenRA
return new LuaCustomClrObject(a - b); return new LuaCustomClrObject(a - b);
} }
throw new LuaException("Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); throw new LuaException($"Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})");
} }
public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right)
@@ -132,7 +132,7 @@ namespace OpenRA
case "X": return X; case "X": return X;
case "Y": return Y; case "Y": return Y;
case "Layer": return Layer; case "Layer": return Layer;
default: throw new LuaException("CPos does not define a member '{0}'".F(key)); default: throw new LuaException($"CPos does not define a member '{key}'");
} }
} }

View File

@@ -76,7 +76,7 @@ namespace OpenRA
public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out CVec a) || !right.TryGetClrValue(out CVec b)) if (!left.TryGetClrValue(out CVec a) || !right.TryGetClrValue(out CVec b))
throw new LuaException("Attempted to call CVec.Add(CVec, CVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call CVec.Add(CVec, CVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
return new LuaCustomClrObject(a + b); return new LuaCustomClrObject(a + b);
} }
@@ -84,7 +84,7 @@ namespace OpenRA
public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out CVec a) || !right.TryGetClrValue(out CVec b)) if (!left.TryGetClrValue(out CVec a) || !right.TryGetClrValue(out CVec b))
throw new LuaException("Attempted to call CVec.Subtract(CVec, CVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call CVec.Subtract(CVec, CVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
return new LuaCustomClrObject(a - b); return new LuaCustomClrObject(a - b);
} }
@@ -110,7 +110,7 @@ namespace OpenRA
{ {
case "X": return X; case "X": return X;
case "Y": return Y; case "Y": return Y;
default: throw new LuaException("CVec does not define a member '{0}'".F(key)); default: throw new LuaException($"CVec does not define a member '{key}'");
} }
} }

View File

@@ -278,7 +278,7 @@ namespace OpenRA
public static int ISqrt(int number, ISqrtRoundMode round = ISqrtRoundMode.Floor) public static int ISqrt(int number, ISqrtRoundMode round = ISqrtRoundMode.Floor)
{ {
if (number < 0) if (number < 0)
throw new InvalidOperationException("Attempted to calculate the square root of a negative integer: {0}".F(number)); throw new InvalidOperationException($"Attempted to calculate the square root of a negative integer: {number}");
return (int)ISqrt((uint)number, round); return (int)ISqrt((uint)number, round);
} }
@@ -319,7 +319,7 @@ namespace OpenRA
public static long ISqrt(long number, ISqrtRoundMode round = ISqrtRoundMode.Floor) public static long ISqrt(long number, ISqrtRoundMode round = ISqrtRoundMode.Floor)
{ {
if (number < 0) if (number < 0)
throw new InvalidOperationException("Attempted to calculate the square root of a negative integer: {0}".F(number)); throw new InvalidOperationException($"Attempted to calculate the square root of a negative integer: {number}");
return (long)ISqrt((ulong)number, round); return (long)ISqrt((ulong)number, round);
} }
@@ -429,8 +429,8 @@ namespace OpenRA
// If any duplicates were found, throw a descriptive error // If any duplicates were found, throw a descriptive error
if (dupKeys.Count > 0) if (dupKeys.Count > 0)
{ {
var badKeysFormatted = string.Join(", ", dupKeys.Select(p => "{0}: [{1}]".F(logKey(p.Key), string.Join(",", p.Value)))); var badKeysFormatted = string.Join(", ", dupKeys.Select(p => $"{logKey(p.Key)}: [{string.Join(",", p.Value)}]"));
var msg = "{0}, duplicate values found for the following keys: {1}".F(debugName, badKeysFormatted); var msg = $"{debugName}, duplicate values found for the following keys: {badKeysFormatted}";
throw new ArgumentException(msg); throw new ArgumentException(msg);
} }

View File

@@ -58,12 +58,12 @@ namespace OpenRA
public static Func<string, Type, string, object> InvalidValueAction = (s, t, f) => public static Func<string, Type, string, object> InvalidValueAction = (s, t, f) =>
{ {
throw new YamlException("FieldLoader: Cannot parse `{0}` into `{1}.{2}` ".F(s, f, t)); throw new YamlException($"FieldLoader: Cannot parse `{s}` into `{f}.{t}` ");
}; };
public static Action<string, Type> UnknownFieldAction = (s, f) => public static Action<string, Type> UnknownFieldAction = (s, f) =>
{ {
throw new NotImplementedException("FieldLoader: Missing field `{0}` on `{1}`".F(s, f.Name)); throw new NotImplementedException($"FieldLoader: Missing field `{s}` on `{f.Name}`");
}; };
static readonly ConcurrentCache<Type, FieldLoadInfo[]> TypeLoadInfo = static readonly ConcurrentCache<Type, FieldLoadInfo[]> TypeLoadInfo =
@@ -660,7 +660,7 @@ namespace OpenRA
} }
} }
UnknownFieldAction("[Type] {0}".F(value), fieldType); UnknownFieldAction($"[Type] {value}", fieldType);
return null; return null;
} }
@@ -771,7 +771,7 @@ namespace OpenRA
{ {
var method = type.GetMethod(Loader, Flags); var method = type.GetMethod(Loader, Flags);
if (method == null) if (method == null)
throw new InvalidOperationException("{0} does not specify a loader function '{1}'".F(type.Name, Loader)); throw new InvalidOperationException($"{type.Name} does not specify a loader function '{Loader}'");
return (Func<MiniYaml, object>)Delegate.CreateDelegate(typeof(Func<MiniYaml, object>), method); return (Func<MiniYaml, object>)Delegate.CreateDelegate(typeof(Func<MiniYaml, object>), method);
} }

View File

@@ -94,7 +94,7 @@ namespace OpenRA
var formattedKey = FormatValue(key); var formattedKey = FormatValue(key);
var formattedValue = FormatValue(value); var formattedValue = FormatValue(value);
result += "{0}: {1}{2}".F(formattedKey, formattedValue, Environment.NewLine); result += $"{formattedKey}: {formattedValue}{Environment.NewLine}";
} }
return result; return result;

View File

@@ -213,7 +213,7 @@ namespace OpenRA.FileFormats
} }
default: default:
throw new InvalidDataException("Unhandled SpriteFrameType {0}".F(type)); throw new InvalidDataException($"Unhandled SpriteFrameType {type}");
} }
if (embeddedData != null) if (embeddedData != null)

View File

@@ -44,7 +44,7 @@ namespace OpenRA.FileFormats
// Read version // Read version
var version = fs.ReadInt32(); var version = fs.ReadInt32();
if (version != MetaVersion) if (version != MetaVersion)
throw new NotSupportedException("Metadata version {0} is not supported".F(version)); throw new NotSupportedException($"Metadata version {version} is not supported");
// Read game info (max 100K limit as a safeguard against corrupted files) // Read game info (max 100K limit as a safeguard against corrupted files)
var data = fs.ReadString(Encoding.UTF8, 1024 * 100); var data = fs.ReadString(Encoding.UTF8, 1024 * 100);

View File

@@ -95,7 +95,7 @@ namespace OpenRA.FileSystem
name = name.Substring(1); name = name.Substring(1);
if (!installedMods.TryGetValue(name, out var mod)) if (!installedMods.TryGetValue(name, out var mod))
throw new InvalidOperationException("Could not load mod '{0}'. Available mods: {1}".F(name, installedMods.Keys.JoinWith(", "))); throw new InvalidOperationException($"Could not load mod '{name}'. Available mods: {installedMods.Keys.JoinWith(", ")}");
package = mod.Package; package = mod.Package;
modPackages.Add(package); modPackages.Add(package);
@@ -104,7 +104,7 @@ namespace OpenRA.FileSystem
{ {
package = OpenPackage(name); package = OpenPackage(name);
if (package == null) if (package == null)
throw new InvalidOperationException("Could not open package '{0}', file not found or its format is not supported.".F(name)); throw new InvalidOperationException($"Could not open package '{name}', file not found or its format is not supported.");
} }
Mount(package, explicitName); Mount(package, explicitName);
@@ -203,7 +203,7 @@ namespace OpenRA.FileSystem
public Stream Open(string filename) public Stream Open(string filename)
{ {
if (!TryOpen(filename, out var s)) if (!TryOpen(filename, out var s))
throw new FileNotFoundException("File not found: {0}".F(filename), filename); throw new FileNotFoundException($"File not found: {filename}", filename);
return s; return s;
} }

View File

@@ -216,7 +216,7 @@ namespace OpenRA
var orders = new[] var orders = new[]
{ {
Order.Command("sync_lobby {0}".F(lobbyInfo.Serialize())), Order.Command($"sync_lobby {lobbyInfo.Serialize()}"),
Order.Command("startgame") Order.Command("startgame")
}; };
@@ -439,7 +439,7 @@ namespace OpenRA
throw new InvalidOperationException("Game.Mod argument missing."); throw new InvalidOperationException("Game.Mod argument missing.");
if (!Mods.ContainsKey(mod)) if (!Mods.ContainsKey(mod))
throw new InvalidOperationException("Unknown or invalid mod '{0}'.".F(mod)); throw new InvalidOperationException($"Unknown or invalid mod '{mod}'.");
Console.WriteLine("Loading mod: {0}", mod); Console.WriteLine("Loading mod: {0}", mod);
@@ -988,8 +988,8 @@ namespace OpenRA
{ {
var orders = new List<Order> var orders = new List<Order>
{ {
Order.Command("option gamespeed {0}".F("default")), Order.Command("option gamespeed default"),
Order.Command("state {0}".F(Session.ClientState.Ready)) Order.Command($"state {Session.ClientState.Ready}")
}; };
var path = Platform.ResolvePath(launchMap); var path = Platform.ResolvePath(launchMap);
@@ -997,7 +997,7 @@ namespace OpenRA
ModData.MapCache.SingleOrDefault(m => m.Package.Name == path); ModData.MapCache.SingleOrDefault(m => m.Package.Name == path);
if (map == null) if (map == null)
throw new InvalidOperationException("Could not find map '{0}'.".F(launchMap)); throw new InvalidOperationException($"Could not find map '{launchMap}'.");
CreateAndStartLocalServer(map.Uid, orders); CreateAndStartLocalServer(map.Uid, orders);
} }

View File

@@ -76,7 +76,7 @@ namespace OpenRA
} }
catch (YamlException) catch (YamlException)
{ {
Log.Write("debug", "GameInformation deserialized invalid MiniYaml:\n{0}".F(data)); Log.Write("debug", $"GameInformation deserialized invalid MiniYaml:\n{data}");
throw; throw;
} }
} }
@@ -89,7 +89,7 @@ namespace OpenRA
}; };
for (var i = 0; i < Players.Count; i++) for (var i = 0; i < Players.Count; i++)
nodes.Add(new MiniYamlNode("Player@{0}".F(i), FieldSaver.Save(Players[i]))); nodes.Add(new MiniYamlNode($"Player@{i}", FieldSaver.Save(Players[i])));
return nodes.WriteToString(); return nodes.WriteToString();
} }

View File

@@ -61,7 +61,7 @@ namespace OpenRA
} }
catch (YamlException e) catch (YamlException e)
{ {
throw new YamlException("Actor type {0}: {1}".F(name, e.Message)); throw new YamlException($"Actor type {name}: {e.Message}");
} }
} }
@@ -76,8 +76,7 @@ namespace OpenRA
static TraitInfo LoadTraitInfo(ObjectCreator creator, string traitName, MiniYaml my) static TraitInfo LoadTraitInfo(ObjectCreator creator, string traitName, MiniYaml my)
{ {
if (!string.IsNullOrEmpty(my.Value)) if (!string.IsNullOrEmpty(my.Value))
throw new YamlException("Junk value `{0}` on trait node {1}" throw new YamlException($"Junk value `{my.Value}` on trait node {traitName}");
.F(my.Value, traitName));
// HACK: The linter does not want to crash when a trait doesn't exist but only print an error instead // HACK: The linter does not want to crash when a trait doesn't exist but only print an error instead
// ObjectCreator will only return null to signal us to abort here if the linter is running // ObjectCreator will only return null to signal us to abort here if the linter is running

View File

@@ -60,7 +60,7 @@ namespace OpenRA
} }
catch (YamlException e) catch (YamlException e)
{ {
throw new YamlException("Actor type {0}: {1}".F(a.Name, e.Message)); throw new YamlException($"Actor type {a.Name}: {e.Message}");
} }
} }
} }
@@ -75,7 +75,7 @@ namespace OpenRA
} }
catch (YamlException e) catch (YamlException e)
{ {
throw new YamlException("Projectile type {0}: {1}".F(weapon.Key, e.Message)); throw new YamlException($"Projectile type {weapon.Key}: {e.Message}");
} }
} }
@@ -89,7 +89,7 @@ namespace OpenRA
} }
catch (YamlException e) catch (YamlException e)
{ {
throw new YamlException("Weapon type {0}: {1}".F(weapon.Key, e.Message)); throw new YamlException($"Weapon type {weapon.Key}: {e.Message}");
} }
} }
} }

View File

@@ -50,7 +50,7 @@ namespace OpenRA
catch (FieldLoader.MissingFieldsException e) catch (FieldLoader.MissingFieldsException e)
{ {
var label = e.Missing.Length > 1 ? "Required properties missing" : "Required property missing"; var label = e.Missing.Length > 1 ? "Required properties missing" : "Required property missing";
throw new YamlException("Error parsing GameSpeed {0}: {1}: {2}".F(node.Key, label, e.Missing.JoinWith(", "))); throw new YamlException($"Error parsing GameSpeed {node.Key}: {label}: {e.Missing.JoinWith(", ")}");
} }
} }

View File

@@ -231,7 +231,7 @@ namespace OpenRA.Graphics
// All palettes must be explicitly referenced, even if they are embedded in the sprite. // All palettes must be explicitly referenced, even if they are embedded in the sprite.
if (palette == null) if (palette == null)
throw new InvalidOperationException("Cursor sequence `{0}` attempted to load an indexed sprite but does not define Palette".F(name)); throw new InvalidOperationException($"Cursor sequence `{name}` attempted to load an indexed sprite but does not define Palette");
var width = frame.Size.Width; var width = frame.Size.Width;
var height = frame.Size.Height; var height = frame.Size.Height;

View File

@@ -59,7 +59,7 @@ namespace OpenRA.Graphics
try { return Cursors[cursor]; } try { return Cursors[cursor]; }
catch (KeyNotFoundException) catch (KeyNotFoundException)
{ {
throw new InvalidOperationException("Cursor does not have a sequence `{0}`".F(cursor)); throw new InvalidOperationException($"Cursor does not have a sequence `{cursor}`");
} }
} }
} }

View File

@@ -40,20 +40,20 @@ namespace OpenRA.Graphics
return mutable.AsReadOnly(); return mutable.AsReadOnly();
if (palettes.TryGetValue(name, out var immutable)) if (palettes.TryGetValue(name, out var immutable))
return immutable; return immutable;
throw new InvalidOperationException("Palette `{0}` does not exist".F(name)); throw new InvalidOperationException($"Palette `{name}` does not exist");
} }
public int GetPaletteIndex(string name) public int GetPaletteIndex(string name)
{ {
if (!indices.TryGetValue(name, out var ret)) if (!indices.TryGetValue(name, out var ret))
throw new InvalidOperationException("Palette `{0}` does not exist".F(name)); throw new InvalidOperationException($"Palette `{name}` does not exist");
return ret; return ret;
} }
public void AddPalette(string name, ImmutablePalette p, bool allowModifiers) public void AddPalette(string name, ImmutablePalette p, bool allowModifiers)
{ {
if (palettes.ContainsKey(name)) if (palettes.ContainsKey(name))
throw new InvalidOperationException("Palette {0} has already been defined".F(name)); throw new InvalidOperationException($"Palette {name} has already been defined");
int index = palettes.Count; int index = palettes.Count;
indices.Add(name, index); indices.Add(name, index);
@@ -78,7 +78,7 @@ namespace OpenRA.Graphics
else if (palettes.ContainsKey(name)) else if (palettes.ContainsKey(name))
CopyPaletteToBuffer(indices[name], palettes[name] = new ImmutablePalette(p)); CopyPaletteToBuffer(indices[name], palettes[name] = new ImmutablePalette(p));
else else
throw new InvalidOperationException("Palette `{0}` does not exist".F(name)); throw new InvalidOperationException($"Palette `{name}` does not exist");
CopyBufferToTexture(); CopyBufferToTexture();
} }

View File

@@ -205,7 +205,7 @@ namespace OpenRA.Graphics
var t = m.Model.TransformationMatrix(i, frame); var t = m.Model.TransformationMatrix(i, frame);
var it = Util.MatrixInverse(t); var it = Util.MatrixInverse(t);
if (it == null) if (it == null)
throw new InvalidOperationException("Failed to invert the transformed matrix of frame {0} during RenderAsync.".F(i)); throw new InvalidOperationException($"Failed to invert the transformed matrix of frame {i} during RenderAsync.");
// Transform light vector from shadow -> world -> limb coords // Transform light vector from shadow -> world -> limb coords
var lightDirection = ExtractRotationVector(Util.MatrixMultiply(it, lightTransform)); var lightDirection = ExtractRotationVector(Util.MatrixMultiply(it, lightTransform));

View File

@@ -72,10 +72,10 @@ namespace OpenRA.Graphics
public ISpriteSequence GetSequence(string unitName, string sequenceName) public ISpriteSequence GetSequence(string unitName, string sequenceName)
{ {
if (!sequences.Value.TryGetValue(unitName, out var unitSeq)) if (!sequences.Value.TryGetValue(unitName, out var unitSeq))
throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName)); throw new InvalidOperationException($"Unit `{unitName}` does not have any sequences defined.");
if (!unitSeq.Value.TryGetValue(sequenceName, out var seq)) if (!unitSeq.Value.TryGetValue(sequenceName, out var seq))
throw new InvalidOperationException("Unit `{0}` does not have a sequence named `{1}`".F(unitName, sequenceName)); throw new InvalidOperationException($"Unit `{unitName}` does not have a sequence named `{sequenceName}`");
return seq; return seq;
} }
@@ -90,7 +90,7 @@ namespace OpenRA.Graphics
public bool HasSequence(string unitName, string sequenceName) public bool HasSequence(string unitName, string sequenceName)
{ {
if (!sequences.Value.TryGetValue(unitName, out var unitSeq)) if (!sequences.Value.TryGetValue(unitName, out var unitSeq))
throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName)); throw new InvalidOperationException($"Unit `{unitName}` does not have any sequences defined.");
return unitSeq.Value.ContainsKey(sequenceName); return unitSeq.Value.ContainsKey(sequenceName);
} }
@@ -98,7 +98,7 @@ namespace OpenRA.Graphics
public IEnumerable<string> Sequences(string unitName) public IEnumerable<string> Sequences(string unitName)
{ {
if (!sequences.Value.TryGetValue(unitName, out var unitSeq)) if (!sequences.Value.TryGetValue(unitName, out var unitSeq))
throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName)); throw new InvalidOperationException($"Unit `{unitName}` does not have any sequences defined.");
return unitSeq.Value.Keys; return unitSeq.Value.Keys;
} }

View File

@@ -61,7 +61,7 @@ namespace OpenRA.Graphics
case SpriteFrameType.Rgba32: case SpriteFrameType.Rgba32:
case SpriteFrameType.Rgb24: case SpriteFrameType.Rgb24:
return SheetType.BGRA; return SheetType.BGRA;
default: throw new NotImplementedException("Unknown SpriteFrameType {0}".F(t)); default: throw new NotImplementedException($"Unknown SpriteFrameType {t}");
} }
} }

View File

@@ -43,7 +43,7 @@ namespace OpenRA.Graphics
// Pre-cache small font sizes so glyphs are immediately available when we need them // Pre-cache small font sizes so glyphs are immediately available when we need them
if (size <= 24) if (size <= 24)
using (new PerfTimer("Precache {0} {1}px".F(name, size))) using (new PerfTimer($"Precache {name} {size}px"))
for (var n = (char)0x20; n < (char)0x7f; n++) for (var n = (char)0x20; n < (char)0x7f; n++)
if (glyphs[n] == null) if (glyphs[n] == null)
throw new InvalidOperationException(); throw new InvalidOperationException();

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Graphics
public class SpriteRenderer : Renderer.IBatchRenderer public class SpriteRenderer : Renderer.IBatchRenderer
{ {
public const int SheetCount = 7; public const int SheetCount = 7;
static readonly string[] SheetIndexToTextureName = Exts.MakeArray(SheetCount, i => "Texture{0}".F(i)); static readonly string[] SheetIndexToTextureName = Exts.MakeArray(SheetCount, i => $"Texture{i}");
readonly Renderer renderer; readonly Renderer renderer;
readonly IShader shader; readonly IShader shader;
@@ -173,7 +173,7 @@ namespace OpenRA.Graphics
// PERF: methods that throw won't be inlined by the JIT, so extract a static helper for use on hot paths // PERF: methods that throw won't be inlined by the JIT, so extract a static helper for use on hot paths
static void ThrowSheetOverflow(string paramName) static void ThrowSheetOverflow(string paramName)
{ {
throw new ArgumentException("SpriteRenderer only supports {0} simultaneous textures".F(SheetCount), paramName); throw new ArgumentException($"SpriteRenderer only supports {SheetCount} simultaneous textures", paramName);
} }
// For RGBAColorRenderer // For RGBAColorRenderer

View File

@@ -108,7 +108,7 @@ namespace OpenRA.Graphics
} }
default: default:
throw new InvalidOperationException("Unknown SpriteFrameType {0}".F(srcType)); throw new InvalidOperationException($"Unknown SpriteFrameType {srcType}");
} }
var cc = Color.FromArgb(a, r, g, b); var cc = Color.FromArgb(a, r, g, b);
@@ -181,7 +181,7 @@ namespace OpenRA.Graphics
// Pngs don't support BGR[A], so no need to include them here // Pngs don't support BGR[A], so no need to include them here
default: default:
throw new InvalidOperationException("Unknown SpriteFrameType {0}".F(src.Type)); throw new InvalidOperationException($"Unknown SpriteFrameType {src.Type}");
} }
data[(y + j) * destStride + x + i] = PremultiplyAlpha(cc).ToArgb(); data[(y + j) * destStride + x + i] = PremultiplyAlpha(cc).ToArgb();

View File

@@ -84,7 +84,7 @@ namespace OpenRA
return obj is Hotkey o && (Hotkey?)o == this; return obj is Hotkey o && (Hotkey?)o == this;
} }
public override string ToString() { return "{0} {1}".F(Key, Modifiers.ToString("F")); } public override string ToString() { return $"{Key} {Modifiers.ToString("F")}"; }
public string DisplayString() public string DisplayString()
{ {

View File

@@ -74,7 +74,7 @@ namespace OpenRA
} }
catch (Exception e) catch (Exception e)
{ {
Log.Write("debug", "Load mod '{0}': {1}".F(path, e)); Log.Write("debug", $"Load mod '{path}': {e}");
} }
package?.Dispose(); package?.Dispose();

View File

@@ -113,7 +113,7 @@ namespace OpenRA
var filename = nodes[i].Value.Value; var filename = nodes[i].Value.Value;
var contents = package.GetStream(filename); var contents = package.GetStream(filename);
if (contents == null) if (contents == null)
throw new YamlException("{0}: File `{1}` not found.".F(nodes[i].Location, filename)); throw new YamlException($"{nodes[i].Location}: File `{filename}` not found.");
nodes.RemoveAt(i); nodes.RemoveAt(i);
nodes.InsertRange(i, MiniYaml.FromStream(contents, filename)); nodes.InsertRange(i, MiniYaml.FromStream(contents, filename));
@@ -182,7 +182,7 @@ namespace OpenRA
var t = oc.FindType(kv.Key); var t = oc.FindType(kv.Key);
if (t == null || !typeof(IGlobalModData).IsAssignableFrom(t)) if (t == null || !typeof(IGlobalModData).IsAssignableFrom(t))
throw new InvalidDataException("`{0}` is not a valid mod manifest entry.".F(kv.Key)); throw new InvalidDataException($"`{kv.Key}` is not a valid mod manifest entry.");
IGlobalModData module; IGlobalModData module;
var ctor = t.GetConstructor(new[] { typeof(MiniYaml) }); var ctor = t.GetConstructor(new[] { typeof(MiniYaml) });

View File

@@ -66,7 +66,7 @@ namespace OpenRA
{ {
var init = GetOrDefault<T>(info); var init = GetOrDefault<T>(info);
if (init == null) if (init == null)
throw new InvalidOperationException("TypeDictionary does not contain instance of type `{0}`".F(typeof(T))); throw new InvalidOperationException($"TypeDictionary does not contain instance of type `{typeof(T)}`");
return init; return init;
} }

View File

@@ -42,7 +42,7 @@ namespace OpenRA
{ {
var init = LoadInit(i.Key, i.Value); var init = LoadInit(i.Key, i.Value);
if (init is ISingleInstanceInit && dict.Contains(init.GetType())) if (init is ISingleInstanceInit && dict.Contains(init.GetType()))
throw new InvalidDataException("Duplicate initializer '{0}'".F(init.GetType().Name)); throw new InvalidDataException($"Duplicate initializer '{init.GetType().Name}'");
dict.Add(init); dict.Add(init);
} }
@@ -68,7 +68,7 @@ namespace OpenRA
var initInstance = initName.Split(ActorInfo.TraitInstanceSeparator); var initInstance = initName.Split(ActorInfo.TraitInstanceSeparator);
var type = Game.ModData.ObjectCreator.FindType(initInstance[0] + "Init"); var type = Game.ModData.ObjectCreator.FindType(initInstance[0] + "Init");
if (type == null) if (type == null)
throw new InvalidDataException("Unknown initializer type '{0}Init'".F(initInstance[0])); throw new InvalidDataException($"Unknown initializer type '{initInstance[0]}Init'");
var init = (ActorInit)FormatterServices.GetUninitializedObject(type); var init = (ActorInit)FormatterServices.GetUninitializedObject(type);
if (initInstance.Length > 1) if (initInstance.Length > 1)
@@ -76,7 +76,7 @@ namespace OpenRA
var loader = type.GetMethod("Initialize", new[] { typeof(MiniYaml) }); var loader = type.GetMethod("Initialize", new[] { typeof(MiniYaml) });
if (loader == null) if (loader == null)
throw new InvalidDataException("{0}Init does not define a yaml-assignable type.".F(initInstance[0])); throw new InvalidDataException($"{initInstance[0]}Init does not define a yaml-assignable type.");
loader.Invoke(init, new[] { initYaml }); loader.Invoke(init, new[] { initYaml });
return init; return init;
@@ -119,7 +119,7 @@ namespace OpenRA
public void Add(ActorInit init) public void Add(ActorInit init)
{ {
if (init is ISingleInstanceInit && InitDict.Contains(init.GetType())) if (init is ISingleInstanceInit && InitDict.Contains(init.GetType()))
throw new InvalidDataException("Duplicate initializer '{0}'".F(init.GetType().Name)); throw new InvalidDataException($"Duplicate initializer '{init.GetType().Name}'");
InitDict.Add(init); InitDict.Add(init);
} }
@@ -162,7 +162,7 @@ namespace OpenRA
{ {
var init = GetOrDefault<T>(info); var init = GetOrDefault<T>(info);
if (init == null) if (init == null)
throw new InvalidOperationException("TypeDictionary does not contain instance of type `{0}`".F(typeof(T))); throw new InvalidOperationException($"TypeDictionary does not contain instance of type `{typeof(T)}`");
return init; return init;
} }

View File

@@ -53,7 +53,7 @@ namespace OpenRA
ResourcesOffset = s.ReadUInt32(); ResourcesOffset = s.ReadUInt32();
} }
else else
throw new InvalidDataException("Unknown binary map format '{0}'".F(Format)); throw new InvalidDataException($"Unknown binary map format '{Format}'");
} }
} }
@@ -100,7 +100,7 @@ namespace OpenRA
if (node == null) if (node == null)
{ {
if (required) if (required)
throw new YamlException("Required field `{0}` not found in map.yaml".F(key)); throw new YamlException($"Required field `{key}` not found in map.yaml");
return; return;
} }
@@ -258,7 +258,7 @@ namespace OpenRA
var contents = package.Contents.ToList(); var contents = package.Contents.ToList();
foreach (var required in requiredFiles) foreach (var required in requiredFiles)
if (!contents.Contains(required)) if (!contents.Contains(required))
throw new FileNotFoundException("Required file {0} not present in this map".F(required)); throw new FileNotFoundException($"Required file {required} not present in this map");
var streams = new List<Stream>(); var streams = new List<Stream>();
try try
@@ -326,18 +326,18 @@ namespace OpenRA
Package = package; Package = package;
if (!Package.Contains("map.yaml") || !Package.Contains("map.bin")) if (!Package.Contains("map.yaml") || !Package.Contains("map.bin"))
throw new InvalidDataException("Not a valid map\n File: {0}".F(package.Name)); throw new InvalidDataException($"Not a valid map\n File: {package.Name}");
var yaml = new MiniYaml(null, MiniYaml.FromStream(Package.GetStream("map.yaml"), package.Name)); var yaml = new MiniYaml(null, MiniYaml.FromStream(Package.GetStream("map.yaml"), package.Name));
foreach (var field in YamlFields) foreach (var field in YamlFields)
field.Deserialize(this, yaml.Nodes); field.Deserialize(this, yaml.Nodes);
if (MapFormat != SupportedMapFormat) if (MapFormat != SupportedMapFormat)
throw new InvalidDataException("Map format {0} is not supported.\n File: {1}".F(MapFormat, package.Name)); throw new InvalidDataException($"Map format {MapFormat} is not supported.\n File: {package.Name}");
PlayerDefinitions = MiniYaml.NodesOrEmpty(yaml, "Players"); PlayerDefinitions = MiniYaml.NodesOrEmpty(yaml, "Players");
if (PlayerDefinitions.Count > 64) if (PlayerDefinitions.Count > 64)
throw new InvalidDataException("Maps must not define more than 64 players.\n File: {0}".F(package.Name)); throw new InvalidDataException($"Maps must not define more than 64 players.\n File: {package.Name}");
ActorDefinitions = MiniYaml.NodesOrEmpty(yaml, "Actors"); ActorDefinitions = MiniYaml.NodesOrEmpty(yaml, "Actors");
@@ -1251,7 +1251,7 @@ namespace OpenRA
if (maxRange >= Grid.TilesByDistance.Length) if (maxRange >= Grid.TilesByDistance.Length)
throw new ArgumentOutOfRangeException(nameof(maxRange), throw new ArgumentOutOfRangeException(nameof(maxRange),
"The requested range ({0}) cannot exceed the value of MaximumTileSearchRange ({1})".F(maxRange, Grid.MaximumTileSearchRange)); $"The requested range ({maxRange}) cannot exceed the value of MaximumTileSearchRange ({Grid.MaximumTileSearchRange})");
for (var i = minRange; i <= maxRange; i++) for (var i = minRange; i <= maxRange; i++)
{ {

View File

@@ -50,7 +50,7 @@ namespace OpenRA
Name = "Creeps", Name = "Creeps",
Faction = firstFaction, Faction = firstFaction,
NonCombatant = true, NonCombatant = true,
Enemies = Exts.MakeArray(playerCount, i => "Multi{0}".F(i)) Enemies = Exts.MakeArray(playerCount, i => $"Multi{i}")
} }
} }
}; };
@@ -59,7 +59,7 @@ namespace OpenRA
{ {
var p = new PlayerReference var p = new PlayerReference
{ {
Name = "Multi{0}".F(index), Name = $"Multi{index}",
Faction = "Random", Faction = "Random",
Playable = true, Playable = true,
Enemies = new[] { "Creeps" } Enemies = new[] { "Creeps" }
@@ -70,7 +70,7 @@ namespace OpenRA
public List<MiniYamlNode> ToMiniYaml() public List<MiniYamlNode> ToMiniYaml()
{ {
return Players.Select(p => new MiniYamlNode("PlayerReference@{0}".F(p.Key), return Players.Select(p => new MiniYamlNode($"PlayerReference@{p.Key}",
FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList(); FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList();
} }
} }

View File

@@ -324,7 +324,7 @@ namespace OpenRA
{ {
var format = FieldLoader.GetValue<int>("MapFormat", temp.Value); var format = FieldLoader.GetValue<int>("MapFormat", temp.Value);
if (format != Map.SupportedMapFormat) if (format != Map.SupportedMapFormat)
throw new InvalidDataException("Map format {0} is not supported.".F(format)); throw new InvalidDataException($"Map format {format} is not supported.");
} }
if (yaml.TryGetValue("Title", out temp)) if (yaml.TryGetValue("Title", out temp))

View File

@@ -45,7 +45,7 @@ namespace OpenRA
public struct SourceLocation public struct SourceLocation
{ {
public string Filename; public int Line; public string Filename; public int Line;
public override string ToString() { return "{0}:{1}".F(Filename, Line); } public override string ToString() { return $"{Filename}:{Line}"; }
} }
public SourceLocation Location; public SourceLocation Location;
@@ -80,7 +80,7 @@ namespace OpenRA
public override string ToString() public override string ToString()
{ {
return "{{YamlNode: {0} @ {1}}}".F(Key, Location); return $"{{YamlNode: {Key} @ {Location}}}";
} }
public MiniYamlNode Clone() public MiniYamlNode Clone()
@@ -129,7 +129,7 @@ namespace OpenRA
} }
catch (ArgumentException ex) catch (ArgumentException ex)
{ {
throw new InvalidDataException("Duplicate key '{0}' in {1}".F(y.Key, y.Location), ex); throw new InvalidDataException($"Duplicate key '{y.Key}' in {y.Location}", ex);
} }
} }
@@ -205,7 +205,7 @@ namespace OpenRA
} }
if (levels.Count <= level) if (levels.Count <= level)
throw new YamlException("Bad indent in miniyaml at {0}".F(location)); throw new YamlException($"Bad indent in miniyaml at {location}");
while (levels.Count > level + 1) while (levels.Count > level + 1)
levels.RemoveAt(levels.Count - 1); levels.RemoveAt(levels.Count - 1);
@@ -361,11 +361,10 @@ namespace OpenRA
{ {
if (!tree.TryGetValue(n.Value.Value, out var parent)) if (!tree.TryGetValue(n.Value.Value, out var parent))
throw new YamlException( throw new YamlException(
"{0}: Parent type `{1}` not found".F(n.Location, n.Value.Value)); $"{n.Location}: Parent type `{n.Value.Value}` not found");
if (inherited.ContainsKey(n.Value.Value)) if (inherited.ContainsKey(n.Value.Value))
throw new YamlException("{0}: Parent type `{1}` was already inherited by this yaml tree at {2} (note: may be from a derived tree)" throw new YamlException($"{n.Location}: Parent type `{n.Value.Value}` was already inherited by this yaml tree at {inherited[n.Value.Value]} (note: may be from a derived tree)");
.F(n.Location, n.Value.Value, inherited[n.Value.Value]));
inherited.Add(n.Value.Value, n.Location); inherited.Add(n.Value.Value, n.Location);
foreach (var r in ResolveInherits(n.Key, parent, tree, inherited)) foreach (var r in ResolveInherits(n.Key, parent, tree, inherited))
@@ -375,7 +374,7 @@ namespace OpenRA
{ {
var removed = n.Key.Substring(1); var removed = n.Key.Substring(1);
if (resolved.RemoveAll(r => r.Key == removed) == 0) if (resolved.RemoveAll(r => r.Key == removed) == 0)
throw new YamlException("{0}: There are no elements with key `{1}` to remove".F(n.Location, removed)); throw new YamlException($"{n.Location}: There are no elements with key `{removed}` to remove");
} }
else else
MergeIntoResolved(n, resolved, tree, inherited); MergeIntoResolved(n, resolved, tree, inherited);
@@ -443,8 +442,8 @@ namespace OpenRA
var ret = new List<MiniYamlNode>(); var ret = new List<MiniYamlNode>();
var existingDict = existingNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => "{0} (at {1})".F(x.Key, x.Location)); var existingDict = existingNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => $"{x.Key} (at {x.Location})");
var overrideDict = overrideNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => "{0} (at {1})".F(x.Key, x.Location)); var overrideDict = overrideNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => $"{x.Key} (at {x.Location})");
var allKeys = existingDict.Keys.Union(overrideDict.Keys); var allKeys = existingDict.Keys.Union(overrideDict.Keys);
foreach (var key in allKeys) foreach (var key in allKeys)

View File

@@ -81,7 +81,7 @@ namespace OpenRA
var terrainLoader = ObjectCreator.FindType(terrainFormat.Type + "Loader"); var terrainLoader = ObjectCreator.FindType(terrainFormat.Type + "Loader");
var terrainCtor = terrainLoader?.GetConstructor(new[] { typeof(ModData) }); var terrainCtor = terrainLoader?.GetConstructor(new[] { typeof(ModData) });
if (terrainLoader == null || !terrainLoader.GetInterfaces().Contains(typeof(ITerrainLoader)) || terrainCtor == null) if (terrainLoader == null || !terrainLoader.GetInterfaces().Contains(typeof(ITerrainLoader)) || terrainCtor == null)
throw new InvalidOperationException("Unable to find a terrain loader for type '{0}'.".F(terrainFormat.Type)); throw new InvalidOperationException($"Unable to find a terrain loader for type '{terrainFormat.Type}'.");
TerrainLoader = (ITerrainLoader)terrainCtor.Invoke(new[] { this }); TerrainLoader = (ITerrainLoader)terrainCtor.Invoke(new[] { this });
@@ -89,7 +89,7 @@ namespace OpenRA
var sequenceLoader = ObjectCreator.FindType(sequenceFormat.Type + "Loader"); var sequenceLoader = ObjectCreator.FindType(sequenceFormat.Type + "Loader");
var sequenceCtor = sequenceLoader != null ? sequenceLoader.GetConstructor(new[] { typeof(ModData) }) : null; var sequenceCtor = sequenceLoader != null ? sequenceLoader.GetConstructor(new[] { typeof(ModData) }) : null;
if (sequenceLoader == null || !sequenceLoader.GetInterfaces().Contains(typeof(ISpriteSequenceLoader)) || sequenceCtor == null) if (sequenceLoader == null || !sequenceLoader.GetInterfaces().Contains(typeof(ISpriteSequenceLoader)) || sequenceCtor == null)
throw new InvalidOperationException("Unable to find a sequence loader for type '{0}'.".F(sequenceFormat.Type)); throw new InvalidOperationException($"Unable to find a sequence loader for type '{sequenceFormat.Type}'.");
SpriteSequenceLoader = (ISpriteSequenceLoader)sequenceCtor.Invoke(new[] { this }); SpriteSequenceLoader = (ISpriteSequenceLoader)sequenceCtor.Invoke(new[] { this });
@@ -97,7 +97,7 @@ namespace OpenRA
var modelLoader = ObjectCreator.FindType(modelFormat.Type + "Loader"); var modelLoader = ObjectCreator.FindType(modelFormat.Type + "Loader");
var modelCtor = modelLoader != null ? modelLoader.GetConstructor(new[] { typeof(ModData) }) : null; var modelCtor = modelLoader != null ? modelLoader.GetConstructor(new[] { typeof(ModData) }) : null;
if (modelLoader == null || !modelLoader.GetInterfaces().Contains(typeof(IModelSequenceLoader)) || modelCtor == null) if (modelLoader == null || !modelLoader.GetInterfaces().Contains(typeof(IModelSequenceLoader)) || modelCtor == null)
throw new InvalidOperationException("Unable to find a model loader for type '{0}'.".F(modelFormat.Type)); throw new InvalidOperationException($"Unable to find a model loader for type '{modelFormat.Type}'.");
ModelSequenceLoader = (IModelSequenceLoader)modelCtor.Invoke(new[] { this }); ModelSequenceLoader = (IModelSequenceLoader)modelCtor.Invoke(new[] { this });
ModelSequenceLoader.OnMissingModelError = s => Log.Write("debug", s); ModelSequenceLoader.OnMissingModelError = s => Log.Write("debug", s);
@@ -156,7 +156,7 @@ namespace OpenRA
LoadScreen?.Display(); LoadScreen?.Display();
if (MapCache[uid].Status != MapStatus.Available) if (MapCache[uid].Status != MapStatus.Available)
throw new InvalidDataException("Invalid map uid: {0}".F(uid)); throw new InvalidDataException($"Invalid map uid: {uid}");
Map map; Map map;
using (new Support.PerfTimer("Map")) using (new Support.PerfTimer("Map"))

View File

@@ -156,7 +156,7 @@ namespace OpenRA.Network
this.target = target; this.target = target;
new Thread(NetworkConnectionConnect) new Thread(NetworkConnectionConnect)
{ {
Name = "{0} (connect to {1})".F(GetType().Name, target), Name = $"{GetType().Name} (connect to {target})",
IsBackground = true IsBackground = true
}.Start(); }.Start();
} }
@@ -189,11 +189,11 @@ namespace OpenRA.Network
catch (Exception ex) catch (Exception ex)
{ {
errorMessage = "Failed to connect"; errorMessage = "Failed to connect";
Log.Write("client", "Failed to connect to {0}: {1}".F(endpoint, ex.Message)); Log.Write("client", $"Failed to connect to {endpoint}: {ex.Message}");
} }
}) })
{ {
Name = "{0} (connect to {1})".F(GetType().Name, endpoint), Name = $"{GetType().Name} (connect to {endpoint})",
IsBackground = true IsBackground = true
}.Start(); }.Start();
} }
@@ -212,7 +212,7 @@ namespace OpenRA.Network
new Thread(NetworkConnectionReceive) new Thread(NetworkConnectionReceive)
{ {
Name = "{0} (receive from {1})".F(GetType().Name, tcp.Client.RemoteEndPoint), Name = $"{GetType().Name} (receive from {tcp.Client.RemoteEndPoint})",
IsBackground = true IsBackground = true
}.Start(); }.Start();
} }
@@ -235,9 +235,7 @@ namespace OpenRA.Network
var handshakeProtocol = reader.ReadInt32(); var handshakeProtocol = reader.ReadInt32();
if (handshakeProtocol != ProtocolVersion.Handshake) if (handshakeProtocol != ProtocolVersion.Handshake)
throw new InvalidOperationException( throw new InvalidOperationException($"Handshake protocol version mismatch. Server={handshakeProtocol} Client={ProtocolVersion.Handshake}");
"Handshake protocol version mismatch. Server={0} Client={1}"
.F(handshakeProtocol, ProtocolVersion.Handshake));
clientId = reader.ReadInt32(); clientId = reader.ReadInt32();
connectionState = ConnectionState.Connected; connectionState = ConnectionState.Connected;
@@ -255,7 +253,7 @@ namespace OpenRA.Network
catch (Exception ex) catch (Exception ex)
{ {
errorMessage = "Connection failed"; errorMessage = "Connection failed";
Log.Write("client", "Connection to {0} failed: {1}".F(endpoint, ex.Message)); Log.Write("client", $"Connection to {endpoint} failed: {ex.Message}");
} }
finally finally
{ {

View File

@@ -56,7 +56,7 @@ namespace OpenRA.Network
public override string ToString() public override string ToString()
{ {
return endpoints return endpoints
.Select(e => "{0}:{1}".F(e.Host, e.Port)) .Select(e => $"{e.Host}:{e.Port}")
.JoinWith("/"); .JoinWith("/");
} }
} }

View File

@@ -23,7 +23,7 @@ namespace OpenRA.Network
public override string ToString() public override string ToString()
{ {
return "ClientId: {0} {1}".F(Client, Order); return $"ClientId: {Client} {Order}";
} }
} }

View File

@@ -71,7 +71,7 @@ namespace OpenRA.Network
public MiniYamlNode Serialize(string key) public MiniYamlNode Serialize(string key)
{ {
return new MiniYamlNode("SlotClient@{0}".F(key), FieldSaver.Save(this)); return new MiniYamlNode($"SlotClient@{key}", FieldSaver.Save(this));
} }
} }
@@ -195,7 +195,7 @@ namespace OpenRA.Network
{ {
if (data.Length != Order.SyncHashOrderLength) if (data.Length != Order.SyncHashOrderLength)
{ {
Log.Write("debug", "Dropped sync order with length {0}. Expected length {1}.".F(data.Length, Order.SyncHashOrderLength)); Log.Write("debug", $"Dropped sync order with length {data.Length}. Expected length {Order.SyncHashOrderLength}.");
return; return;
} }

View File

@@ -135,7 +135,7 @@ namespace OpenRA.Network
/// <summary>The list of spawnpoints that are disabled for this game</summary> /// <summary>The list of spawnpoints that are disabled for this game</summary>
public readonly int[] DisabledSpawnPoints = { }; public readonly int[] DisabledSpawnPoints = { };
public string ModLabel => "{0} ({1})".F(ModTitle, Version); public string ModLabel => $"{ModTitle} ({Version})";
static object LoadClients(MiniYaml yaml) static object LoadClients(MiniYaml yaml)
{ {
@@ -200,9 +200,9 @@ namespace OpenRA.Network
.FirstOrDefault(m => m.Id == Mod); .FirstOrDefault(m => m.Id == Mod);
if (guessMod != null) if (guessMod != null)
ModTitle = "{0}".F(guessMod.Title); ModTitle = guessMod.Title;
else else
ModTitle = "Unknown mod: {0}".F(Mod); ModTitle = $"Unknown mod: {Mod}";
} }
} }

View File

@@ -405,7 +405,7 @@ namespace OpenRA
} }
default: default:
throw new InvalidDataException("Cannot serialize order type {0}".F(Type)); throw new InvalidDataException($"Cannot serialize order type {Type}");
} }
return ret.ToArray(); return ret.ToArray();
@@ -413,10 +413,8 @@ namespace OpenRA
public override string ToString() public override string ToString()
{ {
return ("OrderString: \"{0}\" \n\t Type: \"{1}\". \n\t Subject: \"{2}\". \n\t Target: \"{3}\"." + return $"OrderString: \"{OrderString}\" \n\t Type: \"{Type}\". \n\t Subject: \"{Subject}\". \n\t Target: \"{Target}\"." +
"\n\t TargetString: \"{4}\".\n\t IsImmediate: {5}.\n\t Player(PlayerName): {6}\n").F( $"\n\t TargetString: \"{TargetString}\".\n\t IsImmediate: {IsImmediate}.\n\t Player(PlayerName): {Player?.PlayerName}\n";
OrderString, Type, Subject, Target, TargetString, IsImmediate,
Player != null ? Player.PlayerName : null);
} }
} }
} }

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Network
void OutOfSync(int frame) void OutOfSync(int frame)
{ {
syncReport.DumpSyncReport(frame, frameData.OrdersForFrame(World, frame)); syncReport.DumpSyncReport(frame, frameData.OrdersForFrame(World, frame));
throw new InvalidOperationException("Out of sync in frame {0}.\n Compare syncreport.log with other players.".F(frame)); throw new InvalidOperationException($"Out of sync in frame {frame}.\n Compare syncreport.log with other players.");
} }
public void StartGame() public void StartGame()
@@ -126,7 +126,7 @@ namespace OpenRA.Network
{ {
if (packet.Length != 4 + Order.SyncHashOrderLength) if (packet.Length != 4 + Order.SyncHashOrderLength)
{ {
Log.Write("debug", "Dropped sync order with length {0}. Expected length {1}.".F(packet.Length, 4 + Order.SyncHashOrderLength)); Log.Write("debug", $"Dropped sync order with length {packet.Length}. Expected length {4 + Order.SyncHashOrderLength}.");
return; return;
} }

View File

@@ -56,7 +56,7 @@ namespace OpenRA.Network
var id = -1; var id = -1;
while (file == null) while (file == null)
{ {
var fullFilename = Path.Combine(dir, id < 0 ? "{0}.orarep".F(filename) : "{0}-{1}.orarep".F(filename, id)); var fullFilename = Path.Combine(dir, id < 0 ? $"{filename}.orarep" : $"{filename}-{id}.orarep");
id++; id++;
try try
{ {
@@ -65,8 +65,7 @@ namespace OpenRA.Network
catch (IOException ex) catch (IOException ex)
{ {
if (id > CreateReplayFileMaxRetryCount) if (id > CreateReplayFileMaxRetryCount)
throw new ArgumentException( throw new ArgumentException($"Error creating replay file \"{filename}.orarep\"", ex);
"Error creating replay file \"{0}.orarep\"".F(filename), ex);
} }
} }

View File

@@ -37,7 +37,7 @@ namespace OpenRA.Network
{ {
// Follow convention used by Google Analytics: remove last octet // Follow convention used by Google Analytics: remove last octet
var b = ip.GetAddressBytes(); var b = ip.GetAddressBytes();
return "{0}.{1}.{2}.*".F(b[0], b[1], b[2]); return $"{b[0]}.{b[1]}.{b[2]}.*";
} }
return null; return null;
@@ -82,11 +82,11 @@ namespace OpenRA.Network
} }
catch (YamlException) catch (YamlException)
{ {
throw new YamlException("Session deserialized invalid MiniYaml:\n{0}".F(data)); throw new YamlException($"Session deserialized invalid MiniYaml:\n{data}");
} }
catch (InvalidOperationException) catch (InvalidOperationException)
{ {
throw new YamlException("Session deserialized invalid MiniYaml:\n{0}".F(data)); throw new YamlException($"Session deserialized invalid MiniYaml:\n{data}");
} }
} }
@@ -159,7 +159,7 @@ namespace OpenRA.Network
public MiniYamlNode Serialize() public MiniYamlNode Serialize()
{ {
return new MiniYamlNode("Client@{0}".F(Index), FieldSaver.Save(this)); return new MiniYamlNode($"Client@{Index}", FieldSaver.Save(this));
} }
} }
@@ -182,7 +182,7 @@ namespace OpenRA.Network
public MiniYamlNode Serialize() public MiniYamlNode Serialize()
{ {
return new MiniYamlNode("ClientPing@{0}".F(Index), FieldSaver.Save(this)); return new MiniYamlNode($"ClientPing@{Index}", FieldSaver.Save(this));
} }
} }
@@ -206,7 +206,7 @@ namespace OpenRA.Network
public MiniYamlNode Serialize() public MiniYamlNode Serialize()
{ {
return new MiniYamlNode("Slot@{0}".F(PlayerReference), FieldSaver.Save(this)); return new MiniYamlNode($"Slot@{PlayerReference}", FieldSaver.Save(this));
} }
} }

View File

@@ -117,12 +117,12 @@ 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(a.ActorID, a.Type, a.Owner, a.Trait, a.Hash)); Log.Write("sync", $"\t {a.ActorID} {a.Type} {a.Owner} {a.Trait} ({a.Hash})");
var nvp = a.NamesValues; var nvp = a.NamesValues;
for (int i = 0; i < nvp.Names.Length; i++) for (int i = 0; i < nvp.Names.Length; i++)
if (nvp.Values[i] != null) if (nvp.Values[i] != null)
Log.Write("sync", "\t\t {0}: {1}".F(nvp.Names[i], nvp.Values[i])); Log.Write("sync", $"\t\t {nvp.Names[i]}: {nvp.Values[i]}");
} }
Log.Write("sync", "Synced Effects:"); Log.Write("sync", "Synced Effects:");
@@ -133,7 +133,7 @@ namespace OpenRA.Network
var nvp = e.NamesValues; var nvp = e.NamesValues;
for (int i = 0; i < nvp.Names.Length; i++) for (int i = 0; i < nvp.Names.Length; i++)
if (nvp.Values[i] != null) if (nvp.Values[i] != null)
Log.Write("sync", "\t\t {0}: {1}".F(nvp.Names[i], nvp.Values[i])); Log.Write("sync", $"\t\t {nvp.Names[i]}: {nvp.Values[i]}");
} }
Log.Write("sync", "Orders Issued:"); Log.Write("sync", "Orders Issued:");

View File

@@ -170,7 +170,7 @@ namespace OpenRA.Network
if (orderManager.World.Paused != pause && world != null && world.LobbyInfo.NonBotClients.Count() > 1) if (orderManager.World.Paused != pause && world != null && world.LobbyInfo.NonBotClients.Count() > 1)
{ {
var pausetext = "The game is {0} by {1}".F(pause ? "paused" : "un-paused", client.Name); var pausetext = $"The game is {(pause ? "paused" : "un-paused")} by {client.Name}";
Game.AddSystemLine(pausetext); Game.AddSystemLine(pausetext);
} }

View File

@@ -41,7 +41,7 @@ namespace OpenRA
{ {
var resolvedPath = FileSystem.FileSystem.ResolveAssemblyPath(path, manifest, mods); var resolvedPath = FileSystem.FileSystem.ResolveAssemblyPath(path, manifest, mods);
if (resolvedPath == null) if (resolvedPath == null)
throw new FileNotFoundException("Assembly `{0}` not found.".F(path)); throw new FileNotFoundException($"Assembly `{path}` not found.");
LoadAssembly(assemblyList, resolvedPath); LoadAssembly(assemblyList, resolvedPath);
} }
@@ -111,7 +111,7 @@ namespace OpenRA
if (MissingTypeAction != null) if (MissingTypeAction != null)
MissingTypeAction(className); MissingTypeAction(className);
else else
throw new InvalidOperationException("Cannot locate type: {0}".F(className)); throw new InvalidOperationException($"Cannot locate type: {className}");
return default(T); return default(T);
} }
@@ -151,7 +151,7 @@ namespace OpenRA
for (var i = 0; i < p.Length; i++) for (var i = 0; i < p.Length; i++)
{ {
var key = p[i].Name; var key = p[i].Name;
if (!args.ContainsKey(key)) throw new InvalidOperationException("ObjectCreator: key `{0}' not found".F(key)); if (!args.ContainsKey(key)) throw new InvalidOperationException($"ObjectCreator: key `{key}' not found");
a[i] = args[key]; a[i] = args[key];
} }
@@ -177,7 +177,7 @@ namespace OpenRA
{ {
var loader = FindType(format + "Loader"); var loader = FindType(format + "Loader");
if (loader == null || !loader.GetInterfaces().Contains(typeof(TLoader))) if (loader == null || !loader.GetInterfaces().Contains(typeof(TLoader)))
throw new InvalidOperationException("Unable to find a {0} loader for type '{1}'.".F(name, format)); throw new InvalidOperationException($"Unable to find a {name} loader for type '{format}'.");
loaders.Add((TLoader)CreateBasic(loader)); loaders.Add((TLoader)CreateBasic(loader));
} }

View File

@@ -64,13 +64,13 @@ namespace OpenRA
{ {
var mono = Type.GetType("Mono.Runtime"); var mono = Type.GetType("Mono.Runtime");
if (mono == null) if (mono == null)
return ".NET CLR {0}".F(Environment.Version); return $".NET CLR {Environment.Version}";
var version = mono.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); var version = mono.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
if (version == null) if (version == null)
return "Mono (unknown version) CLR {0}".F(Environment.Version); return $"Mono (unknown version) CLR {Environment.Version}";
return "Mono {0} CLR {1}".F(version.Invoke(null, null), Environment.Version); return $"Mono {version.Invoke(null, null)} CLR {Environment.Version}";
} }
} }

View File

@@ -118,7 +118,7 @@ namespace OpenRA
selected = selectableFactions.FirstOrDefault(f => f.InternalName == faction); selected = selectableFactions.FirstOrDefault(f => f.InternalName == faction);
if (selected == null) if (selected == null)
throw new YamlException("Unknown faction: {0}".F(faction)); throw new YamlException($"Unknown faction: {faction}");
} }
return selected; return selected;
@@ -143,7 +143,7 @@ namespace OpenRA
{ {
var botInfo = botInfos.First(b => b.Type == client.Bot); var botInfo = botInfos.First(b => b.Type == client.Bot);
var botsOfSameType = clients.Where(c => c.Bot == client.Bot).ToArray(); var botsOfSameType = clients.Where(c => c.Bot == client.Bot).ToArray();
return botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1); return botsOfSameType.Length == 1 ? botInfo.Name : $"{botInfo.Name} {botsOfSameType.IndexOf(client) + 1}";
} }
return client.Name; return client.Name;
@@ -230,7 +230,7 @@ namespace OpenRA
public override string ToString() public override string ToString()
{ {
return "{0} ({1})".F(PlayerName, ClientIndex); return $"{PlayerName} ({ClientIndex})";
} }
public PlayerRelationship RelationshipWith(Player other) public PlayerRelationship RelationshipWith(Player other)
@@ -305,7 +305,7 @@ namespace OpenRA
public LuaValue ToString(LuaRuntime runtime) public LuaValue ToString(LuaRuntime runtime)
{ {
return "Player ({0})".F(PlayerName); return $"Player ({PlayerName})";
} }
#endregion #endregion

View File

@@ -126,7 +126,7 @@ namespace OpenRA.Primitives
public override string ToString() public override string ToString()
{ {
return "{0},{1},{2},{3}".F(X, Y, Width, Height); return $"{X},{Y},{Width},{Height}";
} }
} }
} }

View File

@@ -66,7 +66,7 @@ namespace OpenRA.Primitives
public override string ToString() public override string ToString()
{ {
return string.Format("{{Width={0}, Height={1}}}", Width, Height); return $"{{Width={Width}, Height={Height}}}";
} }
} }
} }

View File

@@ -33,7 +33,7 @@ namespace OpenRA.Primitives
void ValidateBounds(T actor, Rectangle bounds) void ValidateBounds(T actor, Rectangle bounds)
{ {
if (bounds.Width == 0 || bounds.Height == 0) if (bounds.Width == 0 || bounds.Height == 0)
throw new ArgumentException("Bounds of actor {0} are empty.".F(actor), nameof(bounds)); throw new ArgumentException($"Bounds of actor {actor} are empty.", nameof(bounds));
} }
public void Add(T item, Rectangle bounds) public void Add(T item, Rectangle bounds)

View File

@@ -64,12 +64,12 @@ namespace OpenRA.Primitives
if (!data.TryGetValue(t, out var ret)) if (!data.TryGetValue(t, out var ret))
{ {
if (throwsIfMissing) if (throwsIfMissing)
throw new InvalidOperationException("TypeDictionary does not contain instance of type `{0}`".F(t)); throw new InvalidOperationException($"TypeDictionary does not contain instance of type `{t}`");
return null; return null;
} }
if (ret.Count > 1) if (ret.Count > 1)
throw new InvalidOperationException("TypeDictionary contains multiple instances of type `{0}`".F(t)); throw new InvalidOperationException($"TypeDictionary contains multiple instances of type `{t}`");
return ret[0]; return ret[0];
} }

View File

@@ -58,7 +58,7 @@ namespace OpenRA
return obj is float3 o && (float3?)o == this; return obj is float3 o && (float3?)o == this;
} }
public override string ToString() { return "{0},{1},{2}".F(X, Y, Z); } public override string ToString() { return $"{X},{Y},{Z}"; }
public static readonly float3 Zero = new float3(0, 0, 0); public static readonly float3 Zero = new float3(0, 0, 0);
public static readonly float3 Ones = new float3(1, 1, 1); public static readonly float3 Ones = new float3(1, 1, 1);

View File

@@ -181,7 +181,7 @@ namespace OpenRA
public void BeginWorld(Rectangle worldViewport) public void BeginWorld(Rectangle worldViewport)
{ {
if (renderType != RenderType.None) if (renderType != RenderType.None)
throw new InvalidOperationException("BeginWorld called with renderType = {0}, expected RenderType.None.".F(renderType)); throw new InvalidOperationException($"BeginWorld called with renderType = {renderType}, expected RenderType.None.");
BeginFrame(); BeginFrame();
@@ -263,7 +263,7 @@ namespace OpenRA
public void EndFrame(IInputHandler inputHandler) public void EndFrame(IInputHandler inputHandler)
{ {
if (renderType != RenderType.UI) if (renderType != RenderType.UI)
throw new InvalidOperationException("EndFrame called with renderType = {0}, expected RenderType.UI.".F(renderType)); throw new InvalidOperationException($"EndFrame called with renderType = {renderType}, expected RenderType.UI.");
Flush(); Flush();
@@ -391,7 +391,7 @@ namespace OpenRA
public void EnableAntialiasingFilter() public void EnableAntialiasingFilter()
{ {
if (renderType != RenderType.UI) if (renderType != RenderType.UI)
throw new InvalidOperationException("EndFrame called with renderType = {0}, expected RenderType.UI.".F(renderType)); throw new InvalidOperationException($"EndFrame called with renderType = {renderType}, expected RenderType.UI.");
Flush(); Flush();
SpriteRenderer.SetAntialiasingPixelsPerTexel(Window.EffectiveWindowScale); SpriteRenderer.SetAntialiasingPixelsPerTexel(Window.EffectiveWindowScale);
@@ -400,7 +400,7 @@ namespace OpenRA
public void DisableAntialiasingFilter() public void DisableAntialiasingFilter()
{ {
if (renderType != RenderType.UI) if (renderType != RenderType.UI)
throw new InvalidOperationException("EndFrame called with renderType = {0}, expected RenderType.UI.".F(renderType)); throw new InvalidOperationException($"EndFrame called with renderType = {renderType}, expected RenderType.UI.");
Flush(); Flush();
SpriteRenderer.SetAntialiasingPixelsPerTexel(0); SpriteRenderer.SetAntialiasingPixelsPerTexel(0);

View File

@@ -18,14 +18,14 @@ namespace OpenRA.Scripting
{ {
readonly Actor actor; readonly Actor actor;
protected override string DuplicateKeyError(string memberName) { return "Actor '{0}' defines the command '{1}' on multiple traits".F(actor.Info.Name, memberName); } protected override string DuplicateKeyError(string memberName) { return $"Actor '{actor.Info.Name}' defines the command '{memberName}' on multiple traits"; }
protected override string MemberNotFoundError(string memberName) protected override string MemberNotFoundError(string memberName)
{ {
var actorName = actor.Info.Name; var actorName = actor.Info.Name;
if (actor.IsDead) if (actor.IsDead)
actorName += " (dead)"; actorName += " (dead)";
return "Actor '{0}' does not define a property '{1}'".F(actorName, memberName); return $"Actor '{actorName}' does not define a property '{memberName}'";
} }
public ScriptActorInterface(ScriptContext context, Actor actor) public ScriptActorInterface(ScriptContext context, Actor actor)

View File

@@ -81,8 +81,8 @@ namespace OpenRA.Scripting
/// </remarks> /// </remarks>
public abstract class ScriptGlobal : ScriptObjectWrapper public abstract class ScriptGlobal : ScriptObjectWrapper
{ {
protected override string DuplicateKeyError(string memberName) { return "Table '{0}' defines multiple members '{1}'".F(Name, memberName); } protected override string DuplicateKeyError(string memberName) { return $"Table '{Name}' defines multiple members '{memberName}'"; }
protected override string MemberNotFoundError(string memberName) { return "Table '{0}' does not define a property '{1}'".F(Name, memberName); } protected override string MemberNotFoundError(string memberName) { return $"Table '{Name}' does not define a property '{memberName}'"; }
public readonly string Name; public readonly string Name;
public ScriptGlobal(ScriptContext context) public ScriptGlobal(ScriptContext context)
@@ -92,7 +92,7 @@ namespace OpenRA.Scripting
var type = GetType(); var type = GetType();
var names = type.GetCustomAttributes<ScriptGlobalAttribute>(true); var names = type.GetCustomAttributes<ScriptGlobalAttribute>(true);
if (names.Length != 1) if (names.Length != 1)
throw new InvalidOperationException("[ScriptGlobal] attribute not found for global table '{0}'".F(type)); throw new InvalidOperationException($"[ScriptGlobal] attribute not found for global table '{type}'");
Name = names.First().Name; Name = names.First().Name;
Bind(new[] { this }); Bind(new[] { this });
@@ -187,7 +187,7 @@ namespace OpenRA.Scripting
}); });
if (ctor == null) if (ctor == null)
throw new InvalidOperationException("{0} must define a constructor that takes a ScriptContext context parameter".F(b.Name)); throw new InvalidOperationException($"{b.Name} must define a constructor that takes a ScriptContext context parameter");
var binding = (ScriptGlobal)ctor.Invoke(new[] { this }); var binding = (ScriptGlobal)ctor.Invoke(new[] { this });
using (var obj = binding.ToLuaValue(this)) using (var obj = binding.ToLuaValue(this))
@@ -236,7 +236,7 @@ namespace OpenRA.Scripting
using (var registerGlobal = (LuaFunction)runtime.Globals["RegisterSandboxedGlobal"]) using (var registerGlobal = (LuaFunction)runtime.Globals["RegisterSandboxedGlobal"])
{ {
if (runtime.Globals.ContainsKey(name)) if (runtime.Globals.ContainsKey(name))
throw new LuaException("The global name '{0}' is reserved, and may not be used by a map actor".F(name)); throw new LuaException($"The global name '{name}' is reserved, and may not be used by a map actor");
using (var obj = a.ToLuaValue(this)) using (var obj = a.ToLuaValue(this))
registerGlobal.Call(name, obj).Dispose(); registerGlobal.Call(name, obj).Dispose();

View File

@@ -32,16 +32,16 @@ namespace OpenRA.Scripting
ret = t.Name; ret = t.Name;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
ret = "{0}?".F(t.GetGenericArguments().Select(p => p.Name).First()); ret = $"{t.GetGenericArguments().Select(p => p.Name).First()}?";
return ret; return ret;
} }
public static string LuaDocString(this ParameterInfo pi) public static string LuaDocString(this ParameterInfo pi)
{ {
var ret = "{0} {1}".F(pi.ParameterType.LuaDocString(), pi.Name); var ret = $"{pi.ParameterType.LuaDocString()} {pi.Name}";
if (pi.IsOptional) if (pi.IsOptional)
ret += " = {0}".F(pi.DefaultValue != null ? pi.DefaultValue : "nil"); ret += $" = {pi.DefaultValue ?? "nil"}";
return ret; return ret;
} }
@@ -52,7 +52,7 @@ namespace OpenRA.Scripting
if (methodInfo != null) if (methodInfo != null)
{ {
var parameters = methodInfo.GetParameters().Select(pi => pi.LuaDocString()); var parameters = methodInfo.GetParameters().Select(pi => pi.LuaDocString());
return "{0} {1}({2})".F(methodInfo.ReturnType.LuaDocString(), mi.Name, parameters.JoinWith(", ")); return $"{methodInfo.ReturnType.LuaDocString()} {mi.Name}({parameters.JoinWith(", ")})";
} }
var propertyInfo = mi as PropertyInfo; var propertyInfo = mi as PropertyInfo;
@@ -64,10 +64,10 @@ namespace OpenRA.Scripting
if (propertyInfo.GetSetMethod() != null) if (propertyInfo.GetSetMethod() != null)
types.Add("set;"); types.Add("set;");
return "{0} {1} {{ {2} }}".F(propertyInfo.PropertyType.LuaDocString(), mi.Name, types.JoinWith(" ")); return $"{propertyInfo.PropertyType.LuaDocString()} {mi.Name} {{ {types.JoinWith(" ")} }}";
} }
return "Unknown field: {0}".F(mi.Name); return $"Unknown field: {mi.Name}";
} }
} }
} }

View File

@@ -62,14 +62,14 @@ namespace OpenRA.Scripting
if (i >= argCount) if (i >= argCount)
{ {
if (!pi[i].IsOptional) if (!pi[i].IsOptional)
throw new LuaException("Argument '{0}' of '{1}' is not optional.".F(pi[i].LuaDocString(), Member.LuaDocString())); throw new LuaException($"Argument '{pi[i].LuaDocString()}' of '{Member.LuaDocString()}' is not optional.");
clrArgs[i] = pi[i].DefaultValue; clrArgs[i] = pi[i].DefaultValue;
continue; continue;
} }
if (!args[i].TryGetClrValue(pi[i].ParameterType, out clrArgs[i])) if (!args[i].TryGetClrValue(pi[i].ParameterType, out clrArgs[i]))
throw new LuaException("Unable to convert parameter {0} to {1}".F(i, pi[i].ParameterType.Name)); throw new LuaException($"Unable to convert parameter {i} to {pi[i].ParameterType.Name}");
} }
return mi.Invoke(Target, clrArgs).ToLuaValue(context); return mi.Invoke(Target, clrArgs).ToLuaValue(context);
@@ -105,7 +105,7 @@ namespace OpenRA.Scripting
if (IsGetProperty) if (IsGetProperty)
return ((PropertyInfo)Member).GetValue(Target, null).ToLuaValue(context); return ((PropertyInfo)Member).GetValue(Target, null).ToLuaValue(context);
throw new LuaException("The property '{0}' is write-only".F(Member.Name)); throw new LuaException($"The property '{Member.Name}' is write-only");
} }
public void Set(LuaRuntime runtime, LuaValue value) public void Set(LuaRuntime runtime, LuaValue value)
@@ -114,12 +114,12 @@ namespace OpenRA.Scripting
{ {
var pi = (PropertyInfo)Member; var pi = (PropertyInfo)Member;
if (!value.TryGetClrValue(pi.PropertyType, out var clrValue)) if (!value.TryGetClrValue(pi.PropertyType, out var clrValue))
throw new LuaException("Unable to convert '{0}' to Clr type '{1}'".F(value.WrappedClrType().Name, pi.PropertyType)); throw new LuaException($"Unable to convert '{value.WrappedClrType().Name}' to Clr type '{pi.PropertyType}'");
pi.SetValue(Target, clrValue, null); pi.SetValue(Target, clrValue, null);
} }
else else
throw new LuaException("The property '{0}' is read-only".F(Member.Name)); throw new LuaException($"The property '{Member.Name}' is read-only");
} }
public static IEnumerable<MemberInfo> WrappableMembers(Type t) public static IEnumerable<MemberInfo> WrappableMembers(Type t)

View File

@@ -18,8 +18,8 @@ namespace OpenRA.Scripting
{ {
readonly Player player; readonly Player player;
protected override string DuplicateKeyError(string memberName) { return "Player '{0}' defines the command '{1}' on multiple traits".F(player.PlayerName, memberName); } protected override string DuplicateKeyError(string memberName) { return $"Player '{player.PlayerName}' defines the command '{memberName}' on multiple traits"; }
protected override string MemberNotFoundError(string memberName) { return "Player '{0}' does not define a property '{1}'".F(player.PlayerName, memberName); } protected override string MemberNotFoundError(string memberName) { return $"Player '{player.PlayerName}' does not define a property '{memberName}'"; }
public ScriptPlayerInterface(ScriptContext context, Player player) public ScriptPlayerInterface(ScriptContext context, Player player)
: base(context) : base(context)

View File

@@ -126,7 +126,7 @@ namespace OpenRA.Scripting
if (!elementHasClrValue || !(element is LuaValue)) if (!elementHasClrValue || !(element is LuaValue))
kv.Value.Dispose(); kv.Value.Dispose();
if (!elementHasClrValue) if (!elementHasClrValue)
throw new LuaException("Unable to convert table value of type {0} to type {1}".F(kv.Value.WrappedClrType(), innerType)); throw new LuaException($"Unable to convert table value of type {kv.Value.WrappedClrType()} to type {innerType}");
} }
array.SetValue(element, i++); array.SetValue(element, i++);
@@ -186,7 +186,7 @@ namespace OpenRA.Scripting
return table; return table;
} }
throw new InvalidOperationException("Cannot convert type '{0}' to Lua. Class must implement IScriptBindable.".F(obj.GetType())); throw new InvalidOperationException($"Cannot convert type '{obj.GetType()}' to Lua. Class must implement IScriptBindable.");
} }
} }
} }

View File

@@ -494,7 +494,7 @@ namespace OpenRA.Server
if (bans.Contains(client.IPAddress)) if (bans.Contains(client.IPAddress))
{ {
Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint); Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint);
SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IPAddress) ? "banned" : "temporarily banned")); SendOrderTo(newConn, "ServerError", $"You have been {(Settings.Ban.Contains(client.IPAddress) ? "banned" : "temporarily banned")} from the server");
DropClient(newConn); DropClient(newConn);
return; return;
} }
@@ -543,7 +543,7 @@ namespace OpenRA.Server
client.Name, newConn.Socket.RemoteEndPoint); client.Name, newConn.Socket.RemoteEndPoint);
// Report to all other players // Report to all other players
SendMessage("{0} has joined the game.".F(client.Name), newConn); SendMessage($"{client.Name} has joined the game.", newConn);
// Send initial ping // Send initial ping
SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture));
@@ -816,7 +816,7 @@ namespace OpenRA.Server
if (data.Length == Order.SyncHashOrderLength) if (data.Length == Order.SyncHashOrderLength)
HandleSyncOrder(frame, data); HandleSyncOrder(frame, data);
else else
Log.Write("server", "Dropped sync order with length {0} from client {1}. Expected length {2}.".F(data.Length, from, Order.SyncHashOrderLength)); Log.Write("server", $"Dropped sync order with length {data.Length} from client {from}. Expected length {Order.SyncHashOrderLength}.");
} }
} }
} }
@@ -860,7 +860,7 @@ namespace OpenRA.Server
DispatchOrdersToClients(conn, 0, Order.FromTargetString("Message", text, true).Serialize()); DispatchOrdersToClients(conn, 0, Order.FromTargetString("Message", text, true).Serialize());
if (Type == ServerType.Dedicated) if (Type == ServerType.Dedicated)
Console.WriteLine("[{0}] {1}".F(DateTime.Now.ToString(Settings.TimestampFormat), text)); Console.WriteLine($"[{DateTime.Now.ToString(Settings.TimestampFormat)}] {text}");
} }
void InterpretServerOrder(Connection conn, Order o) void InterpretServerOrder(Connection conn, Order o)
@@ -894,7 +894,7 @@ namespace OpenRA.Server
if (handledBy == null) if (handledBy == null)
{ {
Log.Write("server", "Unknown server command: {0}", o.TargetString); Log.Write("server", "Unknown server command: {0}", o.TargetString);
SendOrderTo(conn, "Message", "Unknown server command: {0}".F(o.TargetString)); SendOrderTo(conn, "Message", $"Unknown server command: {o.TargetString}");
} }
break; break;
@@ -1070,8 +1070,8 @@ namespace OpenRA.Server
var suffix = ""; var suffix = "";
if (State == ServerState.GameStarted) if (State == ServerState.GameStarted)
suffix = dropClient.IsObserver ? " (Spectator)" : dropClient.Team != 0 ? " (Team {0})".F(dropClient.Team) : ""; suffix = dropClient.IsObserver ? " (Spectator)" : dropClient.Team != 0 ? $" (Team {dropClient.Team})" : "";
SendMessage("{0}{1} has disconnected.".F(dropClient.Name, suffix)); SendMessage($"{dropClient.Name}{suffix} has disconnected.");
// Send disconnected order, even if still in the lobby // Send disconnected order, even if still in the lobby
DispatchOrdersToClients(toDrop, 0, Order.FromTargetString("Disconnected", "", true).Serialize()); DispatchOrdersToClients(toDrop, 0, Order.FromTargetString("Disconnected", "", true).Serialize());
@@ -1098,7 +1098,7 @@ namespace OpenRA.Server
if (nextAdmin != null) if (nextAdmin != null)
{ {
nextAdmin.IsAdmin = true; nextAdmin.IsAdmin = true;
SendMessage("{0} is now the admin.".F(nextAdmin.Name)); SendMessage($"{nextAdmin.Name} is now the admin.");
} }
} }

View File

@@ -304,7 +304,7 @@ namespace OpenRA
var err2 = FieldLoader.InvalidValueAction; var err2 = FieldLoader.InvalidValueAction;
try try
{ {
FieldLoader.UnknownFieldAction = (s, f) => Console.WriteLine("Ignoring unknown field `{0}` on `{1}`".F(s, f.Name)); FieldLoader.UnknownFieldAction = (s, f) => Console.WriteLine($"Ignoring unknown field `{s}` on `{f.Name}`");
if (File.Exists(settingsFile)) if (File.Exists(settingsFile))
{ {
@@ -430,7 +430,7 @@ namespace OpenRA
FieldLoader.InvalidValueAction = (s, t, f) => FieldLoader.InvalidValueAction = (s, t, f) =>
{ {
var ret = defaults.GetType().GetField(f).GetValue(defaults); var ret = defaults.GetType().GetField(f).GetValue(defaults);
Console.WriteLine("FieldLoader: Cannot parse `{0}` into `{2}:{1}`; substituting default `{3}`".F(s, t.Name, f, ret)); Console.WriteLine($"FieldLoader: Cannot parse `{s}` into `{f}:{t.Name}`; substituting default `{ret}`");
return ret; return ret;
}; };

View File

@@ -353,14 +353,14 @@ namespace OpenRA
if (voicedActor != null) if (voicedActor != null)
{ {
if (!rules.VoicePools.Value.ContainsKey(definition)) if (!rules.VoicePools.Value.ContainsKey(definition))
throw new InvalidOperationException("Can't find {0} in voice pool.".F(definition)); throw new InvalidOperationException($"Can't find {definition} in voice pool.");
pool = rules.VoicePools.Value[definition]; pool = rules.VoicePools.Value[definition];
} }
else else
{ {
if (!rules.NotificationsPools.Value.ContainsKey(definition)) if (!rules.NotificationsPools.Value.ContainsKey(definition))
throw new InvalidOperationException("Can't find {0} in notification pool.".F(definition)); throw new InvalidOperationException($"Can't find {definition} in notification pool.");
pool = rules.NotificationsPools.Value[definition]; pool = rules.NotificationsPools.Value[definition];
} }

View File

@@ -151,7 +151,7 @@ namespace OpenRA
{ {
var length = s.ReadInt32(); var length = s.ReadInt32();
if (length > maxLength) if (length > maxLength)
throw new InvalidOperationException("The length of the string ({0}) is longer than the maximum allowed ({1}).".F(length, maxLength)); throw new InvalidOperationException($"The length of the string ({length}) is longer than the maximum allowed ({maxLength}).");
return encoding.GetString(s.ReadBytes(length)); return encoding.GetString(s.ReadBytes(length));
} }

View File

@@ -46,11 +46,11 @@ namespace OpenRA.Support
foreach (var sample in samples) foreach (var sample in samples)
{ {
var name = sample.Key; var name = sample.Key;
Log.AddChannel(name, "{0}{1}.csv".F(prefix, name)); Log.AddChannel(name, $"{prefix}{name}.csv");
Log.Write(name, "tick,time [ms]"); Log.Write(name, "tick,time [ms]");
foreach (var point in sample.Value) foreach (var point in sample.Value)
Log.Write(name, "{0},{1}".F(point.Tick, point.Value)); Log.Write(name, $"{point.Tick},{point.Value}");
} }
} }

View File

@@ -66,7 +66,7 @@ namespace OpenRA.Support
else if (char.IsLetter(t[0])) else if (char.IsLetter(t[0]))
{ {
if (!syms.ContainsKey(t)) if (!syms.ContainsKey(t))
throw new InvalidOperationException("Substitution `{0}` undefined".F(t)); throw new InvalidOperationException($"Substitution `{t}` undefined");
yield return syms[t].ToString(); yield return syms[t].ToString();
} }

View File

@@ -121,9 +121,9 @@ namespace OpenRA
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
for (var i = 0; i < CreateLogFileMaxRetryCount; i++) for (var i = 0; i < CreateLogFileMaxRetryCount; i++)
yield return Path.Combine(path, i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename); yield return Path.Combine(path, i > 0 ? $"{baseFilename}.{i}" : baseFilename);
throw new ApplicationException("Error creating log file \"{0}\"".F(baseFilename)); throw new ApplicationException($"Error creating log file \"{baseFilename}\"");
} }
static ChannelInfo GetChannel(string channelName) static ChannelInfo GetChannel(string channelName)

View File

@@ -287,8 +287,7 @@ namespace OpenRA.Support
continue; continue;
} }
throw new InvalidProgramException("CreateTokenTypeInfoEnumeration is missing a TokenTypeInfo entry for TokenType.{0}".F( throw new InvalidProgramException($"CreateTokenTypeInfoEnumeration is missing a TokenTypeInfo entry for TokenType.{Enum<TokenType>.GetValues()[i]}");
Enum<TokenType>.GetValues()[i]));
} }
} }
@@ -355,8 +354,7 @@ namespace OpenRA.Support
if (cc != CharClass.Digit) if (cc != CharClass.Digit)
{ {
if (cc != CharClass.Whitespace && cc != CharClass.Operator && cc != CharClass.Mixed) if (cc != CharClass.Whitespace && cc != CharClass.Operator && cc != CharClass.Mixed)
throw new InvalidDataException("Number {0} and variable merged at index {1}".F( throw new InvalidDataException($"Number {int.Parse(expression.Substring(start, i - start))} and variable merged at index {start}");
int.Parse(expression.Substring(start, i - start)), start));
return true; return true;
} }
@@ -371,8 +369,7 @@ namespace OpenRA.Support
static TokenType VariableOrKeyword(string expression, int start, ref int i) static TokenType VariableOrKeyword(string expression, int start, ref int i)
{ {
if (CharClassOf(expression[i - 1]) == CharClass.Mixed) if (CharClassOf(expression[i - 1]) == CharClass.Mixed)
throw new InvalidDataException("Invalid identifier end character at index {0} for `{1}`".F( throw new InvalidDataException($"Invalid identifier end character at index {i - 1} for `{expression.Substring(start, i - start)}`");
i - 1, expression.Substring(start, i - start)));
return VariableOrKeyword(expression, start, i - start); return VariableOrKeyword(expression, start, i - start);
} }
@@ -435,7 +432,7 @@ namespace OpenRA.Support
return TokenType.Equals; return TokenType.Equals;
} }
throw new InvalidDataException("Unexpected character '=' at index {0} - should it be `==`?".F(start)); throw new InvalidDataException($"Unexpected character '=' at index {start} - should it be `==`?");
case '&': case '&':
i++; i++;
@@ -445,7 +442,7 @@ namespace OpenRA.Support
return TokenType.And; return TokenType.And;
} }
throw new InvalidDataException("Unexpected character '&' at index {0} - should it be `&&`?".F(start)); throw new InvalidDataException($"Unexpected character '&' at index {start} - should it be `&&`?");
case '|': case '|':
i++; i++;
@@ -455,7 +452,7 @@ namespace OpenRA.Support
return TokenType.Or; return TokenType.Or;
} }
throw new InvalidDataException("Unexpected character '|' at index {0} - should it be `||`?".F(start)); throw new InvalidDataException($"Unexpected character '|' at index {start} - should it be `||`?");
case '(': case '(':
i++; i++;
@@ -500,7 +497,7 @@ namespace OpenRA.Support
var cc = CharClassOf(expression[start]); var cc = CharClassOf(expression[start]);
if (cc != CharClass.Id) if (cc != CharClass.Id)
throw new InvalidDataException("Invalid character '{0}' at index {1}".F(expression[i], start)); throw new InvalidDataException($"Invalid character '{expression[i]}' at index {start}");
// Scan forwards until we find an invalid name character // Scan forwards until we find an invalid name character
for (i = start; i < expression.Length; i++) for (i = start; i < expression.Length; i++)
@@ -532,15 +529,13 @@ namespace OpenRA.Support
else if (lastType == TokenType.Invalid) else if (lastType == TokenType.Invalid)
whitespaceBefore = true; whitespaceBefore = true;
else if (RequiresWhitespaceAfter(lastType)) else if (RequiresWhitespaceAfter(lastType))
throw new InvalidDataException("Missing whitespace at index {0}, after `{1}` operator." throw new InvalidDataException($"Missing whitespace at index {i}, after `{GetTokenSymbol(lastType)}` operator.");
.F(i, GetTokenSymbol(lastType)));
var start = i; var start = i;
var type = GetNextType(expression, ref i, lastType); var type = GetNextType(expression, ref i, lastType);
if (!whitespaceBefore && RequiresWhitespaceBefore(type)) if (!whitespaceBefore && RequiresWhitespaceBefore(type))
throw new InvalidDataException("Missing whitespace at index {0}, before `{1}` operator." throw new InvalidDataException($"Missing whitespace at index {i}, before `{GetTokenSymbol(type)}` operator.");
.F(i, GetTokenSymbol(type)));
switch (type) switch (type)
{ {
@@ -602,7 +597,7 @@ namespace OpenRA.Support
// Expressions can't end with a binary or unary prefix operation // Expressions can't end with a binary or unary prefix operation
if (lastToken.RightOperand) if (lastToken.RightOperand)
throw new InvalidDataException("Missing value or sub-expression at end for `{0}` operator".F(lastToken.Symbol)); throw new InvalidDataException($"Missing value or sub-expression at end for `{lastToken.Symbol}` operator");
break; break;
} }
@@ -610,7 +605,7 @@ namespace OpenRA.Support
if (token.Closes != Grouping.None) if (token.Closes != Grouping.None)
{ {
if (currentOpeners.Count == 0) if (currentOpeners.Count == 0)
throw new InvalidDataException("Unmatched closing parenthesis at index {0}".F(token.Index)); throw new InvalidDataException($"Unmatched closing parenthesis at index {token.Index}");
currentOpeners.Pop(); currentOpeners.Pop();
} }
@@ -622,22 +617,20 @@ namespace OpenRA.Support
{ {
// Expressions can't start with a binary or unary postfix operation or closer // Expressions can't start with a binary or unary postfix operation or closer
if (token.LeftOperand) if (token.LeftOperand)
throw new InvalidDataException("Missing value or sub-expression at beginning for `{0}` operator".F(token.Symbol)); throw new InvalidDataException($"Missing value or sub-expression at beginning for `{token.Symbol}` operator");
} }
else else
{ {
// Disallow empty parentheses // Disallow empty parentheses
if (lastToken.Opens != Grouping.None && token.Closes != Grouping.None) if (lastToken.Opens != Grouping.None && token.Closes != Grouping.None)
throw new InvalidDataException("Empty parenthesis at index {0}".F(lastToken.Index)); throw new InvalidDataException($"Empty parenthesis at index {lastToken.Index}");
// Exactly one of two consective tokens must take the other's sub-expression evaluation as an operand // Exactly one of two consective tokens must take the other's sub-expression evaluation as an operand
if (lastToken.RightOperand == token.LeftOperand) if (lastToken.RightOperand == token.LeftOperand)
{ {
if (lastToken.RightOperand) if (lastToken.RightOperand)
throw new InvalidDataException( throw new InvalidDataException($"Missing value or sub-expression or there is an extra operator `{lastToken.Symbol}` at index {lastToken.Index} or `{token.Symbol}` at index {token.Index}");
"Missing value or sub-expression or there is an extra operator `{0}` at index {1} or `{2}` at index {3}".F( throw new InvalidDataException($"Missing binary operation before `{token.Symbol}` at index {token.Index}");
lastToken.Symbol, lastToken.Index, token.Symbol, token.Index));
throw new InvalidDataException("Missing binary operation before `{0}` at index {1}".F(token.Symbol, token.Index));
} }
} }
@@ -649,7 +642,7 @@ namespace OpenRA.Support
} }
if (currentOpeners.Count > 0) if (currentOpeners.Count > 0)
throw new InvalidDataException("Unclosed opening parenthesis at index {0}".F(currentOpeners.Peek().Index)); throw new InvalidDataException($"Unclosed opening parenthesis at index {currentOpeners.Peek().Index}");
return new Compiler().Build(ToPostfix(tokens).ToArray(), resultType); return new Compiler().Build(ToPostfix(tokens).ToArray(), resultType);
} }
@@ -743,8 +736,7 @@ namespace OpenRA.Support
return IfThenElse(expression, One, Zero); return IfThenElse(expression, One, Zero);
} }
throw new InvalidProgramException("Unable to convert ExpressionType.{0} to ExpressionType.{1}".F( throw new InvalidProgramException($"Unable to convert ExpressionType.{Enum<ExpressionType>.GetValues()[(int)fromType]} to ExpressionType.{Enum<ExpressionType>.GetValues()[(int)toType]}");
Enum<ExpressionType>.GetValues()[(int)fromType], Enum<ExpressionType>.GetValues()[(int)toType]));
} }
public Expression Pop(ExpressionType type) public Expression Pop(ExpressionType type)
@@ -760,11 +752,11 @@ namespace OpenRA.Support
expressions.Add(expression); expressions.Add(expression);
if (type == ExpressionType.Int) if (type == ExpressionType.Int)
if (expression.Type != typeof(int)) if (expression.Type != typeof(int))
throw new InvalidOperationException("Expected System.Int type instead of {0} for {1}".F(expression.Type, expression)); throw new InvalidOperationException($"Expected System.Int type instead of {expression.Type} for {expression}");
if (type == ExpressionType.Bool) if (type == ExpressionType.Bool)
if (expression.Type != typeof(bool)) if (expression.Type != typeof(bool))
throw new InvalidOperationException("Expected System.Boolean type instead of {0} for {1}".F(expression.Type, expression)); throw new InvalidOperationException($"Expected System.Boolean type instead of {expression.Type} for {expression}");
types.Add(type); types.Add(type);
} }
@@ -776,7 +768,7 @@ namespace OpenRA.Support
else if (expression.Type == typeof(bool)) else if (expression.Type == typeof(bool))
types.Add(ExpressionType.Bool); types.Add(ExpressionType.Bool);
else else
throw new InvalidOperationException("Unhandled result type {0} for {1}".F(expression.Type, expression)); throw new InvalidOperationException($"Unhandled result type {expression.Type} for {expression}");
} }
} }
@@ -943,9 +935,7 @@ namespace OpenRA.Support
} }
default: default:
throw new InvalidProgramException( throw new InvalidProgramException($"ConditionExpression.Compiler.Compile() is missing an expression builder for TokenType.{Enum<TokenType>.GetValues()[(int)t.Type]}");
"ConditionExpression.Compiler.Compile() is missing an expression builder for TokenType.{0}".F(
Enum<TokenType>.GetValues()[(int)t.Type]));
} }
} }

View File

@@ -69,14 +69,14 @@ namespace OpenRA
il.MarkLabel(l); il.MarkLabel(l);
} }
else if (type != typeof(int)) else if (type != typeof(int))
throw new NotImplementedException("SyncAttribute on member of unhashable type: {0}".F(type.FullName)); throw new NotImplementedException($"SyncAttribute on member of unhashable type: {type.FullName}");
il.Emit(OpCodes.Xor); il.Emit(OpCodes.Xor);
} }
static Func<object, int> GenerateHashFunc(Type t) static Func<object, int> GenerateHashFunc(Type t)
{ {
var d = new DynamicMethod("hash_{0}".F(t.Name), typeof(int), new Type[] { typeof(object) }, t); var d = new DynamicMethod($"hash_{t.Name}", typeof(int), new Type[] { typeof(object) }, t);
var il = d.GetILGenerator(); var il = d.GetILGenerator();
var this_ = il.DeclareLocal(t).LocalIndex; var this_ = il.DeclareLocal(t).LocalIndex;
il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_0);

View File

@@ -81,7 +81,7 @@ namespace OpenRA
static void CheckDestroyed(Actor actor) static void CheckDestroyed(Actor actor)
{ {
if (actor.Disposed) if (actor.Disposed)
throw new InvalidOperationException("Attempted to get trait from destroyed object ({0})".F(actor)); throw new InvalidOperationException($"Attempted to get trait from destroyed object ({actor})");
} }
public T Get<T>(Actor actor) public T Get<T>(Actor actor)
@@ -160,7 +160,7 @@ namespace OpenRA
{ {
var result = GetOrDefault(actor); var result = GetOrDefault(actor);
if (result == null) if (result == null)
throw new InvalidOperationException("Actor {0} does not have trait of type `{1}`".F(actor.Info.Name, typeof(T))); throw new InvalidOperationException($"Actor {actor.Info.Name} does not have trait of type `{typeof(T)}`");
return result; return result;
} }
@@ -173,7 +173,7 @@ namespace OpenRA
return default; return default;
if (index + 1 < actors.Count && actors[index + 1] == actor) if (index + 1 < actors.Count && actors[index + 1] == actor)
throw new InvalidOperationException("Actor {0} has multiple traits of type `{1}`".F(actor.Info.Name, typeof(T))); throw new InvalidOperationException($"Actor {actor.Info.Name} has multiple traits of type `{typeof(T)}`");
return traits[index]; return traits[index];
} }

View File

@@ -203,7 +203,7 @@ namespace OpenRA.Traits
public override string ToString() public override string ToString()
{ {
return "{0} {1}{2}".F(Info.Name, ID, IsValid ? "" : " (invalid)"); return $"{Info.Name} {ID}{(IsValid ? "" : " (invalid)")}";
} }
} }

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Traits
public override int GetHashCode() { return Actor.GetHashCode() ^ Bounds.GetHashCode(); } public override int GetHashCode() { return Actor.GetHashCode() ^ Bounds.GetHashCode(); }
public override string ToString() { return "{0}->{1}".F(Actor.Info.Name, Bounds.GetType().Name); } public override string ToString() { return $"{Actor.Info.Name}->{Bounds.GetType().Name}"; }
} }
[TraitLocation(SystemActors.World | SystemActors.EditorWorld)] [TraitLocation(SystemActors.World | SystemActors.EditorWorld)]

View File

@@ -104,13 +104,13 @@ namespace OpenRA
name = args[i] as string; name = args[i] as string;
if (string.IsNullOrEmpty(name)) if (string.IsNullOrEmpty(name))
{ {
throw new ArgumentException("Expected the argument at index {0} to be a non-empty string".F(i), throw new ArgumentException($"Expected the argument at index {i} to be a non-empty string",
nameof(args)); nameof(args));
} }
value = args[i + 1]; value = args[i + 1];
if (value == null) if (value == null)
throw new ArgumentNullException("args", "Expected the argument at index {0} to be a non-null value".F(i + 1)); throw new ArgumentNullException("args", $"Expected the argument at index {i + 1} to be a non-null value");
argumentDictionary.Add(name, value); argumentDictionary.Add(name, value);
} }

View File

@@ -85,7 +85,7 @@ namespace OpenRA
public static WAngle ArcSin(int d) public static WAngle ArcSin(int d)
{ {
if (d < -1024 || d > 1024) if (d < -1024 || d > 1024)
throw new ArgumentException("ArcSin is only valid for values between -1024 and 1024. Received {0}".F(d)); throw new ArgumentException($"ArcSin is only valid for values between -1024 and 1024. Received {d}");
var a = ClosestCosineIndex(Math.Abs(d)); var a = ClosestCosineIndex(Math.Abs(d));
return new WAngle(d < 0 ? 768 + a : 256 - a); return new WAngle(d < 0 ? 768 + a : 256 - a);
@@ -94,7 +94,7 @@ namespace OpenRA
public static WAngle ArcCos(int d) public static WAngle ArcCos(int d)
{ {
if (d < -1024 || d > 1024) if (d < -1024 || d > 1024)
throw new ArgumentException("ArcCos is only valid for values between -1024 and 1024. Received {0}".F(d)); throw new ArgumentException($"ArcCos is only valid for values between -1024 and 1024. Received {d}");
var a = ClosestCosineIndex(Math.Abs(d)); var a = ClosestCosineIndex(Math.Abs(d));
return new WAngle(d < 0 ? 512 - a : a); return new WAngle(d < 0 ? 512 - a : a);
@@ -222,7 +222,7 @@ namespace OpenRA
public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out WAngle a)) if (!left.TryGetClrValue(out WAngle a))
throw new LuaException("Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
if (right.TryGetClrValue(out int c)) if (right.TryGetClrValue(out int c))
{ {
@@ -233,13 +233,13 @@ namespace OpenRA
if (right.TryGetClrValue(out WAngle b)) if (right.TryGetClrValue(out WAngle b))
return new LuaCustomClrObject(a + b); return new LuaCustomClrObject(a + b);
throw new LuaException("Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
} }
public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out WAngle a)) if (!left.TryGetClrValue(out WAngle a))
throw new LuaException("Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
if (right.TryGetClrValue(out int c)) if (right.TryGetClrValue(out int c))
{ {
@@ -250,7 +250,7 @@ namespace OpenRA
if (right.TryGetClrValue(out WAngle b)) if (right.TryGetClrValue(out WAngle b))
return new LuaCustomClrObject(a - b); return new LuaCustomClrObject(a - b);
throw new LuaException("Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
} }
public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right)

View File

@@ -144,7 +144,7 @@ namespace OpenRA
{ {
case "Length": return Length; case "Length": return Length;
case "Range": Game.Debug("WDist.Range is deprecated. Use WDist.Length instead"); return Length; case "Range": Game.Debug("WDist.Range is deprecated. Use WDist.Length instead"); return Length;
default: throw new LuaException("WDist does not define a member '{0}'".F(key)); default: throw new LuaException($"WDist does not define a member '{key}'");
} }
} }

View File

@@ -83,7 +83,7 @@ namespace OpenRA
public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out WPos a) || !right.TryGetClrValue(out WVec b)) if (!left.TryGetClrValue(out WPos a) || !right.TryGetClrValue(out WVec b))
throw new LuaException("Attempted to call WPos.Add(WPos, WVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WPos.Add(WPos, WVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
return new LuaCustomClrObject(a + b); return new LuaCustomClrObject(a + b);
} }
@@ -92,7 +92,7 @@ namespace OpenRA
{ {
var rightType = right.WrappedClrType(); var rightType = right.WrappedClrType();
if (!left.TryGetClrValue(out WPos a)) if (!left.TryGetClrValue(out WPos a))
throw new LuaException("Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); throw new LuaException($"Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})");
if (rightType == typeof(WPos)) if (rightType == typeof(WPos))
{ {
@@ -105,7 +105,7 @@ namespace OpenRA
return new LuaCustomClrObject(a - b); return new LuaCustomClrObject(a - b);
} }
throw new LuaException("Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); throw new LuaException($"Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})");
} }
public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right)
@@ -125,7 +125,7 @@ namespace OpenRA
case "X": return X; case "X": return X;
case "Y": return Y; case "Y": return Y;
case "Z": return Z; case "Z": return Z;
default: throw new LuaException("WPos does not define a member '{0}'".F(key)); default: throw new LuaException($"WPos does not define a member '{key}'");
} }
} }

View File

@@ -111,7 +111,7 @@ namespace OpenRA
public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out WVec a) || !right.TryGetClrValue(out WVec b)) if (!left.TryGetClrValue(out WVec a) || !right.TryGetClrValue(out WVec b))
throw new LuaException("Attempted to call WVec.Add(WVec, WVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WVec.Add(WVec, WVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
return new LuaCustomClrObject(a + b); return new LuaCustomClrObject(a + b);
} }
@@ -119,7 +119,7 @@ namespace OpenRA
public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right) public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right)
{ {
if (!left.TryGetClrValue(out WVec a) || !right.TryGetClrValue(out WVec b)) if (!left.TryGetClrValue(out WVec a) || !right.TryGetClrValue(out WVec b))
throw new LuaException("Attempted to call WVec.Subtract(WVec, WVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); throw new LuaException($"Attempted to call WVec.Subtract(WVec, WVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})");
return new LuaCustomClrObject(a - b); return new LuaCustomClrObject(a - b);
} }
@@ -147,7 +147,7 @@ namespace OpenRA
case "Y": return Y; case "Y": return Y;
case "Z": return Z; case "Z": return Z;
case "Facing": return new LuaCustomClrObject(Yaw); case "Facing": return new LuaCustomClrObject(Yaw);
default: throw new LuaException("WVec does not define a member '{0}'".F(key)); default: throw new LuaException($"WVec does not define a member '{key}'");
} }
} }

View File

@@ -80,7 +80,7 @@ namespace OpenRA.Widgets
if (LoadWidget(id, parent, args) is T widget) if (LoadWidget(id, parent, args) is T widget)
return widget; return widget;
throw new InvalidOperationException("Widget {0} is not of type {1}".F(id, typeof(T).Name)); throw new InvalidOperationException($"Widget {id} is not of type {typeof(T).Name}");
} }
public static Widget LoadWidget(string id, Widget parent, WidgetArgs args) public static Widget LoadWidget(string id, Widget parent, WidgetArgs args)
@@ -236,7 +236,7 @@ namespace OpenRA.Widgets
public virtual Widget Clone() public virtual Widget Clone()
{ {
throw new InvalidOperationException("Widget type `{0}` is not cloneable.".F(GetType().Name)); throw new InvalidOperationException($"Widget type `{GetType().Name}` is not cloneable.");
} }
public virtual int2 RenderOrigin public virtual int2 RenderOrigin
@@ -579,9 +579,7 @@ namespace OpenRA.Widgets
{ {
var t = GetOrNull<T>(id); var t = GetOrNull<T>(id);
if (t == null) if (t == null)
throw new InvalidOperationException( throw new InvalidOperationException($"Widget {Id} has no child {id} of type {typeof(T).Name}");
"Widget {0} has no child {1} of type {2}".F(
Id, id, typeof(T).Name));
return t; return t;
} }

View File

@@ -30,7 +30,7 @@ namespace OpenRA
{ {
var key = w.Key.Substring(w.Key.IndexOf('@') + 1); var key = w.Key.Substring(w.Key.IndexOf('@') + 1);
if (widgets.ContainsKey(key)) if (widgets.ContainsKey(key))
throw new InvalidDataException("Widget has duplicate Key `{0}` at {1}".F(w.Key, w.Location)); throw new InvalidDataException($"Widget has duplicate Key `{w.Key}` at {w.Location}");
widgets.Add(key, w); widgets.Add(key, w);
} }
} }
@@ -38,7 +38,7 @@ namespace OpenRA
public Widget LoadWidget(WidgetArgs args, Widget parent, string w) public Widget LoadWidget(WidgetArgs args, Widget parent, string w)
{ {
if (!widgets.TryGetValue(w, out var ret)) if (!widgets.TryGetValue(w, out var ret))
throw new InvalidDataException("Cannot find widget with Id `{0}`".F(w)); throw new InvalidDataException($"Cannot find widget with Id `{w}`");
return LoadWidget(args, parent, ret); return LoadWidget(args, parent, ret);
} }

View File

@@ -37,7 +37,7 @@ namespace OpenRA.Mods.Cnc.Activities
{ {
var max = teleporter.World.Map.Grid.MaximumTileSearchRange; var max = teleporter.World.Map.Grid.MaximumTileSearchRange;
if (maximumDistance > max) if (maximumDistance > max)
throw new InvalidOperationException("Teleport distance cannot exceed the value of MaximumTileSearchRange ({0}).".F(max)); throw new InvalidOperationException($"Teleport distance cannot exceed the value of MaximumTileSearchRange ({max}).");
this.teleporter = teleporter; this.teleporter = teleporter;
this.destination = destination; this.destination = destination;

View File

@@ -50,8 +50,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
Array.Copy(Transforms, 16 * (LimbCount * j + i), testMatrix, 0, 16); Array.Copy(Transforms, 16 * (LimbCount * j + i), testMatrix, 0, 16);
if (OpenRA.Graphics.Util.MatrixInverse(testMatrix) == null) if (OpenRA.Graphics.Util.MatrixInverse(testMatrix) == null)
throw new InvalidDataException( throw new InvalidDataException(
"The transformation matrix for HVA file `{0}` section {1} frame {2} is invalid because it is not invertible!" $"The transformation matrix for HVA file `{fileName}` section {i} frame {j} is invalid because it is not invertible!");
.F(fileName, i, j));
} }
} }

View File

@@ -39,7 +39,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
public override string ToString() public override string ToString()
{ {
return "{0} - offset 0x{1:x8} - length 0x{2:x8}".F(Filename, Offset, Length); return $"{Filename} - offset 0x{Offset:x8} - length 0x{Length:x8}";
} }
} }
} }

View File

@@ -26,12 +26,12 @@ namespace OpenRA.Mods.Cnc.FileFormats
var id = s.ReadASCII(4); var id = s.ReadASCII(4);
if (id != "GABA") if (id != "GABA")
throw new InvalidDataException("Unable to load Idx file, did not find magic id, found {0} instead".F(id)); throw new InvalidDataException($"Unable to load Idx file, did not find magic id, found {id} instead");
var two = s.ReadInt32(); var two = s.ReadInt32();
if (two != 2) if (two != 2)
throw new InvalidDataException("Unable to load Idx file, did not find magic number 2, found {0} instead".F(two)); throw new InvalidDataException($"Unable to load Idx file, did not find magic number 2, found {two} instead");
SoundCount = s.ReadInt32(); SoundCount = s.ReadInt32();

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
static void ReplicatePrevious(byte[] dest, int destIndex, int srcIndex, int count) static void ReplicatePrevious(byte[] dest, int destIndex, int srcIndex, int count)
{ {
if (srcIndex > destIndex) if (srcIndex > destIndex)
throw new NotImplementedException("srcIndex > destIndex {0} {1}".F(srcIndex, destIndex)); throw new NotImplementedException($"srcIndex > destIndex {srcIndex} {destIndex}");
for (var i = 0; i < count; i++) for (var i = 0; i < count; i++)
{ {
@@ -80,7 +80,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
var count = count3 == 0x3F ? ctx.ReadWord() : count3 + 3; var count = count3 == 0x3F ? ctx.ReadWord() : count3 + 3;
var srcIndex = reverse ? destIndex - ctx.ReadWord() : ctx.ReadWord(); var srcIndex = reverse ? destIndex - ctx.ReadWord() : ctx.ReadWord();
if (srcIndex >= destIndex) if (srcIndex >= destIndex)
throw new NotImplementedException("srcIndex >= destIndex {0} {1}".F(srcIndex, destIndex)); throw new NotImplementedException($"srcIndex >= destIndex {srcIndex} {destIndex}");
for (var end = destIndex + count; destIndex < end; destIndex++) for (var end = destIndex + count; destIndex < end; destIndex++)
dest[destIndex] = dest[srcIndex++]; dest[destIndex] = dest[srcIndex++];

View File

@@ -142,7 +142,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
type = stream.ReadASCII(4); type = stream.ReadASCII(4);
} }
else else
throw new NotSupportedException("Vqa uses unknown Subtype: {0}".F(type)); throw new NotSupportedException($"Vqa uses unknown Subtype: {type}");
} }
/*var length = */stream.ReadUInt16(); /*var length = */stream.ReadUInt16();
@@ -217,7 +217,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
break; break;
default: default:
if (length + stream.Position > stream.Length) if (length + stream.Position > stream.Length)
throw new NotSupportedException("Vqa uses unknown Subtype: {0}".F(type)); throw new NotSupportedException($"Vqa uses unknown Subtype: {type}");
stream.ReadBytes((int)length); stream.ReadBytes((int)length);
break; break;
} }
@@ -420,7 +420,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
vtprSize = subchunkLength; vtprSize = subchunkLength;
return; return;
default: default:
throw new InvalidDataException("Unknown sub-chunk {0}".F(type)); throw new InvalidDataException($"Unknown sub-chunk {type}");
} }
} }
} }
@@ -562,7 +562,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
// Replicate previous // Replicate previous
var srcIndex = destIndex - rpos; var srcIndex = destIndex - rpos;
if (srcIndex > destIndex) if (srcIndex > destIndex)
throw new NotImplementedException("srcIndex > destIndex {0} {1}".F(srcIndex, destIndex)); throw new NotImplementedException($"srcIndex > destIndex {srcIndex} {destIndex}");
for (var j = 0; j < count; j++) for (var j = 0; j < count; j++)
{ {
@@ -602,7 +602,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
var count = count3 == 0x3F ? ctx.ReadWord() : count3 + 3; var count = count3 == 0x3F ? ctx.ReadWord() : count3 + 3;
var srcIndex = reverse ? destIndex - ctx.ReadWord() : ctx.ReadWord(); var srcIndex = reverse ? destIndex - ctx.ReadWord() : ctx.ReadWord();
if (srcIndex >= destIndex) if (srcIndex >= destIndex)
throw new NotImplementedException("srcIndex >= destIndex {0} {1}".F(srcIndex, destIndex)); throw new NotImplementedException($"srcIndex >= destIndex {srcIndex} {destIndex}");
for (var end = destIndex + count; destIndex < end; destIndex++) for (var end = destIndex + count; destIndex < end; destIndex++)
dest[destIndex] = dest[srcIndex++]; dest[destIndex] = dest[srcIndex++];

View File

@@ -54,8 +54,8 @@ namespace OpenRA.Mods.Cnc.FileSystem
entries = ParseHeader(s, isCncMix ? 0 : 4, out dataStart); entries = ParseHeader(s, isCncMix ? 0 : 4, out dataStart);
index = ParseIndex(entries.ToDictionaryWithConflictLog(x => x.Hash, index = ParseIndex(entries.ToDictionaryWithConflictLog(x => x.Hash,
"{0} ({1} format, Encrypted: {2}, DataStart: {3})".F(filename, isCncMix ? "C&C" : "RA/TS/RA2", isEncrypted, dataStart), $"{filename} ({(isCncMix ? "C&C" : "RA/TS/RA2")} format, Encrypted: {isEncrypted}, DataStart: {dataStart})",
null, x => "(offs={0}, len={1})".F(x.Offset, x.Length)), allPossibleFilenames); null, x => $"(offs={x.Offset}, len={x.Length})"), allPossibleFilenames);
} }
catch (Exception) catch (Exception)
{ {
@@ -103,7 +103,7 @@ namespace OpenRA.Mods.Cnc.FileSystem
var unknown = entries.Count - bestIndex.Count; var unknown = entries.Count - bestIndex.Count;
if (unknown > 0) if (unknown > 0)
Log.Write("debug", "{0}: failed to resolve filenames for {1} unknown hashes".F(Name, unknown)); Log.Write("debug", $"{Name}: failed to resolve filenames for {unknown} unknown hashes");
return bestIndex; return bestIndex;
} }
@@ -165,7 +165,7 @@ namespace OpenRA.Mods.Cnc.FileSystem
throw new ArgumentOutOfRangeException(nameof(count), "Non-negative number required."); throw new ArgumentOutOfRangeException(nameof(count), "Non-negative number required.");
if (offset + (count * 2) > s.Length) if (offset + (count * 2) > s.Length)
throw new ArgumentException("Bytes to read {0} and offset {1} greater than stream length {2}.".F(count * 2, offset, s.Length)); throw new ArgumentException($"Bytes to read {count * 2} and offset {offset} greater than stream length {s.Length}.");
s.Seek(offset, SeekOrigin.Begin); s.Seek(offset, SeekOrigin.Begin);

View File

@@ -50,9 +50,9 @@ namespace OpenRA.Mods.Cnc.FileSystem
public override string ToString() public override string ToString()
{ {
if (names.TryGetValue(Hash, out var filename)) if (names.TryGetValue(Hash, out var filename))
return "{0} - offset 0x{1:x8} - length 0x{2:x8}".F(filename, Offset, Length); return $"{filename} - offset 0x{Offset:x8} - length 0x{Length:x8}";
else else
return "0x{0:x8} - offset 0x{1:x8} - length 0x{2:x8}".F(Hash, Offset, Length); return $"0x{Hash:x8} - offset 0x{Offset:x8} - length 0x{Length:x8}";
} }
public static uint HashFilename(string name, PackageHashType type) public static uint HashFilename(string name, PackageHashType type)
@@ -93,7 +93,7 @@ namespace OpenRA.Mods.Cnc.FileSystem
return CRC32.Calculate(Encoding.ASCII.GetBytes(name)); return CRC32.Calculate(Encoding.ASCII.GetBytes(name));
} }
default: throw new NotImplementedException("Unknown hash type `{0}`".F(type)); default: throw new NotImplementedException($"Unknown hash type `{type}`");
} }
} }

View File

@@ -38,8 +38,7 @@ namespace OpenRA.Mods.Cnc.Graphics
if (useClassicFacings && Facings != 32) if (useClassicFacings && Facings != 32)
throw new InvalidOperationException( throw new InvalidOperationException(
"{0}: Sequence {1}.{2}: UseClassicFacings is only valid for 32 facings" $"{info.Nodes[0].Location}: Sequence {sequence}.{animation}: UseClassicFacings is only valid for 32 facings");
.F(info.Nodes[0].Location, sequence, animation));
} }
protected override int GetFacingFrameOffset(WAngle facing) protected override int GetFacingFrameOffset(WAngle facing)

View File

@@ -38,7 +38,7 @@ namespace OpenRA.Mods.Cnc.Graphics
public Voxel(VoxelLoader loader, VxlReader vxl, HvaReader hva, (string Vxl, string Hva) files) public Voxel(VoxelLoader loader, VxlReader vxl, HvaReader hva, (string Vxl, string Hva) files)
{ {
if (vxl.LimbCount != hva.LimbCount) if (vxl.LimbCount != hva.LimbCount)
throw new InvalidOperationException("{0}.vxl and {1}.hva limb counts don't match.".F(files.Vxl, files.Hva)); throw new InvalidOperationException($"{files.Vxl}.vxl and {files.Hva}.hva limb counts don't match.");
transforms = hva.Transforms; transforms = hva.Transforms;
frames = hva.FrameCount; frames = hva.FrameCount;
@@ -60,9 +60,9 @@ namespace OpenRA.Mods.Cnc.Graphics
public float[] TransformationMatrix(uint limb, uint frame) public float[] TransformationMatrix(uint limb, uint frame)
{ {
if (frame >= frames) if (frame >= frames)
throw new ArgumentOutOfRangeException(nameof(frame), "Only {0} frames exist.".F(frames)); throw new ArgumentOutOfRangeException(nameof(frame), $"Only {frames} frames exist.");
if (limb >= limbs) if (limb >= limbs)
throw new ArgumentOutOfRangeException(nameof(limb), "Only {1} limbs exist.".F(limbs)); throw new ArgumentOutOfRangeException(nameof(limb), $"Only {limbs} limbs exist.");
var l = limbData[limb]; var l = limbData[limb];
var t = new float[16]; var t = new float[16];

View File

@@ -98,10 +98,10 @@ namespace OpenRA.Mods.Cnc.Graphics
{ {
if (models.ContainsKey(model)) if (models.ContainsKey(model))
throw new InvalidOperationException( throw new InvalidOperationException(
"Model `{0}` does not have a sequence `{1}`".F(model, sequence)); $"Model `{model}` does not have a sequence `{sequence}`");
else else
throw new InvalidOperationException( throw new InvalidOperationException(
"Model `{0}` does not have any sequences defined.".F(model)); $"Model `{model}` does not have any sequences defined.");
} }
} }
@@ -109,7 +109,7 @@ namespace OpenRA.Mods.Cnc.Graphics
{ {
if (!models.ContainsKey(model)) if (!models.ContainsKey(model))
throw new InvalidOperationException( throw new InvalidOperationException(
"Model `{0}` does not have any sequences defined.".F(model)); $"Model `{model}` does not have any sequences defined.");
return models[model].ContainsKey(sequence); return models[model].ContainsKey(sequence);
} }

View File

@@ -33,8 +33,7 @@ namespace OpenRA.Mods.Cnc.Scripting
using (kv.Value) using (kv.Value)
{ {
if (!kv.Key.TryGetClrValue(out actor) || !kv.Value.TryGetClrValue(out cell)) if (!kv.Key.TryGetClrValue(out actor) || !kv.Value.TryGetClrValue(out cell))
throw new LuaException("Chronoshift requires a table of Actor,CPos pairs. Received {0},{1}".F( throw new LuaException($"Chronoshift requires a table of Actor,CPos pairs. Received {kv.Key.WrappedClrType().Name},{kv.Value.WrappedClrType().Name}");
kv.Key.WrappedClrType().Name, kv.Value.WrappedClrType().Name));
} }
var cs = actor.TraitsImplementing<Chronoshiftable>() var cs = actor.TraitsImplementing<Chronoshiftable>()

View File

@@ -35,7 +35,7 @@ namespace OpenRA.Mods.Cnc.Scripting
var infiltrates = infiltratesTraits.FirstOrDefault(x => !x.IsTraitDisabled && x.Info.Types.Overlaps(target.GetEnabledTargetTypes())); var infiltrates = infiltratesTraits.FirstOrDefault(x => !x.IsTraitDisabled && x.Info.Types.Overlaps(target.GetEnabledTargetTypes()));
if (infiltrates == null) if (infiltrates == null)
throw new LuaException("{0} tried to infiltrate invalid target {1}!".F(Self, target)); throw new LuaException($"{Self} tried to infiltrate invalid target {target}!");
// NB: Scripted actions get no visible targetlines. // NB: Scripted actions get no visible targetlines.
Self.QueueActivity(new Infiltrate(Self, Target.FromActor(target), infiltrates, null)); Self.QueueActivity(new Infiltrate(Self, Target.FromActor(target), infiltrates, null));

View File

@@ -75,7 +75,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders
framePrefix = prefix; framePrefix = prefix;
if (prefix != framePrefix) if (prefix != framePrefix)
throw new InvalidDataException("Frame prefix mismatch: `{0}` != `{1}`".F(prefix, framePrefix)); throw new InvalidDataException($"Frame prefix mismatch: `{prefix}` != `{framePrefix}`");
frameCount = Math.Max(frameCount, int.Parse(match.Groups["frame"].Value) + 1); frameCount = Math.Max(frameCount, int.Parse(match.Groups["frame"].Value) + 1);
} }
@@ -83,7 +83,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders
var frames = new ISpriteFrame[frameCount]; var frames = new ISpriteFrame[frameCount];
for (var i = 0; i < frames.Length; i++) for (var i = 0; i < frames.Length; i++)
{ {
var tgaEntry = container.GetEntry("{0}{1:D4}.tga".F(framePrefix, i)); var tgaEntry = container.GetEntry($"{framePrefix}{i:D4}.tga");
// Blank frame // Blank frame
if (tgaEntry == null) if (tgaEntry == null)
@@ -92,7 +92,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders
continue; continue;
} }
var metaEntry = container.GetEntry("{0}{1:D4}.meta".F(framePrefix, i)); var metaEntry = container.GetEntry($"{framePrefix}{i:D4}.meta");
using (var tgaStream = container.GetInputStream(tgaEntry)) using (var tgaStream = container.GetInputStream(tgaEntry))
{ {
var metaStream = metaEntry != null ? container.GetInputStream(metaEntry) : null; var metaStream = metaEntry != null ? container.GetInputStream(metaEntry) : null;

View File

@@ -147,7 +147,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders
if (h.Format == Format.XORPrev) if (h.Format == Format.XORPrev)
h.RefImage = headers[i - 1]; h.RefImage = headers[i - 1];
else if (h.Format == Format.XORLCW && !offsets.TryGetValue(h.RefOffset, out h.RefImage)) else if (h.Format == Format.XORLCW && !offsets.TryGetValue(h.RefOffset, out h.RefImage))
throw new InvalidDataException("Reference doesn't point to image data {0}->{1}".F(h.FileOffset, h.RefOffset)); throw new InvalidDataException($"Reference doesn't point to image data {h.FileOffset}->{h.RefOffset}");
} }
shpBytesFileOffset = stream.Position; shpBytesFileOffset = stream.Position;

View File

@@ -38,7 +38,7 @@ namespace OpenRA.Mods.Cnc.Traits
{ {
var weaponToLower = Weapon.ToLowerInvariant(); var weaponToLower = Weapon.ToLowerInvariant();
if (!rules.Weapons.TryGetValue(weaponToLower, out var weaponInfo)) if (!rules.Weapons.TryGetValue(weaponToLower, out var weaponInfo))
throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'");
WeaponInfo = weaponInfo; WeaponInfo = weaponInfo;
} }

View File

@@ -77,10 +77,10 @@ namespace OpenRA.Mods.Cnc.Traits
var detonationWeaponToLower = (DetonationWeapon ?? string.Empty).ToLowerInvariant(); var detonationWeaponToLower = (DetonationWeapon ?? string.Empty).ToLowerInvariant();
if (!rules.Weapons.TryGetValue(thumpDamageWeaponToLower, out var thumpDamageWeapon)) if (!rules.Weapons.TryGetValue(thumpDamageWeaponToLower, out var thumpDamageWeapon))
throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(thumpDamageWeaponToLower)); throw new YamlException($"Weapons Ruleset does not contain an entry '{thumpDamageWeaponToLower}'");
if (!rules.Weapons.TryGetValue(detonationWeaponToLower, out var detonationWeapon)) if (!rules.Weapons.TryGetValue(detonationWeaponToLower, out var detonationWeapon))
throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(detonationWeaponToLower)); throw new YamlException($"Weapons Ruleset does not contain an entry '{detonationWeaponToLower}'");
ThumpDamageWeaponInfo = thumpDamageWeapon; ThumpDamageWeaponInfo = thumpDamageWeapon;
DetonationWeaponInfo = detonationWeapon; DetonationWeaponInfo = detonationWeapon;

View File

@@ -81,8 +81,8 @@ namespace OpenRA.Mods.Cnc.Traits
this.self = self; this.self = self;
var tileset = self.World.Map.Tileset.ToLowerInvariant(); var tileset = self.World.Map.Tileset.ToLowerInvariant();
if (self.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(Info.TileValidName, tileset))) if (self.World.Map.Rules.Sequences.HasSequence("overlay", $"{Info.TileValidName}-{tileset}"))
Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(Info.TileValidName, tileset)).GetSprite(0); Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", $"{Info.TileValidName}-{tileset}").GetSprite(0);
else else
Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", Info.TileValidName).GetSprite(0); Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", Info.TileValidName).GetSprite(0);
} }
@@ -220,9 +220,9 @@ namespace OpenRA.Mods.Cnc.Traits
minelayer = a.Trait<Minelayer>(); minelayer = a.Trait<Minelayer>();
var tileset = a.World.Map.Tileset.ToLowerInvariant(); var tileset = a.World.Map.Tileset.ToLowerInvariant();
if (a.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(minelayer.Info.TileValidName, tileset))) if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileValidName}-{tileset}"))
{ {
var validSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(minelayer.Info.TileValidName, tileset)); var validSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileValidName}-{tileset}");
validTile = validSequence.GetSprite(0); validTile = validSequence.GetSprite(0);
validAlpha = validSequence.GetAlpha(0); validAlpha = validSequence.GetAlpha(0);
} }
@@ -233,9 +233,9 @@ namespace OpenRA.Mods.Cnc.Traits
validAlpha = validSequence.GetAlpha(0); validAlpha = validSequence.GetAlpha(0);
} }
if (a.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(minelayer.Info.TileUnknownName, tileset))) if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileUnknownName}-{tileset}"))
{ {
var unknownSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(minelayer.Info.TileUnknownName, tileset)); var unknownSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileUnknownName}-{tileset}");
unknownTile = unknownSequence.GetSprite(0); unknownTile = unknownSequence.GetSprite(0);
unknownAlpha = unknownSequence.GetAlpha(0); unknownAlpha = unknownSequence.GetAlpha(0);
} }
@@ -246,9 +246,9 @@ namespace OpenRA.Mods.Cnc.Traits
unknownAlpha = unknownSequence.GetAlpha(0); unknownAlpha = unknownSequence.GetAlpha(0);
} }
if (a.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(minelayer.Info.TileInvalidName, tileset))) if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileInvalidName}-{tileset}"))
{ {
var blockedSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(minelayer.Info.TileInvalidName, tileset)); var blockedSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileInvalidName}-{tileset}");
blockedTile = blockedSequence.GetSprite(0); blockedTile = blockedSequence.GetSprite(0);
blockedAlpha = blockedSequence.GetAlpha(0); blockedAlpha = blockedSequence.GetAlpha(0);
} }

View File

@@ -68,7 +68,7 @@ namespace OpenRA.Mods.Cnc.Traits
{ {
var weaponToLower = (Weapon ?? string.Empty).ToLowerInvariant(); var weaponToLower = (Weapon ?? string.Empty).ToLowerInvariant();
if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon))
throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'");
WeaponInfo = weapon; WeaponInfo = weapon;

View File

@@ -54,7 +54,7 @@ namespace OpenRA.Mods.Cnc.Traits
{ {
var weaponToLower = (Weapon ?? string.Empty).ToLowerInvariant(); var weaponToLower = (Weapon ?? string.Empty).ToLowerInvariant();
if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon))
throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'");
WeaponInfo = weapon; WeaponInfo = weapon;

View File

@@ -249,7 +249,7 @@ namespace OpenRA.Mods.Cnc.Traits
else if (BorderIndices.TryGetValue(adjacency, out var indices)) else if (BorderIndices.TryGetValue(adjacency, out var indices))
UpdateSpriteLayers(cell, indices); UpdateSpriteLayers(cell, indices);
else else
throw new InvalidOperationException("SpriteMap does not contain an index for Adjacency type '{0}'".F(adjacency)); throw new InvalidOperationException($"SpriteMap does not contain an index for Adjacency type '{adjacency}'");
} }
void UpdateSpriteLayers(CPos cell, int[] indices) void UpdateSpriteLayers(CPos cell, int[] indices)

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