Merge pull request #7247 from Hellhake/stylecop-game

Fix StyleCop warnings in OpenRA.Game
This commit is contained in:
Oliver Brakmann
2015-01-02 12:58:04 +01:00
119 changed files with 547 additions and 529 deletions

View File

@@ -24,12 +24,13 @@ namespace OpenRA
{ {
public class Actor : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding, IEquatable<Actor> public class Actor : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding, IEquatable<Actor>
{ {
[Sync] public Player Owner;
public readonly ActorInfo Info; public readonly ActorInfo Info;
public readonly World World; public readonly World World;
public readonly uint ActorID; public readonly uint ActorID;
[Sync]
public Player Owner;
public bool IsInWorld { get; internal set; } public bool IsInWorld { get; internal set; }
public bool Destroyed { get; private set; } public bool Destroyed { get; private set; }

View File

@@ -31,7 +31,7 @@ namespace OpenRA
public static CVec operator -(CPos a, CPos b) { return new CVec(a.X - b.X, a.Y - b.Y); } public static CVec operator -(CPos a, CPos b) { return new CVec(a.X - b.X, a.Y - b.Y); }
public static bool operator ==(CPos me, CPos other) { return (me.X == other.X && me.Y == other.Y); } public static bool operator ==(CPos me, CPos other) { return me.X == other.X && me.Y == other.Y; }
public static bool operator !=(CPos me, CPos other) { return !(me == other); } public static bool operator !=(CPos me, CPos other) { return !(me == other); }
public static CPos Max(CPos a, CPos b) { return new CPos(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); } public static CPos Max(CPos a, CPos b) { return new CPos(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); }

View File

@@ -31,7 +31,7 @@ namespace OpenRA
public static CVec operator -(CVec a) { return new CVec(-a.X, -a.Y); } public static CVec operator -(CVec a) { return new CVec(-a.X, -a.Y); }
public static bool operator ==(CVec me, CVec other) { return (me.X == other.X && me.Y == other.Y); } public static bool operator ==(CVec me, CVec other) { return me.X == other.X && me.Y == other.Y; }
public static bool operator !=(CVec me, CVec other) { return !(me == other); } public static bool operator !=(CVec me, CVec other) { return !(me == other); }
public static CVec Max(CVec a, CVec b) { return new CVec(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); } public static CVec Max(CVec a, CVec b) { return new CVec(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); }
@@ -48,8 +48,7 @@ namespace OpenRA
{ {
return new CVec( return new CVec(
Math.Min(r.Right, Math.Max(X, r.Left)), Math.Min(r.Right, Math.Max(X, r.Left)),
Math.Min(r.Bottom, Math.Max(Y, r.Top)) Math.Min(r.Bottom, Math.Max(Y, r.Top)));
);
} }
public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); }

View File

@@ -92,7 +92,6 @@ namespace OpenRA
return (k & mod) == mod; return (k & mod) == mod;
} }
public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k) public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k)
where V : new() where V : new()
{ {
@@ -184,6 +183,7 @@ namespace OpenRA
u = nextU; u = nextU;
} }
} }
return t; return t;
} }
} }
@@ -242,7 +242,6 @@ namespace OpenRA
// Adjust for other rounding modes // Adjust for other rounding modes
if (round == ISqrtRoundMode.Nearest && remainder > root) if (round == ISqrtRoundMode.Nearest && remainder > root)
root += 1; root += 1;
else if (round == ISqrtRoundMode.Ceiling && root * root < number) else if (round == ISqrtRoundMode.Ceiling && root * root < number)
root += 1; root += 1;
@@ -284,7 +283,6 @@ namespace OpenRA
// Adjust for other rounding modes // Adjust for other rounding modes
if (round == ISqrtRoundMode.Nearest && remainder > root) if (round == ISqrtRoundMode.Nearest && remainder > root)
root += 1; root += 1;
else if (round == ISqrtRoundMode.Ceiling && root * root < number) else if (round == ISqrtRoundMode.Ceiling && root * root < number)
root += 1; root += 1;

View File

@@ -131,7 +131,6 @@ namespace OpenRA
return res; return res;
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(ushort)) else if (fieldType == typeof(ushort))
{ {
ushort res; ushort res;
@@ -147,7 +146,6 @@ namespace OpenRA
return res; return res;
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(float)) else if (fieldType == typeof(float))
{ {
float res; float res;
@@ -155,7 +153,6 @@ namespace OpenRA
return res * (value.Contains('%') ? 0.01f : 1f); return res * (value.Contains('%') ? 0.01f : 1f);
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(decimal)) else if (fieldType == typeof(decimal))
{ {
decimal res; decimal res;
@@ -163,14 +160,12 @@ namespace OpenRA
return res * (value.Contains('%') ? 0.01m : 1m); return res * (value.Contains('%') ? 0.01m : 1m);
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(string)) else if (fieldType == typeof(string))
{ {
if (field != null && field.HasAttribute<TranslateAttribute>()) if (field != null && field.HasAttribute<TranslateAttribute>())
return Regex.Replace(value, "@[^@]+@", m => Translate(m.Value.Substring(1, m.Value.Length - 2)), RegexOptions.Compiled); return Regex.Replace(value, "@[^@]+@", m => Translate(m.Value.Substring(1, m.Value.Length - 2)), RegexOptions.Compiled);
return value; return value;
} }
else if (fieldType == typeof(Color)) else if (fieldType == typeof(Color))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -187,7 +182,6 @@ namespace OpenRA
Exts.ParseIntegerInvariant(parts[3]).Clamp(0, 255)); Exts.ParseIntegerInvariant(parts[3]).Clamp(0, 255));
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(Color[])) else if (fieldType == typeof(Color[]))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -208,7 +202,6 @@ namespace OpenRA
return colors; return colors;
} }
else if (fieldType == typeof(HSLColor)) else if (fieldType == typeof(HSLColor))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -222,7 +215,6 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(Hotkey)) else if (fieldType == typeof(Hotkey))
{ {
Hotkey res; Hotkey res;
@@ -231,7 +223,6 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(WRange)) else if (fieldType == typeof(WRange))
{ {
WRange res; WRange res;
@@ -240,7 +231,6 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(WVec)) else if (fieldType == typeof(WVec))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -253,7 +243,6 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(WVec[])) else if (fieldType == typeof(WVec[]))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -274,7 +263,6 @@ namespace OpenRA
return vecs; return vecs;
} }
else if (fieldType == typeof(WPos)) else if (fieldType == typeof(WPos))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -287,7 +275,6 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(WAngle)) else if (fieldType == typeof(WAngle))
{ {
int res; int res;
@@ -295,7 +282,6 @@ namespace OpenRA
return new WAngle(res); return new WAngle(res);
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(WRot)) else if (fieldType == typeof(WRot))
{ {
var parts = value.Split(','); var parts = value.Split(',');
@@ -310,7 +296,6 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else if (fieldType == typeof(CPos)) else if (fieldType == typeof(CPos))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -318,7 +303,6 @@ namespace OpenRA
Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[0]),
Exts.ParseIntegerInvariant(parts[1])); Exts.ParseIntegerInvariant(parts[1]));
} }
else if (fieldType == typeof(CVec)) else if (fieldType == typeof(CVec))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -326,7 +310,6 @@ namespace OpenRA
Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[0]),
Exts.ParseIntegerInvariant(parts[1])); Exts.ParseIntegerInvariant(parts[1]));
} }
else if (fieldType.IsEnum) else if (fieldType.IsEnum)
{ {
try try
@@ -338,10 +321,8 @@ namespace OpenRA
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
} }
else if (fieldType == typeof(bool)) else if (fieldType == typeof(bool))
return ParseYesNo(value, fieldType, fieldName); return ParseYesNo(value, fieldType, fieldName);
else if (fieldType.IsArray) else if (fieldType.IsArray)
{ {
if (value == null) if (value == null)
@@ -354,7 +335,6 @@ namespace OpenRA
ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i); ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i);
return ret; return ret;
} }
else if (fieldType == typeof(Size)) else if (fieldType == typeof(Size))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -362,7 +342,6 @@ namespace OpenRA
Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[0]),
Exts.ParseIntegerInvariant(parts[1])); Exts.ParseIntegerInvariant(parts[1]));
} }
else if (fieldType == typeof(int2)) else if (fieldType == typeof(int2))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -370,7 +349,6 @@ namespace OpenRA
Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[0]),
Exts.ParseIntegerInvariant(parts[1])); Exts.ParseIntegerInvariant(parts[1]));
} }
else if (fieldType == typeof(float2)) else if (fieldType == typeof(float2))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -383,7 +361,6 @@ namespace OpenRA
yy = res * (parts[1].Contains('%') ? 0.01f : 1f); yy = res * (parts[1].Contains('%') ? 0.01f : 1f);
return new float2(xx, yy); return new float2(xx, yy);
} }
else if (fieldType == typeof(Rectangle)) else if (fieldType == typeof(Rectangle))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -393,7 +370,6 @@ namespace OpenRA
Exts.ParseIntegerInvariant(parts[2]), Exts.ParseIntegerInvariant(parts[2]),
Exts.ParseIntegerInvariant(parts[3])); Exts.ParseIntegerInvariant(parts[3]));
} }
else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Bits<>)) else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Bits<>))
{ {
var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
@@ -401,14 +377,12 @@ namespace OpenRA
var argValues = new object[] { parts }; var argValues = new object[] { parts };
return fieldType.GetConstructor(argTypes).Invoke(argValues); return fieldType.GetConstructor(argTypes).Invoke(argValues);
} }
else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>)) else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
{ {
var innerType = fieldType.GetGenericArguments().First(); var innerType = fieldType.GetGenericArguments().First();
var innerValue = GetValue("Nullable<T>", innerType, value, field); var innerValue = GetValue("Nullable<T>", innerType, value, field);
return fieldType.GetConstructor(new[] { innerType }).Invoke(new[] { innerValue }); return fieldType.GetConstructor(new[] { innerType }).Invoke(new[] { innerValue });
} }
else if (fieldType == typeof(DateTime)) else if (fieldType == typeof(DateTime))
{ {
DateTime dt; DateTime dt;
@@ -416,7 +390,6 @@ namespace OpenRA
return dt; return dt;
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
else else
{ {
var conv = TypeDescriptor.GetConverter(fieldType); var conv = TypeDescriptor.GetConverter(fieldType);

View File

@@ -46,8 +46,7 @@ namespace OpenRA
return new MiniYaml( return new MiniYaml(
null, null,
fields.Select(info => new MiniYamlNode(info.YamlName, FormatValue(o, info.Field))).ToList() fields.Select(info => new MiniYamlNode(info.YamlName, FormatValue(o, info.Field))).ToList());
);
} }
public static MiniYamlNode SaveField(object o, string field) public static MiniYamlNode SaveField(object o, string field)

View File

@@ -142,9 +142,9 @@ namespace OpenRA.FileFormats
} }
} while (len != 0); } while (len != 0);
} }
// literal value
else else
{ {
// literal value
var symbol = EncodedLiterals ? Decode(litcode, br) : br.ReadBits(8); var symbol = EncodedLiterals ? Decode(litcode, br) : br.ReadBits(8);
outBuffer[next++] = (byte)symbol; outBuffer[next++] = (byte)symbol;
if (next == MAXWIN) if (next == MAXWIN)

View File

@@ -80,6 +80,7 @@ namespace OpenRA.FileFormats
else else
Round(ref _b, _a, i); Round(ref _b, _a, i);
} }
_b ^= m_p[17]; _b ^= m_p[17];
a = _b; a = _b;
@@ -99,6 +100,7 @@ namespace OpenRA.FileFormats
else else
Round(ref _b, _a, i); Round(ref _b, _a, i);
} }
_b ^= m_p[0]; _b ^= m_p[0];
a = _b; a = _b;
@@ -400,7 +402,6 @@ namespace OpenRA.FileFormats
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
} }
}; };
} }
} }

View File

@@ -25,6 +25,7 @@ namespace OpenRA.FileFormats
public uint[] key2 = new uint[64]; public uint[] key2 = new uint[64];
public uint len; public uint len;
} }
PublicKey pubkey = new PublicKey(); PublicKey pubkey = new PublicKey();
uint[] glob1 = new uint[64]; uint[] glob1 = new uint[64];
@@ -81,6 +82,7 @@ namespace OpenRA.FileFormats
keylen = key[j]; keylen = key[j];
j++; j++;
} }
if (keylen <= len * 4) if (keylen <= len * 4)
move_key_to_big(n, key.Skip(j).ToArray(), keylen, len); move_key_to_big(n, key.Skip(j).ToArray(), keylen, len);
} }
@@ -105,6 +107,7 @@ namespace OpenRA.FileFormats
mask >>= 1; mask >>= 1;
bitlen--; bitlen--;
} }
return bitlen; return bitlen;
} }
@@ -124,13 +127,13 @@ namespace OpenRA.FileFormats
static int cmp_bignum(uint[] n1, uint[] n2, uint len) static int cmp_bignum(uint[] n1, uint[] n2, uint len)
{ {
while (len > 0) while (len > 0)
{ {
--len; --len;
if (n1[len] < n2[len]) return -1; if (n1[len] < n2[len]) return -1;
if (n1[len] > n2[len]) return 1; if (n1[len] > n2[len]) return 1;
} }
return 0; return 0;
} }
@@ -149,6 +152,7 @@ namespace OpenRA.FileFormats
for (; i < len; i++) n[i] = 0; for (; i < len; i++) n[i] = 0;
bits = bits % 32; bits = bits % 32;
} }
if (bits == 0) return; if (bits == 0) return;
for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 - for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 -
bits)); bits));
@@ -166,6 +170,7 @@ namespace OpenRA.FileFormats
for (; i > 0; i--) n[i] = 0; for (; i > 0; i--) n[i] = 0;
bits = bits % 32; bits = bits % 32;
} }
if (bits == 0) return; if (bits == 0) return;
for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 - for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 -
bits)); bits));
@@ -196,6 +201,7 @@ namespace OpenRA.FileFormats
} }
} }
} }
return carry; return carry;
} }
@@ -215,8 +221,8 @@ namespace OpenRA.FileFormats
i2 = *ps2++; i2 = *ps2++;
*pd++ = (ushort)(i1 - i2 - carry); *pd++ = (ushort)(i1 - i2 - carry);
if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0; if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0;
} }
return carry; return carry;
} }
@@ -245,6 +251,7 @@ namespace OpenRA.FileFormats
sub_bignum(n_tmp, n_tmp, n2, 0, (int)len); sub_bignum(n_tmp, n_tmp, n2, 0, (int)len);
n1[j] |= bit; n1[j] |= bit;
} }
bit >>= 1; bit >>= 1;
if (bit == 0) if (bit == 0)
{ {
@@ -252,6 +259,7 @@ namespace OpenRA.FileFormats
bit = 0x80000000; bit = 0x80000000;
} }
} }
init_bignum(n_tmp, 0, len); init_bignum(n_tmp, 0, len);
} }
@@ -278,6 +286,7 @@ namespace OpenRA.FileFormats
shr_bignum(glob1_hi_inv, 1, 2); shr_bignum(glob1_hi_inv, 1, 2);
glob1_hi_bitlen--; glob1_hi_bitlen--;
} }
glob1_hi_inv_lo = (ushort)glob1_hi_inv[0]; glob1_hi_inv_lo = (ushort)glob1_hi_inv[0];
glob1_hi_inv_hi = (ushort)(glob1_hi_inv[0] >> 16); glob1_hi_inv_hi = (ushort)(glob1_hi_inv[0] >> 16);
} }
@@ -387,9 +396,11 @@ namespace OpenRA.FileFormats
} }
} }
} }
neg_bignum(glob2, len); neg_bignum(glob2, len);
dec_bignum(glob2, len); dec_bignum(glob2, len);
} }
mov_bignum(n1, glob2, len); mov_bignum(n1, glob2, len);
} }
} }
@@ -437,6 +448,7 @@ namespace OpenRA.FileFormats
bit_mask = 0x80000000; bit_mask = 0x80000000;
pn3--; pn3--;
} }
calc_a_bignum(n_tmp, n1, n1, n4_len); calc_a_bignum(n_tmp, n1, n1, n4_len);
if ((*pn3 & bit_mask) != 0) if ((*pn3 & bit_mask) != 0)
calc_a_bignum(n1, n_tmp, n2, n4_len); calc_a_bignum(n1, n_tmp, n2, n4_len);
@@ -444,6 +456,7 @@ namespace OpenRA.FileFormats
mov_bignum(n1, n_tmp, n4_len); mov_bignum(n1, n_tmp, n4_len);
bit_mask >>= 1; bit_mask >>= 1;
} }
init_bignum(n_tmp, 0, n4_len); init_bignum(n_tmp, 0, n4_len);
clear_tmp_vars(len); clear_tmp_vars(len);
} }
@@ -488,6 +501,7 @@ namespace OpenRA.FileFormats
fixed (byte* psrc = &src[0]) fixed (byte* psrc = &src[0])
process_predata(psrc, len_predata(), pdest); process_predata(psrc, len_predata(), pdest);
} }
return dest.Take(56).ToArray(); return dest.Take(56).ToArray();
} }
} }

View File

@@ -10,7 +10,6 @@
namespace OpenRA.FileFormats namespace OpenRA.FileFormats
{ {
/// <summary> /// <summary>
/// Static class that uses a lookup table to calculates CRC32 /// Static class that uses a lookup table to calculates CRC32
/// checksums of input strings. /// checksums of input strings.
@@ -104,6 +103,7 @@ namespace OpenRA.FileFormats
crc ^= polynomial; crc ^= polynomial;
return crc; return crc;
} }
public static uint Calculate(byte[] data) public static uint Calculate(byte[] data)
{ {
return Calculate(data, 0xFFFFFFFF); return Calculate(data, 0xFFFFFFFF);
@@ -125,6 +125,7 @@ namespace OpenRA.FileFormats
crc ^= polynomial; crc ^= polynomial;
return crc; return crc;
} }
public static unsafe uint Calculate(byte* data, uint len) public static unsafe uint Calculate(byte* data, uint len)
{ {
return Calculate(data, len, 0xFFFFFFFF); return Calculate(data, len, 0xFFFFFFFF);

View File

@@ -50,7 +50,7 @@ namespace OpenRA.FileFormats
if ((count & 0x8000) == 0) if ((count & 0x8000) == 0)
{ {
// case 2 // case 2
destIndex += (count & 0x7FFF); destIndex += count & 0x7FFF;
} }
else if ((count & 0x4000) == 0) else if ((count & 0x4000) == 0)
{ {

View File

@@ -54,7 +54,6 @@ namespace OpenRA.FileFormats
{ {
case "IHDR": case "IHDR":
{ {
var width = IPAddress.NetworkToHostOrder(cr.ReadInt32()); var width = IPAddress.NetworkToHostOrder(cr.ReadInt32());
var height = IPAddress.NetworkToHostOrder(cr.ReadInt32()); var height = IPAddress.NetworkToHostOrder(cr.ReadInt32());
var bitDepth = cr.ReadByte(); var bitDepth = cr.ReadByte();
@@ -67,8 +66,8 @@ namespace OpenRA.FileFormats
if (interlace != 0) throw new InvalidDataException("Interlacing not supported"); if (interlace != 0) throw new InvalidDataException("Interlacing not supported");
bitmap = new Bitmap(width, height, MakePixelFormat(bitDepth, colorType)); bitmap = new Bitmap(width, height, MakePixelFormat(bitDepth, colorType));
} }
break; break;
case "PLTE": case "PLTE":
@@ -80,6 +79,7 @@ namespace OpenRA.FileFormats
palette[i] = Color.FromArgb(r, g, b); palette[i] = Color.FromArgb(r, g, b);
} }
} }
break; break;
case "tRNS": case "tRNS":
@@ -87,12 +87,14 @@ namespace OpenRA.FileFormats
for (var i = 0; i < length; i++) for (var i = 0; i < length; i++)
palette[i] = Color.FromArgb(cr.ReadByte(), palette[i]); palette[i] = Color.FromArgb(cr.ReadByte(), palette[i]);
} }
break; break;
case "IDAT": case "IDAT":
{ {
data.AddRange(content); data.AddRange(content);
} }
break; break;
case "IEND": case "IEND":
@@ -168,8 +170,8 @@ namespace OpenRA.FileFormats
} }
[Flags] [Flags]
enum PngColorType { Indexed = 1, Color = 2, Alpha = 4 }; enum PngColorType { Indexed = 1, Color = 2, Alpha = 4 }
enum PngFilter { None, Sub, Up, Average, Paeth }; enum PngFilter { None, Sub, Up, Average, Paeth }
static PixelFormat MakePixelFormat(byte bitDepth, PngColorType colorType) static PixelFormat MakePixelFormat(byte bitDepth, PngColorType colorType)
{ {

View File

@@ -96,6 +96,7 @@ namespace OpenRA.FileFormats
l.VoxelMap[x, y].Add(z, v); l.VoxelMap[x, y].Add(z, v);
z++; z++;
} }
// Skip duplicate count // Skip duplicate count
s.ReadUInt8(); s.ReadUInt8();
} while (z < l.Size[2]); } while (z < l.Size[2]);
@@ -104,7 +105,6 @@ namespace OpenRA.FileFormats
public VxlReader(Stream s) public VxlReader(Stream s)
{ {
if (!s.ReadASCII(16).StartsWith("Voxel Animation")) if (!s.ReadASCII(16).StartsWith("Voxel Animation"))
throw new InvalidDataException("Invalid vxl header"); throw new InvalidDataException("Invalid vxl header");

View File

@@ -30,7 +30,7 @@ namespace OpenRA.FileFormats
public readonly int DataSize; public readonly int DataSize;
public readonly byte[] RawOutput; public readonly byte[] RawOutput;
public enum WaveType { Pcm = 0x1, ImaAdpcm = 0x11 }; public enum WaveType { Pcm = 0x1, ImaAdpcm = 0x11 }
public static WaveType Type { get; private set; } public static WaveType Type { get; private set; }
public WavLoader(Stream s) public WavLoader(Stream s)
@@ -69,6 +69,7 @@ namespace OpenRA.FileFormats
UncompressedSize = s.ReadInt32(); UncompressedSize = s.ReadInt32();
s.ReadBytes(chunkSize - 4); s.ReadBytes(chunkSize - 4);
} }
break; break;
case "data": case "data":
DataSize = s.ReadInt32(); DataSize = s.ReadInt32();
@@ -80,6 +81,7 @@ namespace OpenRA.FileFormats
var chunkSize = s.ReadInt32(); var chunkSize = s.ReadInt32();
s.ReadBytes(chunkSize); s.ReadBytes(chunkSize);
} }
break; break;
} }
} }

View File

@@ -34,7 +34,7 @@ namespace OpenRA.FileFormats
entries.Add(new string(chars.ToArray())); entries.Add(new string(chars.ToArray()));
// Skip comment // Skip comment
while ((c = reader.ReadChar()) != 0); while ((c = reader.ReadChar()) != 0) { }
} }
} }

View File

@@ -88,6 +88,7 @@ namespace OpenRA.FileSystem
return new MixFile(filename, type, order); return new MixFile(filename, type, order);
} }
if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase))
return new ZipFile(filename, order); return new ZipFile(filename, order);
if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase)) if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase))

View File

@@ -51,6 +51,7 @@ namespace OpenRA.FileSystem
var TOCreader = new BinaryReader(s); var TOCreader = new BinaryReader(s);
var fileCountInDirs = new List<uint>(); var fileCountInDirs = new List<uint>();
// Parse directories // Parse directories
for (var i = 0; i < DirCount; i++) for (var i = 0; i < DirCount; i++)
fileCountInDirs.Add(ParseDirectory(TOCreader)); fileCountInDirs.Add(ParseDirectory(TOCreader));
@@ -59,7 +60,6 @@ namespace OpenRA.FileSystem
foreach (var fileCount in fileCountInDirs) foreach (var fileCount in fileCountInDirs)
for (var i = 0; i < fileCount; i++) for (var i = 0; i < fileCount; i++)
ParseFile(reader); ParseFile(reader);
} }
static uint ParseDirectory(BinaryReader reader) static uint ParseDirectory(BinaryReader reader)
@@ -84,7 +84,7 @@ namespace OpenRA.FileSystem
var ChunkSize = reader.ReadUInt16(); var ChunkSize = reader.ReadUInt16();
reader.ReadBytes(4); reader.ReadBytes(4);
var NameLength = reader.ReadByte(); var NameLength = reader.ReadByte();
var FileName = new String(reader.ReadChars(NameLength)); var FileName = new string(reader.ReadChars(NameLength));
var hash = PackageEntry.HashFilename(FileName, PackageHashType.Classic); var hash = PackageEntry.HashFilename(FileName, PackageHashType.Classic);
if (!index.ContainsKey(hash)) if (!index.ContainsKey(hash))

View File

@@ -68,9 +68,8 @@ namespace OpenRA.FileSystem
entries = ParseHeader(s, isCncMix ? 0 : 4, out dataStart); entries = ParseHeader(s, isCncMix ? 0 : 4, out dataStart);
index = entries.ToDictionaryWithConflictLog(x => x.Hash, index = entries.ToDictionaryWithConflictLog(x => x.Hash,
"{0} ({1} format, Encrypted: {2}, DataStart: {3})".F(filename, (isCncMix ? "C&C" : "RA/TS/RA2"), isEncrypted, dataStart), "{0} ({1} format, Encrypted: {2}, DataStart: {3})".F(filename, isCncMix ? "C&C" : "RA/TS/RA2", isEncrypted, dataStart),
null, x => "(offs={0}, len={1})".F(x.Offset, x.Length) null, x => "(offs={0}, len={1})".F(x.Offset, x.Length));
);
} }
static List<PackageEntry> ParseHeader(Stream s, long offset, out long headerEnd) static List<PackageEntry> ParseHeader(Stream s, long offset, out long headerEnd)

View File

@@ -20,6 +20,7 @@ namespace OpenRA.FileSystem
public class PackageEntry public class PackageEntry
{ {
public const int Size = 12;
public readonly uint Hash; public readonly uint Hash;
public readonly uint Offset; public readonly uint Offset;
public readonly uint Length; public readonly uint Length;
@@ -88,6 +89,7 @@ namespace OpenRA.FileSystem
while (i-- != 0) while (i-- != 0)
name += name[a << 2]; name += name[a << 2];
} }
return CRC32.Calculate(Encoding.ASCII.GetBytes(name)); return CRC32.Calculate(Encoding.ASCII.GetBytes(name));
} }
@@ -104,7 +106,5 @@ namespace OpenRA.FileSystem
var crcHash = HashFilename(s, PackageHashType.CRC32); // TS var crcHash = HashFilename(s, PackageHashType.CRC32); // TS
Names.Add(crcHash, s); Names.Add(crcHash, s);
} }
public const int Size = 12;
} }
} }

View File

@@ -27,6 +27,10 @@ namespace OpenRA
{ {
public static class Game public static class Game
{ {
public const int NetTickScale = 3; // 120 ms net tick for 40 ms local tick
public const int Timestep = 40;
public const int TimestepJankThreshold = 250; // Don't catch up for delays larger than 250ms
public static ModData modData; public static ModData modData;
public static Settings Settings; public static Settings Settings;
public static ICursor Cursor; public static ICursor Cursor;
@@ -83,9 +87,6 @@ namespace OpenRA
public static int RenderFrame = 0; public static int RenderFrame = 0;
public static int NetFrameNumber { get { return orderManager.NetFrameNumber; } } public static int NetFrameNumber { get { return orderManager.NetFrameNumber; } }
public static int LocalTick { get { return orderManager.LocalFrameNumber; } } public static int LocalTick { get { return orderManager.LocalFrameNumber; } }
public const int NetTickScale = 3; // 120 ms net tick for 40 ms local tick
public const int Timestep = 40;
public const int TimestepJankThreshold = 250; // Don't catch up for delays larger than 250ms
public static event Action<string, int> OnRemoteDirectConnect = (a, b) => { }; public static event Action<string, int> OnRemoteDirectConnect = (a, b) => { };
public static event Action<OrderManager> ConnectionStateChanged = _ => { }; public static event Action<OrderManager> ConnectionStateChanged = _ => { };
@@ -148,6 +149,7 @@ namespace OpenRA
orderManager.World = new World(map, orderManager, isShellmap); orderManager.World = new World(map, orderManager, isShellmap);
orderManager.World.Timestep = Timestep; orderManager.World.Timestep = Timestep;
} }
if (worldRenderer != null) if (worldRenderer != null)
worldRenderer.Dispose(); worldRenderer.Dispose();
worldRenderer = new WorldRenderer(orderManager.World); worldRenderer = new WorldRenderer(orderManager.World);
@@ -417,7 +419,7 @@ namespace OpenRA
} }
var worldTimestep = world == null ? Timestep : world.Timestep; var worldTimestep = world == null ? Timestep : world.Timestep;
var worldTickDelta = (tick - orderManager.LastTickTime); var worldTickDelta = tick - orderManager.LastTickTime;
if (worldTimestep != 0 && worldTickDelta >= worldTimestep) if (worldTimestep != 0 && worldTickDelta >= worldTimestep)
{ {
using (new PerfSample("tick_time")) using (new PerfSample("tick_time"))
@@ -426,7 +428,6 @@ namespace OpenRA
// If dt < TickJankThreshold then we should try and catch up by repeatedly ticking // If dt < TickJankThreshold then we should try and catch up by repeatedly ticking
// If dt >= TickJankThreshold then we should accept the jank and progress at the normal rate // If dt >= TickJankThreshold then we should accept the jank and progress at the normal rate
// dt is rounded down to an integer tick count in order to preserve fractional tick components. // dt is rounded down to an integer tick count in order to preserve fractional tick components.
var integralTickTimestep = (worldTickDelta / worldTimestep) * worldTimestep; var integralTickTimestep = (worldTickDelta / worldTimestep) * worldTimestep;
orderManager.LastTickTime += integralTickTimestep >= TimestepJankThreshold ? integralTickTimestep : worldTimestep; orderManager.LastTickTime += integralTickTimestep >= TimestepJankThreshold ? integralTickTimestep : worldTimestep;

View File

@@ -21,6 +21,7 @@ namespace OpenRA
public string MapUid; public string MapUid;
public string MapTitle; public string MapTitle;
public DateTime StartTimeUtc; public DateTime StartTimeUtc;
// Game end timestamp (when the recoding stopped). // Game end timestamp (when the recoding stopped).
public DateTime EndTimeUtc; public DateTime EndTimeUtc;
@@ -133,34 +134,36 @@ namespace OpenRA
public class Player public class Player
{ {
//
// Start-up information // Start-up information
//
public int ClientIndex; public int ClientIndex;
// The player name, not guaranteed to be unique. // The player name, not guaranteed to be unique.
public string Name; public string Name;
public bool IsHuman; public bool IsHuman;
public bool IsBot; public bool IsBot;
// The faction name (aka Country) // The faction name (aka Country)
public string FactionName; public string FactionName;
// The faction id (aka Country, aka Race) // The faction id (aka Country, aka Race)
public string FactionId; public string FactionId;
public HSLColor Color; public HSLColor Color;
// The team id on start-up, or 0 if the player is not part of the team. // The team id on start-up, or 0 if the player is not part of the team.
public int Team; public int Team;
public int SpawnPoint; public int SpawnPoint;
// True if the faction was chosen at random; otherwise, false // True if the faction was chosen at random; otherwise, false
public bool IsRandomFaction; public bool IsRandomFaction;
// True if the spawn point was chosen at random; otherwise, false.</summary> // True if the spawn point was chosen at random; otherwise, false.</summary>
public bool IsRandomSpawnPoint; public bool IsRandomSpawnPoint;
//
// Information gathered at a later stage // Information gathered at a later stage
//
// The game outcome for this player // The game outcome for this player
public WinState Outcome; public WinState Outcome;
// The time when this player won or lost the game // The time when this player won or lost the game
public DateTime OutcomeTimestampUtc; public DateTime OutcomeTimestampUtc;
} }

View File

@@ -73,6 +73,7 @@ namespace OpenRA
result.Nodes.RemoveAll(a => a.Key.StartsWith("-")); result.Nodes.RemoveAll(a => a.Key.StartsWith("-"));
return result; return result;
} }
return node; return node;
} }

View File

@@ -15,6 +15,7 @@ namespace OpenRA.Graphics
{ {
public class Animation public class Animation
{ {
readonly int defaultTick = 40; // 25 fps == 40 ms
public Sequence CurrentSequence { get; private set; } public Sequence CurrentSequence { get; private set; }
public bool IsDecoration = false; public bool IsDecoration = false;
public Func<bool> Paused; public Func<bool> Paused;
@@ -26,7 +27,6 @@ namespace OpenRA.Graphics
string name; string name;
readonly int defaultTick = 40; // 25 fps == 40 ms
bool tickAlways; bool tickAlways;
public string Name { get { return name; } } public string Name { get { return name; } }

View File

@@ -51,4 +51,3 @@ namespace OpenRA.Graphics
} }
} }
} }

View File

@@ -38,6 +38,7 @@ namespace OpenRA.Graphics
{ {
return lineWidth; return lineWidth;
} }
set set
{ {
if (LineWidth != value) if (LineWidth != value)

View File

@@ -23,6 +23,7 @@ namespace OpenRA.Graphics
uint this[int index] { get; } uint this[int index] { get; }
void CopyToArray(Array destination, int destinationOffset); void CopyToArray(Array destination, int destinationOffset);
} }
public interface IPaletteRemap { Color GetRemappedColor(Color original, int index); } public interface IPaletteRemap { Color GetRemappedColor(Color original, int index); }
public static class Palette public static class Palette

View File

@@ -177,6 +177,7 @@ namespace OpenRA.Graphics
{ {
return currentBatchRenderer; return currentBatchRenderer;
} }
set set
{ {
if (currentBatchRenderer == value) if (currentBatchRenderer == value)

View File

@@ -30,6 +30,7 @@ namespace OpenRA.Graphics
CreateBuffer(); CreateBuffer();
return data; return data;
} }
public bool Buffered { get { return data != null || texture == null; } } public bool Buffered { get { return data != null || texture == null; } }
public Sheet(Size size) public Sheet(Size size)
@@ -83,7 +84,6 @@ namespace OpenRA.Graphics
if (data != null) if (data != null)
{ {
if (dirty) if (dirty)
{ {
texture.SetData(data, Size.Width, Size.Height); texture.SetData(data, Size.Width, Size.Height);

View File

@@ -99,4 +99,3 @@ namespace OpenRA.Graphics
} }
} }
} }

View File

@@ -40,10 +40,10 @@ namespace OpenRA.Graphics
this.fractionalOffset = offset / this.size; this.fractionalOffset = offset / this.size;
left = (float)(bounds.Left) / sheet.Size.Width; left = (float)bounds.Left / sheet.Size.Width;
top = (float)(bounds.Top) / sheet.Size.Height; top = (float)bounds.Top / sheet.Size.Height;
right = (float)(bounds.Right) / sheet.Size.Width; right = (float)bounds.Right / sheet.Size.Width;
bottom = (float)(bounds.Bottom) / sheet.Size.Height; bottom = (float)bounds.Bottom / sheet.Size.Height;
} }
} }

View File

@@ -136,7 +136,6 @@ namespace OpenRA.Graphics
} }
} }
s.sheet.CommitData(); s.sheet.CommitData();
return g; return g;

View File

@@ -38,6 +38,7 @@ namespace OpenRA.Graphics
public SpriteCache(ISpriteLoader[] loaders, string[] exts, SheetBuilder sheetBuilder) public SpriteCache(ISpriteLoader[] loaders, string[] exts, SheetBuilder sheetBuilder)
{ {
SheetBuilder = sheetBuilder; SheetBuilder = sheetBuilder;
// Include extension-less version // Include extension-less version
exts = exts.Append("").ToArray(); exts = exts.Append("").ToArray();
sprites = new Cache<string, Sprite[]>(filename => SpriteLoader.GetSprites(filename, exts, loaders, sheetBuilder)); sprites = new Cache<string, Sprite[]>(filename => SpriteLoader.GetSprites(filename, exts, loaders, sheetBuilder));

View File

@@ -17,6 +17,8 @@ namespace OpenRA.Graphics
{ {
public static class Util public static class Util
{ {
// yes, our channel order is nuts.
static readonly int[] channelMasks = { 2, 1, 0, 3 };
static float[] channelSelect = { 0.75f, 0.25f, -0.25f, -0.75f }; static float[] channelSelect = { 0.75f, 0.25f, -0.25f, -0.75f };
public static void FastCreateQuad(Vertex[] vertices, float2 o, Sprite r, int palette, int nv, float2 size) public static void FastCreateQuad(Vertex[] vertices, float2 o, Sprite r, int palette, int nv, float2 size)
@@ -38,8 +40,6 @@ namespace OpenRA.Graphics
vertices[nv + 3] = new Vertex(d, r.left, r.bottom, attribP, attribC); vertices[nv + 3] = new Vertex(d, r.left, r.bottom, attribP, attribC);
} }
static readonly int[] channelMasks = { 2, 1, 0, 3 }; // yes, our channel order is nuts.
public static void FastCopyIntoChannel(Sprite dest, byte[] src) { FastCopyIntoChannel(dest, 0, src); } public static void FastCopyIntoChannel(Sprite dest, byte[] src) { FastCopyIntoChannel(dest, 0, src); }
public static void FastCopyIntoChannel(Sprite dest, int channelOffset, byte[] src) public static void FastCopyIntoChannel(Sprite dest, int channelOffset, byte[] src)
{ {
@@ -58,6 +58,7 @@ namespace OpenRA.Graphics
data[destOffset] = src[srcOffset]; data[destOffset] = src[srcOffset];
destOffset += 4; destOffset += 4;
} }
destOffset += destSkip; destOffset += destSkip;
} }
} }

View File

@@ -31,4 +31,3 @@ namespace OpenRA.Graphics
} }
} }
} }

View File

@@ -92,7 +92,7 @@ namespace OpenRA.Graphics
if (world.OrderGenerator != null) if (world.OrderGenerator != null)
effectRenderables = effectRenderables.Concat(world.OrderGenerator.RenderAfterWorld(this, world)); effectRenderables = effectRenderables.Concat(world.OrderGenerator.RenderAfterWorld(this, world));
// Iterating via foreach() copies the structs, so enumerate by index // Iterating via foreach copies the structs, so enumerate by index
var renderables = worldRenderables.Concat(effectRenderables).ToList(); var renderables = worldRenderables.Concat(effectRenderables).ToList();
Game.Renderer.WorldVoxelRenderer.BeginFrame(); Game.Renderer.WorldVoxelRenderer.BeginFrame();

View File

@@ -22,6 +22,7 @@ namespace OpenRA
{ {
get { return initDict.Value; } get { return initDict.Value; }
} }
Lazy<TypeDictionary> initDict; Lazy<TypeDictionary> initDict;
public ActorReference(string type) : this(type, new Dictionary<string, MiniYaml>()) { } public ActorReference(string type) : this(type, new Dictionary<string, MiniYaml>()) { }
@@ -53,6 +54,7 @@ namespace OpenRA
var initName = init.GetType().Name; var initName = init.GetType().Name;
ret.Nodes.Add(new MiniYamlNode(initName.Substring(0, initName.Length - 4), FieldSaver.Save(init))); ret.Nodes.Add(new MiniYamlNode(initName.Substring(0, initName.Length - 4), FieldSaver.Save(init)));
} }
return ret; return ret;
} }

View File

@@ -113,6 +113,12 @@ namespace OpenRA
public class Map public class Map
{ {
public const int MaxTilesInCircleRange = 50;
public readonly TileShape TileShape;
[FieldLoader.Ignore]
public readonly WVec[] SubCellOffsets;
public readonly SubCell DefaultSubCell;
public readonly SubCell LastSubCell;
[FieldLoader.Ignore] public IFolder Container; [FieldLoader.Ignore] public IFolder Container;
public string Path { get; private set; } public string Path { get; private set; }
@@ -131,12 +137,6 @@ namespace OpenRA
public Bitmap CustomPreview; public Bitmap CustomPreview;
public bool InvalidCustomRules { get; private set; } public bool InvalidCustomRules { get; private set; }
public readonly TileShape TileShape;
[FieldLoader.Ignore]
public readonly WVec[] SubCellOffsets;
public readonly SubCell DefaultSubCell;
public readonly SubCell LastSubCell;
public WVec OffsetOfSubCell(SubCell subCell) { return SubCellOffsets[(int)subCell]; } public WVec OffsetOfSubCell(SubCell subCell) { return SubCellOffsets[(int)subCell]; }
[FieldLoader.LoadUsing("LoadOptions")] [FieldLoader.LoadUsing("LoadOptions")]
@@ -421,12 +421,10 @@ namespace OpenRA
root.Add(new MiniYamlNode("Options", FieldSaver.SaveDifferences(Options, new MapOptions()))); root.Add(new MiniYamlNode("Options", FieldSaver.SaveDifferences(Options, new MapOptions())));
root.Add(new MiniYamlNode("Players", null, root.Add(new MiniYamlNode("Players", null,
Players.Select(p => new MiniYamlNode("PlayerReference@{0}".F(p.Key), FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList()) Players.Select(p => new MiniYamlNode("PlayerReference@{0}".F(p.Key), FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList()));
);
root.Add(new MiniYamlNode("Actors", null, root.Add(new MiniYamlNode("Actors", null,
Actors.Value.Select(x => new MiniYamlNode(x.Key, x.Value.Save())).ToList()) Actors.Value.Select(x => new MiniYamlNode(x.Key, x.Value.Save())).ToList()));
);
root.Add(new MiniYamlNode("Smudges", MiniYaml.FromList<SmudgeReference>(Smudges.Value))); root.Add(new MiniYamlNode("Smudges", MiniYaml.FromList<SmudgeReference>(Smudges.Value)));
root.Add(new MiniYamlNode("Rules", null, RuleDefinitions)); root.Add(new MiniYamlNode("Rules", null, RuleDefinitions));
@@ -623,7 +621,6 @@ namespace OpenRA
// (b) Therefore: // (b) Therefore:
// - ax + by adds (a - b) * 512 + 512 to u // - ax + by adds (a - b) * 512 + 512 to u
// - ax + by adds (a + b) * 512 + 512 to v // - ax + by adds (a + b) * 512 + 512 to v
var z = Contains(cell) ? 512 * MapHeight.Value[cell] : 0; var z = Contains(cell) ? 512 * MapHeight.Value[cell] : 0;
return new WPos(512 * (cell.X - cell.Y + 1), 512 * (cell.X + cell.Y + 1), z); return new WPos(512 * (cell.X - cell.Y + 1), 512 * (cell.X + cell.Y + 1), z);
} }
@@ -721,7 +718,6 @@ namespace OpenRA
string ComputeHash() string ComputeHash()
{ {
// UID is calculated by taking an SHA1 of the yaml and binary data // UID is calculated by taking an SHA1 of the yaml and binary data
using (var ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
// Read the relevant data into the buffer // Read the relevant data into the buffer
@@ -851,7 +847,6 @@ namespace OpenRA
return new WRange(Math.Min(x, y) * dir.Length); return new WRange(Math.Min(x, y) * dir.Length);
} }
public const int MaxTilesInCircleRange = 50;
static CVec[][] TilesByDistance = InitTilesByDistance(MaxTilesInCircleRange); static CVec[][] TilesByDistance = InitTilesByDistance(MaxTilesInCircleRange);
static CVec[][] InitTilesByDistance(int max) static CVec[][] InitTilesByDistance(int max)

View File

@@ -132,6 +132,7 @@ namespace OpenRA
// Milliseconds to wait on one loop when nothing to do // Milliseconds to wait on one loop when nothing to do
var emptyDelay = 50; var emptyDelay = 50;
// Keep the thread alive for at least 5 seconds after the last minimap generation // Keep the thread alive for at least 5 seconds after the last minimap generation
var maxKeepAlive = 5000 / emptyDelay; var maxKeepAlive = 5000 / emptyDelay;
var keepAlive = maxKeepAlive; var keepAlive = maxKeepAlive;
@@ -151,6 +152,7 @@ namespace OpenRA
break; break;
} }
} }
if (todo.Count == 0) if (todo.Count == 0)
{ {
Thread.Sleep(emptyDelay); Thread.Sleep(emptyDelay);
@@ -170,6 +172,7 @@ namespace OpenRA
createdPreview = true; createdPreview = true;
bitmap = Minimap.RenderMapPreview(modData.DefaultRules.TileSets[p.Map.Tileset], p.Map, modData.DefaultRules, true); bitmap = Minimap.RenderMapPreview(modData.DefaultRules.TileSets[p.Map.Tileset], p.Map, modData.DefaultRules, true);
} }
// Note: this is not generally thread-safe, but it works here because: // Note: this is not generally thread-safe, but it works here because:
// (a) This worker is the only thread writing to this sheet // (a) This worker is the only thread writing to this sheet
// (b) The main thread is the only thread reading this sheet // (b) The main thread is the only thread reading this sheet
@@ -192,7 +195,9 @@ namespace OpenRA
Thread.Sleep(Environment.ProcessorCount == 1 ? 25 : 5); Thread.Sleep(Environment.ProcessorCount == 1 ? 25 : 5);
} }
} }
sheetBuilder.Current.ReleaseBuffer(); sheetBuilder.Current.ReleaseBuffer();
// The buffer is not fully reclaimed until changes are written out to the texture. // The buffer is not fully reclaimed until changes are written out to the texture.
// We will access the texture in order to force changes to be written out, allowing the buffer to be freed. // We will access the texture in order to force changes to be written out, allowing the buffer to be freed.
Game.RunAfterTick(() => sheetBuilder.Current.GetTexture()); Game.RunAfterTick(() => sheetBuilder.Current.GetTexture());

View File

@@ -177,7 +177,6 @@ namespace OpenRA
var mapUrl = Game.Settings.Game.MapRepository + Uid; var mapUrl = Game.Settings.Game.MapRepository + Uid;
try try
{ {
var request = WebRequest.Create(mapUrl); var request = WebRequest.Create(mapUrl);
request.Method = "HEAD"; request.Method = "HEAD";
var res = request.GetResponse(); var res = request.GetResponse();

View File

@@ -115,6 +115,7 @@ namespace OpenRA
throw new InvalidDataException("Duplicate key '{0}' in {1}".F(y.Key, y.Location), ex); throw new InvalidDataException("Duplicate key '{0}' in {1}".F(y.Key, y.Location), ex);
} }
} }
return ret; return ret;
} }

View File

@@ -44,6 +44,7 @@ namespace OpenRA
LoadScreen.Init(Manifest, Manifest.LoadScreen.ToDictionary(my => my.Value)); LoadScreen.Init(Manifest, Manifest.LoadScreen.ToDictionary(my => my.Value));
LoadScreen.Display(); LoadScreen.Display();
} }
WidgetLoader = new WidgetLoader(this); WidgetLoader = new WidgetLoader(this);
RulesetCache = new RulesetCache(this); RulesetCache = new RulesetCache(this);
RulesetCache.LoadingProgress += HandleLoadingProgress; RulesetCache.LoadingProgress += HandleLoadingProgress;

View File

@@ -198,6 +198,7 @@ namespace OpenRA.Network
var boxedCopy = Expression.Convert(getMember, typeof(object)); var boxedCopy = Expression.Convert(getMember, typeof(object));
return Expression.Lambda<Func<ISync, object>>(boxedCopy, name, new[] { syncParam }).Compile(); return Expression.Lambda<Func<ISync, object>>(boxedCopy, name, new[] { syncParam }).Compile();
} }
return MemberToString(getMember, memberType, name); return MemberToString(getMember, memberType, name);
} }

View File

@@ -126,6 +126,5 @@ namespace OpenRA
return path; return path;
} }
} }
} }

View File

@@ -21,14 +21,12 @@ using OpenRA.Traits;
namespace OpenRA namespace OpenRA
{ {
public enum PowerState { Normal, Low, Critical }; public enum PowerState { Normal, Low, Critical }
public enum WinState { Undefined, Won, Lost }; public enum WinState { Undefined, Won, Lost }
public class Player : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding public class Player : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding
{ {
public Actor PlayerActor; public readonly Actor PlayerActor;
public WinState WinState = WinState.Undefined;
public readonly HSLColor Color; public readonly HSLColor Color;
public readonly string PlayerName; public readonly string PlayerName;
@@ -39,6 +37,8 @@ namespace OpenRA
public readonly bool Playable = true; public readonly bool Playable = true;
public readonly int ClientIndex; public readonly int ClientIndex;
public readonly PlayerReference PlayerReference; public readonly PlayerReference PlayerReference;
public WinState WinState = WinState.Undefined;
public bool IsBot; public bool IsBot;
public int SpawnPoint; public int SpawnPoint;
public bool HasObjectives = false; public bool HasObjectives = false;
@@ -84,6 +84,7 @@ namespace OpenRA
botType = pr.Bot; botType = pr.Bot;
Country = ChooseCountry(world, pr.Race); Country = ChooseCountry(world, pr.Race);
} }
PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) }); PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) });
Shroud = PlayerActor.Trait<Shroud>(); Shroud = PlayerActor.Trait<Shroud>();

View File

@@ -39,6 +39,7 @@ namespace OpenRA.Primitives
a = da.Action + a; a = da.Action + a;
} }
} }
a(); a();
} }
} }

View File

@@ -58,7 +58,7 @@ namespace OpenRA.Primitives
return BitAllocator<T>.GetStrings(Value).JoinWith(","); return BitAllocator<T>.GetStrings(Value).JoinWith(",");
} }
public static bool operator ==(Bits<T> me, Bits<T> other) { return (me.Value == other.Value); } public static bool operator ==(Bits<T> me, Bits<T> other) { return me.Value == other.Value; }
public static bool operator !=(Bits<T> me, Bits<T> other) { return !(me == other); } public static bool operator !=(Bits<T> me, Bits<T> other) { return !(me == other); }
public bool Equals(Bits<T> other) { return other == this; } public bool Equals(Bits<T> other) { return other == this; }

View File

@@ -40,6 +40,7 @@ namespace OpenRA.Primitives
return result; return result;
} }
} }
public bool ContainsKey(T key) { return cache.ContainsKey(key); } public bool ContainsKey(T key) { return cache.ContainsKey(key); }
public bool TryGetValue(T key, out U value) { return cache.TryGetValue(key, out value); } public bool TryGetValue(T key, out U value) { return cache.TryGetValue(key, out value); }
public int Count { get { return cache.Count; } } public int Count { get { return cache.Count; } }

View File

@@ -18,6 +18,7 @@ namespace OpenRA.Primitives
public class ObservableCollection<T> : Collection<T>, IObservableCollection public class ObservableCollection<T> : Collection<T>, IObservableCollection
{ {
public event Action<object> OnAdd = k => { }; public event Action<object> OnAdd = k => { };
// TODO Workaround for https://github.com/OpenRA/OpenRA/issues/6101 // TODO Workaround for https://github.com/OpenRA/OpenRA/issues/6101
#pragma warning disable 67 #pragma warning disable 67
public event Action<object> OnRemove = k => { }; public event Action<object> OnRemove = k => { };

View File

@@ -34,6 +34,7 @@ namespace OpenRA.Primitives
public event Action<object> OnAdd = k => { }; public event Action<object> OnAdd = k => { };
public event Action<object> OnRemove = k => { }; public event Action<object> OnRemove = k => { };
// TODO Workaround for https://github.com/OpenRA/OpenRA/issues/6101 // TODO Workaround for https://github.com/OpenRA/OpenRA/issues/6101
#pragma warning disable 67 #pragma warning disable 67
public event Action<int> OnRemoveAt = i => { }; public event Action<int> OnRemoveAt = i => { };

View File

@@ -46,7 +46,7 @@ namespace OpenRA.Primitives
} }
} }
public bool Empty { get { return (level == 0); } } public bool Empty { get { return level == 0; } }
T At(int level, int index) { return items[level][index]; } T At(int level, int index) { return items[level][index]; }
T Above(int level, int index) { return items[level - 1][index >> 1]; } T Above(int level, int index) { return items[level - 1][index >> 1]; }

View File

@@ -68,7 +68,7 @@ namespace OpenRA
public static float2 operator /(float2 a, float2 b) { return new float2(a.X / b.X, a.Y / b.Y); } public static float2 operator /(float2 a, float2 b) { return new float2(a.X / b.X, a.Y / b.Y); }
public static float2 operator /(float2 a, float b) { return new float2(a.X / b, a.Y / b); } public static float2 operator /(float2 a, float b) { return new float2(a.X / b, a.Y / b); }
public static bool operator ==(float2 me, float2 other) { return (me.X == other.X && me.Y == other.Y); } public static bool operator ==(float2 me, float2 other) { return me.X == other.X && me.Y == other.Y; }
public static bool operator !=(float2 me, float2 other) { return !(me == other); } public static bool operator !=(float2 me, float2 other) { return !(me == other); }
public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); }

View File

@@ -10,8 +10,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics; using System.Diagnostics;
using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;

View File

@@ -67,7 +67,7 @@ namespace OpenRA.Scripting
throw new LuaException("Unable to convert parameter {0} to {1}".F(i, pi[i].ParameterType.Name)); throw new LuaException("Unable to convert parameter {0} to {1}".F(i, pi[i].ParameterType.Name));
} }
var ret = (mi.Invoke(Target, clrArgs)); var ret = mi.Invoke(Target, clrArgs);
return ret.ToLuaValue(context); return ret.ToLuaValue(context);
} }

View File

@@ -69,7 +69,7 @@ namespace OpenRA.Scripting
// TODO: Lua 5.3 will introduce an integer type, so this will be able to go away // TODO: Lua 5.3 will introduce an integer type, so this will be able to go away
if (value is LuaNumber && t.IsAssignableFrom(typeof(int))) if (value is LuaNumber && t.IsAssignableFrom(typeof(int)))
{ {
clrObject = (int)(value.ToNumber().Value); clrObject = (int)value.ToNumber().Value;
return true; return true;
} }

View File

@@ -64,9 +64,11 @@ namespace OpenRA
actors.RemoveAll(a => !a.IsInWorld || (!a.Owner.IsAlliedWith(world.RenderPlayer) && world.FogObscures(a))); actors.RemoveAll(a => !a.IsInWorld || (!a.Owner.IsAlliedWith(world.RenderPlayer) && world.FogObscures(a)));
foreach (var cg in controlGroups.Values) foreach (var cg in controlGroups.Values)
{
// note: NOT `!a.IsInWorld`, since that would remove things that are in transports. // note: NOT `!a.IsInWorld`, since that would remove things that are in transports.
cg.RemoveAll(a => a.Destroyed || a.Owner != world.LocalPlayer); cg.RemoveAll(a => a.Destroyed || a.Owner != world.LocalPlayer);
} }
}
Cache<int, List<Actor>> controlGroups = new Cache<int, List<Actor>>(_ => new List<Actor>()); Cache<int, List<Actor>> controlGroups = new Cache<int, List<Actor>>(_ => new List<Actor>());

View File

@@ -17,13 +17,13 @@ namespace OpenRA.Server
{ {
public class Connection public class Connection
{ {
public const int MaxOrderLength = 131072;
public Socket socket; public Socket socket;
public List<byte> data = new List<byte>(); public List<byte> data = new List<byte>();
public ReceiveState State = ReceiveState.Header; public ReceiveState State = ReceiveState.Header;
public int ExpectLength = 8; public int ExpectLength = 8;
public int Frame = 0; public int Frame = 0;
public int MostRecentFrame = 0; public int MostRecentFrame = 0;
public const int MaxOrderLength = 131072;
public int TimeSinceLastResponse { get { return Game.RunTime - lastReceivedTime; } } public int TimeSinceLastResponse { get { return Game.RunTime - lastReceivedTime; } }
public bool TimeoutMessageShown = false; public bool TimeoutMessageShown = false;
@@ -107,12 +107,11 @@ namespace OpenRA.Server
MostRecentFrame = Frame; MostRecentFrame = Frame;
ExpectLength = 8; ExpectLength = 8;
State = ReceiveState.Header; State = ReceiveState.Header;
} break; } break;
} }
} }
} }
} }
public enum ReceiveState { Header, Data }; public enum ReceiveState { Header, Data }
} }

View File

@@ -35,9 +35,9 @@ namespace OpenRA.Support
if (index == 0) Generate(); if (index == 0) Generate();
var y = mt[index]; var y = mt[index];
y ^= (y >> 11); y ^= y >> 11;
y ^= ((y << 7) & 2636928640); y ^= (y << 7) & 2636928640;
y ^= ((y << 15) & 4022730752); y ^= (y << 15) & 4022730752;
y ^= y >> 18; y ^= y >> 18;
index = (index + 1) % 624; index = (index + 1) % 624;
@@ -77,7 +77,7 @@ namespace OpenRA.Support
var y = (mt[i] & 0x80000000) | (mt[(i + 1) % 624] & 0x7fffffff); var y = (mt[i] & 0x80000000) | (mt[(i + 1) % 624] & 0x7fffffff);
mt[i] = mt[(i + 397u) % 624u] ^ (y >> 1); mt[i] = mt[(i + 397u) % 624u] ^ (y >> 1);
if ((y & 1) == 1) if ((y & 1) == 1)
mt[i] = (mt[i] ^ 2567483615); mt[i] = mt[i] ^ 2567483615;
} }
} }
} }

View File

@@ -91,6 +91,7 @@ namespace OpenRA.Support
sum += samples[n]; sum += samples[n];
i++; i++;
} }
return sum / i; return sum / i;
} }

View File

@@ -18,6 +18,11 @@ namespace OpenRA.Support
{ {
public sealed class PerfTimer : IDisposable public sealed class PerfTimer : IDisposable
{ {
// Tree settings
const int Digits = 6;
const string IndentationString = "| ";
const string FormatSeperation = " ms ";
static readonly string FormatString = "{0," + Digits + ":0}" + FormatSeperation + "{1}";
readonly string name; readonly string name;
readonly float thresholdMs; readonly float thresholdMs;
readonly byte depth; readonly byte depth;
@@ -27,12 +32,6 @@ namespace OpenRA.Support
static ThreadLocal<PerfTimer> Parent = new ThreadLocal<PerfTimer>(); static ThreadLocal<PerfTimer> Parent = new ThreadLocal<PerfTimer>();
// Tree settings
const int Digits = 6;
const string IndentationString = "| ";
const string FormatSeperation = " ms ";
static readonly string FormatString = "{0," + Digits + ":0}" + FormatSeperation + "{1}";
public PerfTimer(string name, float thresholdMs = 0) public PerfTimer(string name, float thresholdMs = 0)
{ {
this.name = name; this.name = name;

View File

@@ -86,8 +86,9 @@ namespace OpenRA
Indent(sb, d); Indent(sb, d);
sb.AppendFormat("TypeName=`{0}`", tle.TypeName); sb.AppendFormat("TypeName=`{0}`", tle.TypeName);
} }
else // TODO: more exception types else
{ {
// TODO: more exception types
} }
if (e.InnerException != null) if (e.InnerException != null)

View File

@@ -29,6 +29,7 @@ namespace OpenRA
else else
end = mid; end = mid;
} }
return start; return start;
} }
} }
@@ -187,6 +188,7 @@ namespace OpenRA
this.actor = actor; this.actor = actor;
Reset(); Reset();
} }
public void Reset() { index = actors.BinarySearchMany(actor) - 1; } public void Reset() { index = actors.BinarySearchMany(actor) - 1; }
public bool MoveNext() { return ++index < actors.Count && actors[index].ActorID == actor; } public bool MoveNext() { return ++index < actors.Count && actors[index].ActorID == actor; }
public T Current { get { return traits[index]; } } public T Current { get { return traits[index]; } }
@@ -219,6 +221,7 @@ namespace OpenRA
traits = container.traits; traits = container.traits;
Reset(); Reset();
} }
public void Reset() { index = -1; } public void Reset() { index = -1; }
public bool MoveNext() { return ++index < actors.Count; } public bool MoveNext() { return ++index < actors.Count; }
public TraitPair<T> Current { get { return new TraitPair<T> { Actor = actors[index], Trait = traits[index] }; } } public TraitPair<T> Current { get { return new TraitPair<T> { Actor = actors[index], Trait = traits[index] }; } }

View File

@@ -18,4 +18,3 @@ namespace OpenRA.Traits
public class Armor { } public class Armor { }
} }

View File

@@ -132,4 +132,3 @@ namespace OpenRA.Traits
} }
} }
} }

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Traits
public virtual object Create(ActorInitializer init) { return new Health(init, this); } public virtual object Create(ActorInitializer init) { return new Health(init, this); }
} }
public enum DamageState { Undamaged, Light, Medium, Heavy, Critical, Dead }; public enum DamageState { Undamaged, Light, Medium, Heavy, Critical, Dead }
public class Health : ISync, ITick public class Health : ISync, ITick
{ {

View File

@@ -97,6 +97,7 @@ namespace OpenRA.Traits
for (var i = 0; i < Info.ResourceGrowth; i++) for (var i = 0; i < Info.ResourceGrowth; i++)
a.Trait.Seed(a.Actor); a.Trait.Seed(a.Actor);
} }
break; break;
} }

View File

@@ -24,6 +24,8 @@ namespace OpenRA.Traits
public class PlayerResources : ITick, ISync public class PlayerResources : ITick, ISync
{ {
const float displayCashFracPerFrame = .07f;
const int displayCashDeltaPerFrame = 37;
readonly Player Owner; readonly Player Owner;
int AdviceInterval; int AdviceInterval;
@@ -97,8 +99,6 @@ namespace OpenRA.Traits
return true; return true;
} }
const float displayCashFracPerFrame = .07f;
const int displayCashDeltaPerFrame = 37;
int nextSiloAdviceTime = 0; int nextSiloAdviceTime = 0;
int nextCashTickTime = 0; int nextCashTickTime = 0;
@@ -131,7 +131,6 @@ namespace OpenRA.Traits
var move = Math.Min(Math.Max((int)(diff * displayCashFracPerFrame), var move = Math.Min(Math.Max((int)(diff * displayCashFracPerFrame),
displayCashDeltaPerFrame), diff); displayCashDeltaPerFrame), diff);
if (DisplayCash < Cash) if (DisplayCash < Cash)
{ {
DisplayCash += move; DisplayCash += move;
@@ -159,7 +158,6 @@ namespace OpenRA.Traits
} }
} }
public void playCashTickUp(Actor self) public void playCashTickUp(Actor self)
{ {
if (Game.Settings.Sound.CashTicks) if (Game.Settings.Sound.CashTicks)

View File

@@ -135,7 +135,5 @@ namespace OpenRA.Traits
} }
} }
} }
} }
} }

View File

@@ -168,6 +168,5 @@ namespace OpenRA.Traits
return "Invalid"; return "Invalid";
} }
} }
} }
} }

View File

@@ -21,8 +21,8 @@ using OpenRA.Primitives;
namespace OpenRA.Traits namespace OpenRA.Traits
{ {
// depends on the order of pips in WorldRenderer.cs! // depends on the order of pips in WorldRenderer.cs!
public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue, Ammo, AmmoEmpty }; public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue, Ammo, AmmoEmpty }
public enum TagType { None, Fake, Primary }; public enum TagType { None, Fake, Primary }
[Flags] [Flags]
public enum Stance public enum Stance
@@ -65,7 +65,7 @@ namespace OpenRA.Traits
Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued); Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued);
} }
[Flags] public enum TargetModifiers { None = 0, ForceAttack = 1, ForceQueue = 2, ForceMove = 4 }; [Flags] public enum TargetModifiers { None = 0, ForceAttack = 1, ForceQueue = 2, ForceMove = 4 }
public static class TargetModifiersExts public static class TargetModifiersExts
{ {
@@ -173,6 +173,7 @@ namespace OpenRA.Traits
nearestDistance = dist; nearestDistance = dist;
} }
} }
return nearest; return nearest;
} }
} }

View File

@@ -91,9 +91,11 @@ namespace OpenRA.Traits
{ {
start = current; start = current;
} }
if (prev == act) if (prev == act)
break; break;
} }
return act; return act;
} }

View File

@@ -476,7 +476,6 @@ namespace OpenRA.Traits
yield return bins[j * cols + i]; yield return bins[j * cols + i];
} }
public IEnumerable<Actor> ActorsInBox(WPos a, WPos b) public IEnumerable<Actor> ActorsInBox(WPos a, WPos b)
{ {
var left = Math.Min(a.X, b.X); var left = Math.Min(a.X, b.X);

View File

@@ -25,6 +25,7 @@ namespace OpenRA
if (Angle < 0) if (Angle < 0)
Angle += 1024; Angle += 1024;
} }
public static readonly WAngle Zero = new WAngle(0); public static readonly WAngle Zero = new WAngle(0);
public static WAngle FromFacing(int facing) { return new WAngle(facing * 4); } public static WAngle FromFacing(int facing) { return new WAngle(facing * 4); }
public static WAngle FromDegrees(int degrees) { return new WAngle(degrees * 1024 / 360); } public static WAngle FromDegrees(int degrees) { return new WAngle(degrees * 1024 / 360); }
@@ -32,7 +33,7 @@ namespace OpenRA
public static WAngle operator -(WAngle a, WAngle b) { return new WAngle(a.Angle - b.Angle); } public static WAngle operator -(WAngle a, WAngle b) { return new WAngle(a.Angle - b.Angle); }
public static WAngle operator -(WAngle a) { return new WAngle(-a.Angle); } public static WAngle operator -(WAngle a) { return new WAngle(-a.Angle); }
public static bool operator ==(WAngle me, WAngle other) { return (me.Angle == other.Angle); } public static bool operator ==(WAngle me, WAngle other) { return me.Angle == other.Angle; }
public static bool operator !=(WAngle me, WAngle other) { return !(me == other); } public static bool operator !=(WAngle me, WAngle other) { return !(me == other); }
public override int GetHashCode() { return Angle.GetHashCode(); } public override int GetHashCode() { return Angle.GetHashCode(); }

View File

@@ -32,7 +32,7 @@ namespace OpenRA
public static WPos operator -(WPos a, WVec b) { return new WPos(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static WPos operator -(WPos a, WVec b) { return new WPos(a.X - b.X, a.Y - b.Y, a.Z - b.Z); }
public static WVec operator -(WPos a, WPos b) { return new WVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static WVec operator -(WPos a, WPos b) { return new WVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z); }
public static bool operator ==(WPos me, WPos other) { return (me.X == other.X && me.Y == other.Y && me.Z == other.Z); } public static bool operator ==(WPos me, WPos other) { return me.X == other.X && me.Y == other.Y && me.Z == other.Z; }
public static bool operator !=(WPos me, WPos other) { return !(me == other); } public static bool operator !=(WPos me, WPos other) { return !(me == other); }
public static WPos Lerp(WPos a, WPos b, int mul, int div) { return a + (b - a) * mul / div; } public static WPos Lerp(WPos a, WPos b, int mul, int div) { return a + (b - a) * mul / div; }

View File

@@ -39,7 +39,7 @@ namespace OpenRA
public static bool operator <=(WRange a, WRange b) { return a.Range <= b.Range; } public static bool operator <=(WRange a, WRange b) { return a.Range <= b.Range; }
public static bool operator >=(WRange a, WRange b) { return a.Range >= b.Range; } public static bool operator >=(WRange a, WRange b) { return a.Range >= b.Range; }
public static bool operator ==(WRange me, WRange other) { return (me.Range == other.Range); } public static bool operator ==(WRange me, WRange other) { return me.Range == other.Range; }
public static bool operator !=(WRange me, WRange other) { return !(me == other); } public static bool operator !=(WRange me, WRange other) { return !(me == other); }
// Sampled a N-sample probability density function in the range [-1024..1024] // Sampled a N-sample probability density function in the range [-1024..1024]
@@ -94,6 +94,7 @@ namespace OpenRA
return 1; return 1;
return Range.CompareTo(((WRange)obj).Range); return Range.CompareTo(((WRange)obj).Range);
} }
public int CompareTo(WRange other) { return Range.CompareTo(other.Range); } public int CompareTo(WRange other) { return Range.CompareTo(other.Range); }
public override string ToString() { return Range.ToString(); } public override string ToString() { return Range.ToString(); }
@@ -139,6 +140,7 @@ namespace OpenRA
default: throw new LuaException("WPos does not define a member '{0}'".F(key)); default: throw new LuaException("WPos does not define a member '{0}'".F(key));
} }
} }
set set
{ {
throw new LuaException("WRange is read-only. Use WRange.New to create a new value"); throw new LuaException("WRange is read-only. Use WRange.New to create a new value");

View File

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

View File

@@ -32,7 +32,7 @@ namespace OpenRA
public static WVec operator *(int a, WVec b) { return new WVec(a * b.X, a * b.Y, a * b.Z); } public static WVec operator *(int a, WVec b) { return new WVec(a * b.X, a * b.Y, a * b.Z); }
public static WVec operator *(WVec a, int b) { return b * a; } public static WVec operator *(WVec a, int b) { return b * a; }
public static bool operator ==(WVec me, WVec other) { return (me.X == other.X && me.Y == other.Y && me.Z == other.Z); } public static bool operator ==(WVec me, WVec other) { return me.X == other.X && me.Y == other.Y && me.Z == other.Z; }
public static bool operator !=(WVec me, WVec other) { return !(me == other); } public static bool operator !=(WVec me, WVec other) { return !(me == other); }
public static int Dot(WVec a, WVec b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } public static int Dot(WVec a, WVec b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; }

View File

@@ -33,7 +33,7 @@ namespace OpenRA.Widgets
if (ClickThrough || !RenderBounds.Contains(mi.Location)) if (ClickThrough || !RenderBounds.Contains(mi.Location))
return false; return false;
if (!Draggable || moving && (!TakeMouseFocus(mi) || mi.Button != MouseButton.Left)) if (!Draggable || (moving && (!TakeMouseFocus(mi) || mi.Button != MouseButton.Left)))
return true; return true;
if (prevMouseLocation == null) if (prevMouseLocation == null)

View File

@@ -15,7 +15,10 @@ namespace OpenRA.Widgets
{ {
public class ButtonWidget : Widget public class ButtonWidget : Widget
{ {
public readonly string TooltipContainer;
public readonly string TooltipTemplate = "BUTTON_TOOLTIP";
public Func<ButtonWidget, Hotkey> GetKey = _ => Hotkey.Invalid; public Func<ButtonWidget, Hotkey> GetKey = _ => Hotkey.Invalid;
public Hotkey Key public Hotkey Key
{ {
get { return GetKey(this); } get { return GetKey(this); }
@@ -44,8 +47,6 @@ namespace OpenRA.Widgets
public Action<MouseInput> OnMouseUp = _ => { }; public Action<MouseInput> OnMouseUp = _ => { };
Lazy<TooltipContainerWidget> tooltipContainer; Lazy<TooltipContainerWidget> tooltipContainer;
public readonly string TooltipContainer;
public readonly string TooltipTemplate = "BUTTON_TOOLTIP";
[Translate] public string TooltipText; [Translate] public string TooltipText;
public Func<string> GetTooltipText; public Func<string> GetTooltipText;
@@ -149,14 +150,15 @@ namespace OpenRA.Widgets
return YieldMouseFocus(mi); return YieldMouseFocus(mi);
} }
} }
// Only fire the onMouseUp event if we successfully lost focus, and were pressed
else if (HasMouseFocus && mi.Event == MouseInputEvent.Up) else if (HasMouseFocus && mi.Event == MouseInputEvent.Up)
{ {
// Only fire the onMouseUp event if we successfully lost focus, and were pressed
if (Depressed && !disabled) if (Depressed && !disabled)
OnMouseUp(mi); OnMouseUp(mi);
return YieldMouseFocus(mi); return YieldMouseFocus(mi);
} }
if (mi.Event == MouseInputEvent.Down) if (mi.Event == MouseInputEvent.Down)
{ {
// OnMouseDown returns false if the button shouldn't be pressed // OnMouseDown returns false if the button shouldn't be pressed
@@ -210,7 +212,7 @@ namespace OpenRA.Widgets
var colordisabled = GetColorDisabled(); var colordisabled = GetColorDisabled();
var contrast = GetContrastColor(); var contrast = GetContrastColor();
var s = font.Measure(text); var s = font.Measure(text);
var stateOffset = (Depressed) ? new int2(VisualHeight, VisualHeight) : new int2(0, 0); var stateOffset = Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0);
var position = new int2(rb.X + (UsableWidth - s.X) / 2, rb.Y - BaseLine + (Bounds.Height - s.Y) / 2); var position = new int2(rb.X + (UsableWidth - s.X) / 2, rb.Y - BaseLine + (Bounds.Height - s.Y) / 2);
DrawBackground(rb, disabled, Depressed, Ui.MouseOverWidget == this, highlighted); DrawBackground(rb, disabled, Depressed, Ui.MouseOverWidget == this, highlighted);

View File

@@ -8,7 +8,6 @@
*/ */
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -42,6 +41,7 @@ namespace OpenRA.Widgets
result = default(T); result = default(T);
return false; return false;
} }
result = FieldLoader.GetValue<T>(key, s); result = FieldLoader.GetValue<T>(key, s);
return true; return true;
} }

View File

@@ -36,16 +36,14 @@ namespace OpenRA.Widgets
public override void Draw() public override void Draw()
{ {
base.Draw(); base.Draw();
var stateOffset = (Depressed) ? new int2(VisualHeight, VisualHeight) : new int2(0, 0); var stateOffset = Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0);
var image = ChromeProvider.GetImage("scrollbar", IsDisabled() ? "down_pressed" : "down_arrow"); var image = ChromeProvider.GetImage("scrollbar", IsDisabled() ? "down_pressed" : "down_arrow");
var rb = RenderBounds; var rb = RenderBounds;
var color = GetColor(); var color = GetColor();
var colorDisabled = GetColorDisabled(); var colorDisabled = GetColorDisabled();
WidgetUtils.DrawRGBA( image, WidgetUtils.DrawRGBA(image, stateOffset + new float2(rb.Right - rb.Height + 4, rb.Top + (rb.Height - image.bounds.Height) / 2));
stateOffset + new float2( rb.Right - rb.Height + 4,
rb.Top + (rb.Height - image.bounds.Height) / 2 ));
WidgetUtils.FillRectWithColor(new Rectangle(stateOffset.X + rb.Right - rb.Height, WidgetUtils.FillRectWithColor(new Rectangle(stateOffset.X + rb.Right - rb.Height,
stateOffset.Y + rb.Top + 3, 1, rb.Height - 6), stateOffset.Y + rb.Top + 3, 1, rb.Height - 6),
@@ -154,6 +152,7 @@ namespace OpenRA.Widgets
panel.AddChild(item); panel.AddChild(item);
} }
} }
panel.Bounds.Height = Math.Min(height, panel.ContentHeight); panel.Bounds.Height = Math.Min(height, panel.ContentHeight);
AttachPanel(panel); AttachPanel(panel);
} }

View File

@@ -44,8 +44,6 @@ namespace OpenRA.Widgets
public void AdjustChildren() public void AdjustChildren()
{ {
} }
} }
} }

View File

@@ -87,6 +87,7 @@ namespace OpenRA.Widgets
{ {
return; return;
} }
var rect = RenderBounds; var rect = RenderBounds;
var origin = new float2(rect.Left, rect.Bottom); var origin = new float2(rect.Left, rect.Bottom);
@@ -147,14 +148,16 @@ namespace OpenRA.Widgets
Game.Renderer.LineRenderer.DrawLine(origin + new float2(x, 0), origin + new float2(x, -5), Color.White, Color.White); Game.Renderer.LineRenderer.DrawLine(origin + new float2(x, 0), origin + new float2(x, -5), Color.White, Color.White);
tiny.DrawText(GetXAxisValueFormat().F(n), origin + new float2(x, 2), Color.White); tiny.DrawText(GetXAxisValueFormat().F(n), origin + new float2(x, 2), Color.White);
} }
bold.DrawText(GetXAxisLabel(), origin + new float2(width / 2, 20), Color.White); bold.DrawText(GetXAxisLabel(), origin + new float2(width / 2, 20), Color.White);
for (var y = (GetDisplayFirstYAxisValue() ? 0 : yStep); y <= height; y += yStep) for (var y = GetDisplayFirstYAxisValue() ? 0 : yStep; y <= height; y += yStep)
{ {
var yValue = y / scale; var yValue = y / scale;
Game.Renderer.LineRenderer.DrawLine(origin + new float2(width - 5, -y), origin + new float2(width, -y), Color.White, Color.White); Game.Renderer.LineRenderer.DrawLine(origin + new float2(width - 5, -y), origin + new float2(width, -y), Color.White, Color.White);
tiny.DrawText(GetYAxisValueFormat().F(yValue), origin + new float2(width + 2, -y), Color.White); tiny.DrawText(GetYAxisValueFormat().F(yValue), origin + new float2(width + 2, -y), Color.White);
} }
bold.DrawText(GetYAxisLabel(), origin + new float2(width + 40, -(height / 2)), Color.White); bold.DrawText(GetYAxisLabel(), origin + new float2(width + 40, -(height / 2)), Color.White);
Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(width, 0), Color.White, Color.White); Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(width, 0), Color.White, Color.White);

View File

@@ -30,6 +30,7 @@ namespace OpenRA.Widgets
public class ScrollPanelWidget : Widget public class ScrollPanelWidget : Widget
{ {
readonly Ruleset modRules;
public int ScrollbarWidth = 24; public int ScrollbarWidth = 24;
public int ItemSpacing = 2; public int ItemSpacing = 2;
public int ButtonDepth = ChromeMetrics.Get<int>("ButtonDepth"); public int ButtonDepth = ChromeMetrics.Get<int>("ButtonDepth");
@@ -59,8 +60,6 @@ namespace OpenRA.Widgets
// The current value is the actual list offset at the moment // The current value is the actual list offset at the moment
float currentListOffset; float currentListOffset;
readonly Ruleset modRules;
// Setting "smooth" to true will only update the target list offset. // Setting "smooth" to true will only update the target list offset.
// Setting "smooth" to false will also set the current list offset, // Setting "smooth" to false will also set the current list offset,
// i.e. it will scroll immediately. // i.e. it will scroll immediately.

View File

@@ -133,4 +133,3 @@ namespace OpenRA.Widgets
} }
} }
} }

View File

@@ -133,6 +133,8 @@ namespace OpenRA.Widgets
public abstract class Widget public abstract class Widget
{ {
public readonly List<Widget> Children = new List<Widget>();
// Info defined in YAML // Info defined in YAML
public string Id = null; public string Id = null;
public string X = "0"; public string X = "0";
@@ -150,7 +152,6 @@ namespace OpenRA.Widgets
public Widget Parent = null; public Widget Parent = null;
public Func<bool> IsVisible; public Func<bool> IsVisible;
public Widget() { IsVisible = () => Visible; } public Widget() { IsVisible = () => Visible; }
public readonly List<Widget> Children = new List<Widget>();
public Widget(Widget widget) public Widget(Widget widget)
{ {
@@ -335,6 +336,7 @@ namespace OpenRA.Widgets
return false; return false;
var oldMouseOver = Ui.MouseOverWidget; var oldMouseOver = Ui.MouseOverWidget;
// Send the event to the deepest children first and bubble up if unhandled // Send the event to the deepest children first and bubble up if unhandled
foreach (var child in Children.OfType<Widget>().Reverse()) foreach (var child in Children.OfType<Widget>().Reverse())
if (child.HandleMouseInputOuter(mi)) if (child.HandleMouseInputOuter(mi))
@@ -452,6 +454,7 @@ namespace OpenRA.Widgets
if (w != null) if (w != null)
return w; return w;
} }
return null; return null;
} }

View File

@@ -57,6 +57,7 @@ namespace OpenRA.Widgets
Math.Min(left.Y, (int)s.size.Y)); Math.Min(left.Y, (int)s.size.Y));
ss = new Sprite(s.sheet, rr, s.channel); ss = new Sprite(s.sheet, rr, s.channel);
} }
DrawRGBA(ss, new float2(x, y)); DrawRGBA(ss, new float2(x, y));
} }
} }
@@ -206,6 +207,7 @@ namespace OpenRA.Widgets
return string.Join("\n", lines); return string.Join("\n", lines);
} }
return text; return text;
} }

View File

@@ -116,7 +116,11 @@ namespace OpenRA
IOrderGenerator orderGenerator_; IOrderGenerator orderGenerator_;
public IOrderGenerator OrderGenerator public IOrderGenerator OrderGenerator
{ {
get { return orderGenerator_; } get
{
return orderGenerator_;
}
set set
{ {
Sync.AssertUnsynced("The current order generator may not be changed from synced code"); Sync.AssertUnsynced("The current order generator may not be changed from synced code");