diff --git a/OpenRA.Editor/Surface.cs b/OpenRA.Editor/Surface.cs index 6ec1c46f5d..fc5e33fbcc 100644 --- a/OpenRA.Editor/Surface.cs +++ b/OpenRA.Editor/Surface.cs @@ -26,7 +26,7 @@ namespace OpenRA.Editor { public static CPos Location(this ActorReference ar) { - return (CPos)ar.InitDict.Get().value; + return (CPos)ar.InitDict.Get().Value(null); } public static void DrawStringContrast(this SGraphics g, Font f, string s, int x, int y, Brush fg, Brush bg) diff --git a/OpenRA.Game/CVec.cs b/OpenRA.Game/CVec.cs index 0203110af4..4ef9c790a1 100644 --- a/OpenRA.Game/CVec.cs +++ b/OpenRA.Game/CVec.cs @@ -58,7 +58,7 @@ namespace OpenRA public override string ToString() { return X + "," + Y; } - public static readonly CVec[] directions = + public static readonly CVec[] Directions = { new CVec(-1, -1), new CVec(-1, 0), diff --git a/OpenRA.Game/Exts.cs b/OpenRA.Game/Exts.cs index 949bd57b6f..9d09320a1b 100644 --- a/OpenRA.Game/Exts.cs +++ b/OpenRA.Game/Exts.cs @@ -372,13 +372,17 @@ namespace OpenRA { var result = new T[width, height]; for (var i = 0; i < width; i++) + { for (var j = 0; j < height; j++) - // Workaround for broken ternary operators in certain versions of mono (3.10 and - // certain versions of the 3.8 series): https://bugzilla.xamarin.com/show_bug.cgi?id=23319 + { + // Workaround for broken ternary operators in certain versions of mono (3.10 and certain versions of the 3.8 series): https://bugzilla.xamarin.com/show_bug.cgi?id=23319 if (i <= ts.GetUpperBound(0) && j <= ts.GetUpperBound(1)) result[i, j] = ts[i, j]; else result[i, j] = t; + } + } + return result; } diff --git a/OpenRA.Game/FieldLoader.cs b/OpenRA.Game/FieldLoader.cs index 9ec3847d44..66eef0972b 100644 --- a/OpenRA.Game/FieldLoader.cs +++ b/OpenRA.Game/FieldLoader.cs @@ -85,11 +85,11 @@ namespace OpenRA static readonly object[] NoIndexes = { }; public static void LoadField(object target, string key, string value) { - const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; key = key.Trim(); - var field = target.GetType().GetField(key, flags); + var field = target.GetType().GetField(key, Flags); if (field != null) { var sa = field.GetCustomAttributes(false).DefaultIfEmpty(SerializeAttribute.Default).First(); @@ -98,7 +98,7 @@ namespace OpenRA return; } - var prop = target.GetType().GetProperty(key, flags); + var prop = target.GetType().GetProperty(key, Flags); if (prop != null) { var sa = prop.GetCustomAttributes(false).DefaultIfEmpty(SerializeAttribute.Default).First(); @@ -503,11 +503,11 @@ namespace OpenRA internal Func GetLoader(Type type) { - const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy; + const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy; if (!string.IsNullOrEmpty(Loader)) { - var method = type.GetMethod(Loader, flags); + var method = type.GetMethod(Loader, Flags); if (method == null) throw new InvalidOperationException("{0} does not specify a loader function '{1}'".F(type.Name, Loader)); diff --git a/OpenRA.Game/FileFormats/Blast.cs b/OpenRA.Game/FileFormats/Blast.cs index 31c9d628a5..ff6873718c 100644 --- a/OpenRA.Game/FileFormats/Blast.cs +++ b/OpenRA.Game/FileFormats/Blast.cs @@ -66,7 +66,7 @@ namespace OpenRA.FileFormats if (coded < 0 || coded > 1) throw new NotImplementedException("Invalid datastream"); - var EncodedLiterals = coded == 1; + var encodedLiterals = coded == 1; // log2(dictionary size) - 6 var dict = br.ReadBits(8); @@ -145,7 +145,7 @@ namespace OpenRA.FileFormats 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; if (next == MAXWIN) { diff --git a/OpenRA.Game/FileFormats/Blowfish.cs b/OpenRA.Game/FileFormats/Blowfish.cs index 6501f932c3..a84fb85101 100644 --- a/OpenRA.Game/FileFormats/Blowfish.cs +++ b/OpenRA.Game/FileFormats/Blowfish.cs @@ -21,7 +21,7 @@ namespace OpenRA.FileFormats uint c = key[j++ % key.Length]; uint d = key[j++ % key.Length]; - m_p[i] ^= a << 24 | b << 16 | c << 8 | d; + lookupMfromP[i] ^= a << 24 | b << 16 | c << 8 | d; } uint l = 0, r = 0; @@ -29,16 +29,16 @@ namespace OpenRA.FileFormats for (var i = 0; i < 18;) { Encrypt(ref l, ref r); - m_p[i++] = l; - m_p[i++] = r; + lookupMfromP[i++] = l; + lookupMfromP[i++] = r; } for (var i = 0; i < 4; ++i) for (var j = 0; j < 256;) { Encrypt(ref l, ref r); - m_s[i, j++] = l; - m_s[i, j++] = r; + lookupMfromS[i, j++] = l; + lookupMfromS[i, j++] = r; } } @@ -69,57 +69,57 @@ namespace OpenRA.FileFormats void Encrypt(ref uint a, ref uint b) { - uint _a = a, _b = b; - _a ^= m_p[0]; + uint tempA = a, tempB = b; + tempA ^= lookupMfromP[0]; var x = false; for (var i = 1; i <= 16; i++, x ^= true) { if (x) - Round(ref _a, _b, i); + Round(ref tempA, tempB, i); else - Round(ref _b, _a, i); + Round(ref tempB, tempA, i); } - _b ^= m_p[17]; + tempB ^= lookupMfromP[17]; - a = _b; - b = _a; + a = tempB; + b = tempA; } void Decrypt(ref uint a, ref uint b) { - uint _a = a, _b = b; - _a ^= m_p[17]; + uint tempA = a, tempB = b; + tempA ^= lookupMfromP[17]; var x = false; for (var i = 16; i >= 1; i--, x ^= true) { if (x) - Round(ref _a, _b, i); + Round(ref tempA, tempB, i); else - Round(ref _b, _a, i); + Round(ref tempB, tempA, i); } - _b ^= m_p[0]; + tempB ^= lookupMfromP[0]; - a = _b; - b = _a; + a = tempB; + b = tempA; } uint S(uint x, int i) { - return m_s[i, (x >> ((3 - i) << 3)) & 0xff]; + return lookupMfromS[i, (x >> ((3 - i) << 3)) & 0xff]; } - uint bf_f(uint x) + uint ConvertBFtoF(uint x) { return ((S(x, 0) + S(x, 1)) ^ S(x, 2)) + S(x, 3); } void Round(ref uint a, uint b, int n) { - a ^= bf_f(b) ^ m_p[n]; + a ^= ConvertBFtoF(b) ^ lookupMfromP[n]; } static uint SwapBytes(uint i) @@ -129,7 +129,7 @@ namespace OpenRA.FileFormats return i; } - uint[] m_p = new uint[] { + uint[] lookupMfromP = new uint[] { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, @@ -137,7 +137,7 @@ namespace OpenRA.FileFormats 0x9216d5d9, 0x8979fb1b }; - uint[,] m_s = new uint[,] { + uint[,] lookupMfromS = new uint[,] { { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, diff --git a/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs b/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs index c1e0213004..e5c6fb16cf 100644 --- a/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs +++ b/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs @@ -13,36 +13,36 @@ using System.Linq; namespace OpenRA.FileFormats { - /* possibly the fugliest C# i've ever seen. */ + /* TODO: Convert this direct C port into readable code. */ class BlowfishKeyProvider { - const string pubkeyStr = "AihRvNoIbTn85FZRYNZRcT+i6KpU+maCsEqr3Q5q+LDB5tH7Tz2qQ38V"; + const string PublicKeyString = "AihRvNoIbTn85FZRYNZRcT+i6KpU+maCsEqr3Q5q+LDB5tH7Tz2qQ38V"; class PublicKey { - public uint[] key1 = new uint[64]; - public uint[] key2 = new uint[64]; - public uint len; + public uint[] KeyOne = new uint[64]; + public uint[] KeyTwo = new uint[64]; + public uint Len; } PublicKey pubkey = new PublicKey(); - uint[] glob1 = new uint[64]; - uint glob1_bitlen, glob1_len_x2; - uint[] glob2 = new uint[130]; - uint[] glob1_hi = new uint[4]; - uint[] glob1_hi_inv = new uint[4]; - uint glob1_hi_bitlen; - uint glob1_hi_inv_lo, glob1_hi_inv_hi; + uint[] globOne = new uint[64]; + uint globOneBitLen, globOneLenXTwo; + uint[] globTwo = new uint[130]; + uint[] globOneHigh = new uint[4]; + uint[] globOneHighInv = new uint[4]; + uint globOneHighBitLen; + uint globOneHighInvLow, globOneHighInvHigh; - static void init_bignum(uint[] n, uint val, uint len) + static void InitBigNum(uint[] n, uint val, uint len) { for (var i = 0; i < len; i++) n[i] = 0; n[0] = val; } - static void move_key_to_big(uint[] n, byte[] key, uint klen, uint blen) + static void MoveKeyToBig(uint[] n, byte[] key, uint klen, uint blen) { byte sign; @@ -51,9 +51,9 @@ namespace OpenRA.FileFormats unsafe { - fixed (uint* _pn = &n[0]) + fixed (uint* tempPn = &n[0]) { - var pn = (byte*)_pn; + var pn = (byte*)tempPn; var i = blen * 4; for (; i > klen; i--) pn[i - 1] = (byte)sign; for (; i > 0; i--) pn[i - 1] = key[klen - i]; @@ -61,7 +61,7 @@ namespace OpenRA.FileFormats } } - static void key_to_bignum(uint[] n, byte[] key, uint len) + static void KeyToBigNum(uint[] n, byte[] key, uint len) { uint keylen; int i; @@ -84,10 +84,10 @@ namespace OpenRA.FileFormats } if (keylen <= len * 4) - move_key_to_big(n, key.Skip(j).ToArray(), keylen, len); + MoveKeyToBig(n, key.Skip(j).ToArray(), keylen, len); } - static uint len_bignum(uint[] n, uint len) + static uint LenBigNum(uint[] n, uint len) { uint i; i = len - 1; @@ -95,10 +95,10 @@ namespace OpenRA.FileFormats return i + 1; } - static uint bitlen_bignum(uint[] n, uint len) + static uint BitLenBigNum(uint[] n, uint len) { uint ddlen, bitlen, mask; - ddlen = len_bignum(n, len); + ddlen = LenBigNum(n, len); if (ddlen == 0) return 0; bitlen = ddlen * 32; mask = 0x80000000; @@ -111,21 +111,21 @@ namespace OpenRA.FileFormats return bitlen; } - void init_pubkey() + void InitPublicKey() { - init_bignum(pubkey.key2, 0x10001, 64); + InitBigNum(pubkey.KeyTwo, 0x10001, 64); - key_to_bignum(pubkey.key1, Convert.FromBase64String(pubkeyStr), 64); - pubkey.len = bitlen_bignum(pubkey.key1, 64) - 1; + KeyToBigNum(pubkey.KeyOne, Convert.FromBase64String(PublicKeyString), 64); + pubkey.Len = BitLenBigNum(pubkey.KeyOne, 64) - 1; } - uint len_predata() + uint LenPreData() { - var a = (pubkey.len - 1) / 8; + var a = (pubkey.Len - 1) / 8; return (55 / a + 1) * (a + 1); } - static int cmp_bignum(uint[] n1, uint[] n2, uint len) + static int CompareBigNum(uint[] n1, uint[] n2, uint len) { while (len > 0) { @@ -137,12 +137,12 @@ namespace OpenRA.FileFormats return 0; } - static void mov_bignum(uint[] dest, uint[] src, uint len) + static void MoveBigNum(uint[] dest, uint[] src, uint len) { Array.Copy(src, dest, len); } - static void shr_bignum(uint[] n, int bits, int len) + static void ShrBigNum(uint[] n, int bits, int len) { int i; var i2 = bits / 32; @@ -154,12 +154,11 @@ namespace OpenRA.FileFormats } if (bits == 0) return; - for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 - - bits)); + for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 - bits)); n[i] = n[i] >> bits; } - static void shl_bignum(uint[] n, int bits, int len) + static void ShlBigNum(uint[] n, int bits, int len) { int i, i2; @@ -172,25 +171,24 @@ namespace OpenRA.FileFormats } if (bits == 0) return; - for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 - - bits)); + for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 - bits)); n[0] <<= bits; } - static uint sub_bignum(uint[] dest, uint[] src1, uint[] src2, uint carry, int len) + static uint SubBigNum(uint[] dest, uint[] src1, uint[] src2, uint carry, int len) { uint i1, i2; len += len; unsafe { - fixed (uint* _ps1 = &src1[0]) - fixed (uint* _ps2 = &src2[0]) - fixed (uint* _pd = &dest[0]) + fixed (uint* tempPs1 = &src1[0]) + fixed (uint* tempPs2 = &src2[0]) + fixed (uint* tempPd = &dest[0]) { - var ps1 = (ushort*)_ps1; - var ps2 = (ushort*)_ps2; - var pd = (ushort*)_pd; + var ps1 = (ushort*)tempPs1; + var ps2 = (ushort*)tempPs2; + var pd = (ushort*)tempPd; while (--len != -1) { @@ -205,7 +203,7 @@ namespace OpenRA.FileFormats return carry; } - static unsafe uint sub_bignum(uint* dest, uint* src1, uint* src2, uint carry, int len) + static unsafe uint SubBigNum(uint* dest, uint* src1, uint* src2, uint carry, int len) { uint i1, i2; @@ -226,29 +224,29 @@ namespace OpenRA.FileFormats return carry; } - static void inv_bignum(uint[] n1, uint[] n2, uint len) + static void InvertBigNum(uint[] n1, uint[] n2, uint len) { - var n_tmp = new uint[64]; - uint n2_bytelen, bit; - int n2_bitlen; + var nTmp = new uint[64]; + uint nTwoByteLen, bit; + int nTwoBitLen; var j = 0; - init_bignum(n_tmp, 0, len); - init_bignum(n1, 0, len); - n2_bitlen = (int)bitlen_bignum(n2, len); - bit = ((uint)1) << (n2_bitlen % 32); - j = ((n2_bitlen + 32) / 32) - 1; - n2_bytelen = (uint)((n2_bitlen - 1) / 32) * 4; - n_tmp[n2_bytelen / 4] |= ((uint)1) << ((n2_bitlen - 1) & 0x1f); + InitBigNum(nTmp, 0, len); + InitBigNum(n1, 0, len); + nTwoBitLen = (int)BitLenBigNum(n2, len); + bit = ((uint)1) << (nTwoBitLen % 32); + j = ((nTwoBitLen + 32) / 32) - 1; + nTwoByteLen = (uint)((nTwoBitLen - 1) / 32) * 4; + nTmp[nTwoByteLen / 4] |= ((uint)1) << ((nTwoBitLen - 1) & 0x1f); - while (n2_bitlen > 0) + while (nTwoBitLen > 0) { - n2_bitlen--; - shl_bignum(n_tmp, 1, (int)len); - if (cmp_bignum(n_tmp, n2, len) != -1) + nTwoBitLen--; + ShlBigNum(nTmp, 1, (int)len); + if (CompareBigNum(nTmp, n2, len) != -1) { - sub_bignum(n_tmp, n_tmp, n2, 0, (int)len); + SubBigNum(nTmp, nTmp, n2, 0, (int)len); n1[j] |= bit; } @@ -260,45 +258,45 @@ namespace OpenRA.FileFormats } } - init_bignum(n_tmp, 0, len); + InitBigNum(nTmp, 0, len); } - static void inc_bignum(uint[] n, uint len) + static void IncrementBigNum(uint[] n, uint len) { var i = 0; while ((++n[i] == 0) && (--len > 0)) i++; } - void init_two_dw(uint[] n, uint len) + void InitTwoDw(uint[] n, uint len) { - mov_bignum(glob1, n, len); - glob1_bitlen = bitlen_bignum(glob1, len); - glob1_len_x2 = (glob1_bitlen + 15) / 16; - mov_bignum(glob1_hi, glob1.Skip((int)len_bignum(glob1, len) - 2).ToArray(), 2); - glob1_hi_bitlen = bitlen_bignum(glob1_hi, 2) - 32; - shr_bignum(glob1_hi, (int)glob1_hi_bitlen, 2); - inv_bignum(glob1_hi_inv, glob1_hi, 2); - shr_bignum(glob1_hi_inv, 1, 2); - glob1_hi_bitlen = (glob1_hi_bitlen + 15) % 16 + 1; - inc_bignum(glob1_hi_inv, 2); - if (bitlen_bignum(glob1_hi_inv, 2) > 32) + MoveBigNum(globOne, n, len); + globOneBitLen = BitLenBigNum(globOne, len); + globOneLenXTwo = (globOneBitLen + 15) / 16; + MoveBigNum(globOneHigh, globOne.Skip((int)LenBigNum(globOne, len) - 2).ToArray(), 2); + globOneHighBitLen = BitLenBigNum(globOneHigh, 2) - 32; + ShrBigNum(globOneHigh, (int)globOneHighBitLen, 2); + InvertBigNum(globOneHighInv, globOneHigh, 2); + ShrBigNum(globOneHighInv, 1, 2); + globOneHighBitLen = (globOneHighBitLen + 15) % 16 + 1; + IncrementBigNum(globOneHighInv, 2); + if (BitLenBigNum(globOneHighInv, 2) > 32) { - shr_bignum(glob1_hi_inv, 1, 2); - glob1_hi_bitlen--; + ShrBigNum(globOneHighInv, 1, 2); + globOneHighBitLen--; } - glob1_hi_inv_lo = (ushort)glob1_hi_inv[0]; - glob1_hi_inv_hi = (ushort)(glob1_hi_inv[0] >> 16); + globOneHighInvLow = (ushort)globOneHighInv[0]; + globOneHighInvHigh = (ushort)(globOneHighInv[0] >> 16); } - static unsafe void mul_bignum_word(ushort* pn1, uint[] n2, uint mul, uint len) + static unsafe void MulBignumWord(ushort* pn1, uint[] n2, uint mul, uint len) { uint i, tmp; unsafe { - fixed (uint* _pn2 = &n2[0]) + fixed (uint* tempPn2 = &n2[0]) { - var pn2 = (ushort*)_pn2; + var pn2 = (ushort*)tempPn2; tmp = 0; for (i = 0; i < len; i++) @@ -314,112 +312,112 @@ namespace OpenRA.FileFormats } } - static void mul_bignum(uint[] dest, uint[] src1, uint[] src2, uint len) + static void MulBigNum(uint[] dest, uint[] src1, uint[] src2, uint len) { - uint i; + uint i; - unsafe - { - fixed (uint* _psrc2 = &src2[0]) - fixed (uint* _pdest = &dest[0]) - { - var psrc2 = (ushort*)_psrc2; - var pdest = (ushort*)_pdest; + unsafe + { + fixed (uint* tempSrc2 = &src2[0]) + fixed (uint* tempPdest = &dest[0]) + { + var psrc2 = (ushort*)tempSrc2; + var pdest = (ushort*)tempPdest; - init_bignum(dest, 0, len * 2); - for (i = 0; i < len * 2; i++) - mul_bignum_word(pdest++, src1, *psrc2++, len * 2); - } - } + InitBigNum(dest, 0, len * 2); + for (i = 0; i < len * 2; i++) + MulBignumWord(pdest++, src1, *psrc2++, len * 2); + } + } } - static void not_bignum(uint[] n, uint len) + static void NotBigNum(uint[] n, uint len) { - uint i; - for (i = 0; i < len; i++) n[i] = ~n[i]; + uint i; + for (i = 0; i < len; i++) n[i] = ~n[i]; } - static void neg_bignum(uint[] n, uint len) + static void NegBigNum(uint[] n, uint len) { - not_bignum(n, len); - inc_bignum(n, len); + NotBigNum(n, len); + IncrementBigNum(n, len); } - unsafe uint get_mulword(uint* n) + unsafe uint GetMulWord(uint* n) { var wn = (ushort*)n; - var i = (uint)((((((((((*(wn - 1) ^ 0xffff) & 0xffff) * glob1_hi_inv_lo + 0x10000) >> 1) - + (((*(wn - 2) ^ 0xffff) * glob1_hi_inv_hi + glob1_hi_inv_hi) >> 1) + 1) - >> 16) + ((((*(wn - 1) ^ 0xffff) & 0xffff) * glob1_hi_inv_hi) >> 1) + - (((*wn ^ 0xffff) * glob1_hi_inv_lo) >> 1) + 1) >> 14) + glob1_hi_inv_hi - * (*wn ^ 0xffff) * 2) >> (int)glob1_hi_bitlen); + var i = (uint)((((((((((*(wn - 1) ^ 0xffff) & 0xffff) * globOneHighInvLow + 0x10000) >> 1) + + (((*(wn - 2) ^ 0xffff) * globOneHighInvHigh + globOneHighInvHigh) >> 1) + 1) + >> 16) + ((((*(wn - 1) ^ 0xffff) & 0xffff) * globOneHighInvHigh) >> 1) + + (((*wn ^ 0xffff) * globOneHighInvLow) >> 1) + 1) >> 14) + globOneHighInvHigh + * (*wn ^ 0xffff) * 2) >> (int)globOneHighBitLen); if (i > 0xffff) i = 0xffff; return i & 0xffff; } - static void dec_bignum(uint[] n, uint len) + static void DecBigNum(uint[] n, uint len) { var i = 0; while ((--n[i] == 0xffffffff) && (--len > 0)) i++; } - void calc_a_bignum(uint[] n1, uint[] n2, uint[] n3, uint len) + void CalcBigNum(uint[] n1, uint[] n2, uint[] n3, uint len) { - uint g2_len_x2, len_diff; + uint globTwoXtwo, lenDiff; unsafe { - fixed (uint* g1 = &glob1[0]) - fixed (uint* g2 = &glob2[0]) + fixed (uint* g1 = &globOne[0]) + fixed (uint* g2 = &globTwo[0]) { - mul_bignum(glob2, n2, n3, len); - glob2[len * 2] = 0; - g2_len_x2 = len_bignum(glob2, len * 2 + 1) * 2; - if (g2_len_x2 >= glob1_len_x2) + MulBigNum(globTwo, n2, n3, len); + globTwo[len * 2] = 0; + globTwoXtwo = LenBigNum(globTwo, len * 2 + 1) * 2; + if (globTwoXtwo >= globOneLenXTwo) { - inc_bignum(glob2, len * 2 + 1); - neg_bignum(glob2, len * 2 + 1); - len_diff = g2_len_x2 + 1 - glob1_len_x2; - var esi = ((ushort*)g2) + (1 + g2_len_x2 - glob1_len_x2); - var edi = ((ushort*)g2) + (g2_len_x2 + 1); - for (; len_diff != 0; len_diff--) + IncrementBigNum(globTwo, len * 2 + 1); + NegBigNum(globTwo, len * 2 + 1); + lenDiff = globTwoXtwo + 1 - globOneLenXTwo; + var esi = ((ushort*)g2) + (1 + globTwoXtwo - globOneLenXTwo); + var edi = ((ushort*)g2) + (globTwoXtwo + 1); + for (; lenDiff != 0; lenDiff--) { edi--; - var tmp = get_mulword((uint*)edi); + var tmp = GetMulWord((uint*)edi); esi--; if (tmp > 0) { - mul_bignum_word(esi, glob1, tmp, 2 * len); + MulBignumWord(esi, globOne, tmp, 2 * len); if ((*edi & 0x8000) == 0) { - if (0 != sub_bignum((uint*)esi, (uint*)esi, g1, 0, (int)len))(*edi)--; + if (0 != SubBigNum((uint*)esi, (uint*)esi, g1, 0, (int)len))(*edi)--; } } } - neg_bignum(glob2, len); - dec_bignum(glob2, len); + NegBigNum(globTwo, len); + DecBigNum(globTwo, len); } - mov_bignum(n1, glob2, len); + MoveBigNum(n1, globTwo, len); } } } - void clear_tmp_vars(uint len) + void ClearTempVars(uint len) { - init_bignum(glob1, 0, len); - init_bignum(glob2, 0, len); - init_bignum(glob1_hi_inv, 0, 4); - init_bignum(glob1_hi, 0, 4); - glob1_bitlen = 0; - glob1_hi_bitlen = 0; - glob1_len_x2 = 0; - glob1_hi_inv_lo = 0; - glob1_hi_inv_hi = 0; + InitBigNum(globOne, 0, len); + InitBigNum(globTwo, 0, len); + InitBigNum(globOneHighInv, 0, 4); + InitBigNum(globOneHigh, 0, 4); + globOneBitLen = 0; + globOneHighBitLen = 0; + globOneLenXTwo = 0; + globOneHighInvLow = 0; + globOneHighInvHigh = 0; } - void calc_a_key(uint[] n1, uint[] n2, uint[] n3, uint[] n4, uint len) + void CalcKey(uint[] n1, uint[] n2, uint[] n3, uint[] n4, uint len) { var n_tmp = new uint[64]; uint n3_len, n4_len; @@ -428,19 +426,19 @@ namespace OpenRA.FileFormats unsafe { - fixed (uint* _pn3 = &n3[0]) + fixed (uint* tempPn3 = &n3[0]) { - var pn3 = _pn3; + var pn3 = tempPn3; - init_bignum(n1, 1, len); - n4_len = len_bignum(n4, len); - init_two_dw(n4, n4_len); - n3_bitlen = (int)bitlen_bignum(n3, n4_len); + InitBigNum(n1, 1, len); + n4_len = LenBigNum(n4, len); + InitTwoDw(n4, n4_len); + n3_bitlen = (int)BitLenBigNum(n3, n4_len); n3_len = (uint)((n3_bitlen + 31) / 32); bit_mask = (((uint)1) << ((n3_bitlen - 1) % 32)) >> 1; pn3 += n3_len - 1; n3_bitlen--; - mov_bignum(n1, n2, n4_len); + MoveBigNum(n1, n2, n4_len); while (--n3_bitlen != -1) { if (bit_mask == 0) @@ -449,40 +447,40 @@ namespace OpenRA.FileFormats pn3--; } - calc_a_bignum(n_tmp, n1, n1, n4_len); + CalcBigNum(n_tmp, n1, n1, n4_len); if ((*pn3 & bit_mask) != 0) - calc_a_bignum(n1, n_tmp, n2, n4_len); + CalcBigNum(n1, n_tmp, n2, n4_len); else - mov_bignum(n1, n_tmp, n4_len); + MoveBigNum(n1, n_tmp, n4_len); bit_mask >>= 1; } - init_bignum(n_tmp, 0, n4_len); - clear_tmp_vars(len); + InitBigNum(n_tmp, 0, n4_len); + ClearTempVars(len); } } } - static unsafe void memcpy(byte* dest, byte* src, int len) + static unsafe void Memcopy(byte* dest, byte* src, int len) { while (len-- != 0) *dest++ = *src++; } - unsafe void process_predata(byte* pre, uint pre_len, byte* buf) + unsafe void ProcessPredata(byte* pre, uint pre_len, byte* buf) { var n2 = new uint[64]; var n3 = new uint[64]; - var a = (pubkey.len - 1) / 8; + var a = (pubkey.Len - 1) / 8; while (a + 1 <= pre_len) { - init_bignum(n2, 0, 64); + InitBigNum(n2, 0, 64); fixed (uint* pn2 = &n2[0]) - memcpy((byte*)pn2, pre, (int)a + 1); - calc_a_key(n3, n2, pubkey.key2, pubkey.key1, 64); + Memcopy((byte*)pn2, pre, (int)a + 1); + CalcKey(n3, n2, pubkey.KeyTwo, pubkey.KeyOne, 64); fixed (uint* pn3 = &n3[0]) - memcpy(buf, (byte*)pn3, (int)a); + Memcopy(buf, (byte*)pn3, (int)a); pre_len -= a + 1; pre += a + 1; @@ -492,14 +490,14 @@ namespace OpenRA.FileFormats public byte[] DecryptKey(byte[] src) { - init_pubkey(); + InitPublicKey(); var dest = new byte[256]; unsafe { fixed (byte* pdest = &dest[0]) fixed (byte* psrc = &src[0]) - process_predata(psrc, len_predata(), pdest); + ProcessPredata(psrc, LenPreData(), pdest); } return dest.Take(56).ToArray(); diff --git a/OpenRA.Game/FileFormats/ImaAdpcmLoader.cs b/OpenRA.Game/FileFormats/ImaAdpcmLoader.cs index 7eed094652..cee7a23e00 100644 --- a/OpenRA.Game/FileFormats/ImaAdpcmLoader.cs +++ b/OpenRA.Game/FileFormats/ImaAdpcmLoader.cs @@ -31,9 +31,9 @@ namespace OpenRA.FileFormats public static class ImaAdpcmLoader { - static readonly int[] indexAdjust = { -1, -1, -1, -1, 2, 4, 6, 8 }; - static readonly int[] stepTable = - { + static readonly int[] IndexAdjust = { -1, -1, -1, -1, 2, 4, 6, 8 }; + static readonly int[] StepTable = + { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, @@ -51,14 +51,14 @@ namespace OpenRA.FileFormats var sb = (b & 8) != 0; b &= 7; - var delta = (stepTable[index] * b) / 4 + stepTable[index] / 8; + var delta = (StepTable[index] * b) / 4 + StepTable[index] / 8; if (sb) delta = -delta; current += delta; if (current > short.MaxValue) current = short.MaxValue; if (current < short.MinValue) current = short.MinValue; - index += indexAdjust[b]; + index += IndexAdjust[b]; if (index < 0) index = 0; if (index > 88) index = 88; diff --git a/OpenRA.Game/FileFormats/VxlReader.cs b/OpenRA.Game/FileFormats/VxlReader.cs index 08e7075436..ed1cf83704 100644 --- a/OpenRA.Game/FileFormats/VxlReader.cs +++ b/OpenRA.Game/FileFormats/VxlReader.cs @@ -38,7 +38,7 @@ namespace OpenRA.FileFormats public readonly uint LimbCount; public VxlLimb[] Limbs; - uint BodySize; + uint bodySize; static void ReadVoxelData(Stream s, VxlLimb l) { @@ -111,7 +111,7 @@ namespace OpenRA.FileFormats s.ReadUInt32(); LimbCount = s.ReadUInt32(); s.ReadUInt32(); - BodySize = s.ReadUInt32(); + bodySize = s.ReadUInt32(); s.Seek(770, SeekOrigin.Current); // Read Limb headers @@ -124,12 +124,12 @@ namespace OpenRA.FileFormats } // Skip to the Limb footers - s.Seek(802 + 28 * LimbCount + BodySize, SeekOrigin.Begin); + s.Seek(802 + 28 * LimbCount + bodySize, SeekOrigin.Begin); - var LimbDataOffset = new uint[LimbCount]; + var limbDataOffset = new uint[LimbCount]; for (var i = 0; i < LimbCount; i++) { - LimbDataOffset[i] = s.ReadUInt32(); + limbDataOffset[i] = s.ReadUInt32(); s.Seek(8, SeekOrigin.Current); Limbs[i].Scale = s.ReadFloat(); s.Seek(48, SeekOrigin.Current); @@ -143,7 +143,7 @@ namespace OpenRA.FileFormats for (var i = 0; i < LimbCount; i++) { - s.Seek(802 + 28 * LimbCount + LimbDataOffset[i], SeekOrigin.Begin); + s.Seek(802 + 28 * LimbCount + limbDataOffset[i], SeekOrigin.Begin); ReadVoxelData(s, Limbs[i]); } } diff --git a/OpenRA.Game/FileSystem/InstallShieldPackage.cs b/OpenRA.Game/FileSystem/InstallShieldPackage.cs index e15f8cdf02..9cdd35a9fa 100644 --- a/OpenRA.Game/FileSystem/InstallShieldPackage.cs +++ b/OpenRA.Game/FileSystem/InstallShieldPackage.cs @@ -42,19 +42,19 @@ namespace OpenRA.FileSystem reader.ReadBytes(4); /*var ArchiveSize = */reader.ReadUInt32(); reader.ReadBytes(19); - var TOCAddress = reader.ReadInt32(); + var tocAddress = reader.ReadInt32(); reader.ReadBytes(4); - var DirCount = reader.ReadUInt16(); + var dirCount = reader.ReadUInt16(); // Parse the directory list - s.Seek(TOCAddress, SeekOrigin.Begin); - var TOCreader = new BinaryReader(s); + s.Seek(tocAddress, SeekOrigin.Begin); + var tocReader = new BinaryReader(s); var fileCountInDirs = new List(); // Parse directories - for (var i = 0; i < DirCount; i++) - fileCountInDirs.Add(ParseDirectory(TOCreader)); + for (var i = 0; i < dirCount; i++) + fileCountInDirs.Add(ParseDirectory(tocReader)); // Parse files foreach (var fileCount in fileCountInDirs) @@ -65,35 +65,35 @@ namespace OpenRA.FileSystem static uint ParseDirectory(BinaryReader reader) { // Parse directory header - var FileCount = reader.ReadUInt16(); - var ChunkSize = reader.ReadUInt16(); - var NameLength = reader.ReadUInt16(); - reader.ReadChars(NameLength); // var DirName = new String(reader.ReadChars(NameLength)); + var fileCount = reader.ReadUInt16(); + var chunkSize = reader.ReadUInt16(); + var nameLength = reader.ReadUInt16(); + reader.ReadChars(nameLength); // var DirName = new String(reader.ReadChars(NameLength)); // Skip to the end of the chunk - reader.ReadBytes(ChunkSize - NameLength - 6); - return FileCount; + reader.ReadBytes(chunkSize - nameLength - 6); + return fileCount; } - uint AccumulatedData = 0; + uint accumulatedData = 0; void ParseFile(BinaryReader reader) { reader.ReadBytes(7); - var CompressedSize = reader.ReadUInt32(); + var compressedSize = reader.ReadUInt32(); reader.ReadBytes(12); - var ChunkSize = reader.ReadUInt16(); + var chunkSize = reader.ReadUInt16(); reader.ReadBytes(4); - var NameLength = reader.ReadByte(); - var FileName = new string(reader.ReadChars(NameLength)); + var nameLength = reader.ReadByte(); + 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)) - index.Add(hash, new PackageEntry(hash, AccumulatedData, CompressedSize)); - filenames.Add(FileName); - AccumulatedData += CompressedSize; + index.Add(hash, new PackageEntry(hash, accumulatedData, compressedSize)); + filenames.Add(fileName); + accumulatedData += compressedSize; // Skip to the end of the chunk - reader.ReadBytes(ChunkSize - NameLength - 30); + reader.ReadBytes(chunkSize - nameLength - 30); } public Stream GetContent(uint hash) diff --git a/OpenRA.Game/FileSystem/PackageEntry.cs b/OpenRA.Game/FileSystem/PackageEntry.cs index 737abe50ee..6667f26e69 100644 --- a/OpenRA.Game/FileSystem/PackageEntry.cs +++ b/OpenRA.Game/FileSystem/PackageEntry.cs @@ -49,7 +49,7 @@ namespace OpenRA.FileSystem public override string ToString() { string filename; - if (Names.TryGetValue(Hash, out filename)) + if (names.TryGetValue(Hash, out filename)) return "{0} - offset 0x{1:x8} - length 0x{2:x8}".F(filename, Offset, Length); else return "0x{0:x8} - offset 0x{1:x8} - length 0x{2:x8}".F(Hash, Offset, Length); @@ -97,14 +97,14 @@ namespace OpenRA.FileSystem } } - static Dictionary Names = new Dictionary(); + static Dictionary names = new Dictionary(); public static void AddStandardName(string s) { var hash = HashFilename(s, PackageHashType.Classic); // RA1 and TD - Names.Add(hash, s); + names.Add(hash, s); var crcHash = HashFilename(s, PackageHashType.CRC32); // TS - Names.Add(crcHash, s); + names.Add(crcHash, s); } } } diff --git a/OpenRA.Game/Game.cs b/OpenRA.Game/Game.cs index 83c0cdb333..7fe650f61f 100644 --- a/OpenRA.Game/Game.cs +++ b/OpenRA.Game/Game.cs @@ -328,10 +328,10 @@ namespace OpenRA else Cursor = new SoftwareCursor(modData.CursorProvider); - PerfHistory.items["render"].hasNormalTick = false; - PerfHistory.items["batches"].hasNormalTick = false; - PerfHistory.items["render_widgets"].hasNormalTick = false; - PerfHistory.items["render_flip"].hasNormalTick = false; + PerfHistory.Items["render"].HasNormalTick = false; + PerfHistory.Items["batches"].HasNormalTick = false; + PerfHistory.Items["render_widgets"].HasNormalTick = false; + PerfHistory.Items["render_flip"].HasNormalTick = false; JoinLocal(); @@ -513,10 +513,10 @@ namespace OpenRA Renderer.EndFrame(new DefaultInputHandler(orderManager.World)); } - PerfHistory.items["render"].Tick(); - PerfHistory.items["batches"].Tick(); - PerfHistory.items["render_widgets"].Tick(); - PerfHistory.items["render_flip"].Tick(); + PerfHistory.Items["render"].Tick(); + PerfHistory.Items["batches"].Tick(); + PerfHistory.Items["render_widgets"].Tick(); + PerfHistory.Items["render_flip"].Tick(); } static void Loop() @@ -551,12 +551,12 @@ namespace OpenRA // (if ever). // This also means that the 'logicInterval' cannot be longer than this // value. - const int maxLogicTicksBehind = 250; + const int MaxLogicTicksBehind = 250; // Try to maintain at least this many FPS during replays, even if it slows down logic. // However, if the user has enabled a framerate limit that is even lower // than this, then that limit will be used. - const int minReplayFps = 10; + const int MinReplayFps = 10; // Timestamps for when the next logic and rendering should run var nextLogic = RunTime; @@ -576,7 +576,7 @@ namespace OpenRA var now = RunTime; // If the logic has fallen behind too much, skip it and catch up - if (now - nextLogic > maxLogicTicksBehind) + if (now - nextLogic > MaxLogicTicksBehind) nextLogic = now; // When's the next update (logic or render) @@ -608,7 +608,7 @@ namespace OpenRA // allowed between screen updates. // We do this before rendering to include the time rendering takes // in this interval. - var maxRenderInterval = Math.Max(1000 / minReplayFps, renderInterval); + var maxRenderInterval = Math.Max(1000 / MinReplayFps, renderInterval); forcedNextRender = now + maxRenderInterval; RenderTick(); diff --git a/OpenRA.Game/Graphics/ChromeProvider.cs b/OpenRA.Game/Graphics/ChromeProvider.cs index 9b00188497..c636c8ef5a 100644 --- a/OpenRA.Game/Graphics/ChromeProvider.cs +++ b/OpenRA.Game/Graphics/ChromeProvider.cs @@ -101,12 +101,12 @@ namespace OpenRA.Graphics // Cached sheet Sheet sheet; - if (cachedSheets.ContainsKey(mi.src)) - sheet = cachedSheets[mi.src]; + if (cachedSheets.ContainsKey(mi.Src)) + sheet = cachedSheets[mi.Src]; else { - sheet = new Sheet(mi.src); - cachedSheets.Add(mi.src, sheet); + sheet = new Sheet(mi.Src); + cachedSheets.Add(mi.Src, sheet); } // Cache the sprite diff --git a/OpenRA.Game/Graphics/MappedImage.cs b/OpenRA.Game/Graphics/MappedImage.cs index c061279f88..1fe6634d3f 100644 --- a/OpenRA.Game/Graphics/MappedImage.cs +++ b/OpenRA.Game/Graphics/MappedImage.cs @@ -15,15 +15,15 @@ namespace OpenRA.Graphics { class MappedImage { - public readonly Rectangle rect = Rectangle.Empty; - public readonly string src; + readonly Rectangle rect = Rectangle.Empty; + public readonly string Src; public MappedImage(string defaultSrc, MiniYaml info) { FieldLoader.LoadField(this, "rect", info.Value); FieldLoader.Load(this, info); - if (src == null) - src = defaultSrc; + if (Src == null) + Src = defaultSrc; } public Sprite GetImage(Sheet s) @@ -34,8 +34,8 @@ namespace OpenRA.Graphics public MiniYaml Save(string defaultSrc) { var root = new List(); - if (defaultSrc != src) - root.Add(new MiniYamlNode("src", src)); + if (defaultSrc != Src) + root.Add(new MiniYamlNode("Src", Src)); return new MiniYaml(FieldSaver.FormatValue(this, this.GetType().GetField("rect")), root); } diff --git a/OpenRA.Game/Graphics/SelectionBarsRenderable.cs b/OpenRA.Game/Graphics/SelectionBarsRenderable.cs index ed447cbfa5..d430abf393 100644 --- a/OpenRA.Game/Graphics/SelectionBarsRenderable.cs +++ b/OpenRA.Game/Graphics/SelectionBarsRenderable.cs @@ -41,21 +41,21 @@ namespace OpenRA.Graphics public IRenderable OffsetBy(WVec vec) { return new SelectionBarsRenderable(pos + vec, actor); } public IRenderable AsDecoration() { return this; } - void DrawExtraBars(WorldRenderer wr, float2 xy, float2 Xy) + void DrawExtraBars(WorldRenderer wr, float2 start, float2 end) { foreach (var extraBar in actor.TraitsImplementing()) { var value = extraBar.GetValue(); if (value != 0) { - xy.Y += (int)(4 / wr.Viewport.Zoom); - Xy.Y += (int)(4 / wr.Viewport.Zoom); - DrawSelectionBar(wr, xy, Xy, extraBar.GetValue(), extraBar.GetColor()); + start.Y += (int)(4 / wr.Viewport.Zoom); + end.Y += (int)(4 / wr.Viewport.Zoom); + DrawSelectionBar(wr, start, end, extraBar.GetValue(), extraBar.GetColor()); } } } - void DrawSelectionBar(WorldRenderer wr, float2 xy, float2 Xy, float value, Color barColor) + void DrawSelectionBar(WorldRenderer wr, float2 start, float2 end, float value, Color barColor) { var c = Color.FromArgb(128, 30, 30, 30); var c2 = Color.FromArgb(128, 10, 10, 10); @@ -65,15 +65,15 @@ namespace OpenRA.Graphics var barColor2 = Color.FromArgb(255, barColor.R / 2, barColor.G / 2, barColor.B / 2); - var z = float2.Lerp(xy, Xy, value); + var z = float2.Lerp(start, end, value); var wlr = Game.Renderer.WorldLineRenderer; - wlr.DrawLine(xy + p, Xy + p, c, c); - wlr.DrawLine(xy + q, Xy + q, c2, c2); - wlr.DrawLine(xy + r, Xy + r, c, c); + wlr.DrawLine(start + p, end + p, c, c); + wlr.DrawLine(start + q, end + q, c2, c2); + wlr.DrawLine(start + r, end + r, c, c); - wlr.DrawLine(xy + p, z + p, barColor2, barColor2); - wlr.DrawLine(xy + q, z + q, barColor, barColor); - wlr.DrawLine(xy + r, z + r, barColor2, barColor2); + wlr.DrawLine(start + p, z + p, barColor2, barColor2); + wlr.DrawLine(start + q, z + q, barColor, barColor); + wlr.DrawLine(start + r, z + r, barColor2, barColor2); } Color GetHealthColor(Health health) @@ -90,7 +90,7 @@ namespace OpenRA.Graphics health.DamageState == DamageState.Heavy ? Color.Yellow : Color.LimeGreen; } - void DrawHealthBar(WorldRenderer wr, Health health, float2 xy, float2 Xy) + void DrawHealthBar(WorldRenderer wr, Health health, float2 start, float2 end) { if (health == null || health.IsDead) return; @@ -108,16 +108,16 @@ namespace OpenRA.Graphics healthColor.G / 2, healthColor.B / 2); - var z = float2.Lerp(xy, Xy, (float)health.HP / health.MaxHP); + var z = float2.Lerp(start, end, (float)health.HP / health.MaxHP); var wlr = Game.Renderer.WorldLineRenderer; - wlr.DrawLine(xy + p, Xy + p, c, c); - wlr.DrawLine(xy + q, Xy + q, c2, c2); - wlr.DrawLine(xy + r, Xy + r, c, c); + wlr.DrawLine(start + p, end + p, c, c); + wlr.DrawLine(start + q, end + q, c2, c2); + wlr.DrawLine(start + r, end + r, c, c); - wlr.DrawLine(xy + p, z + p, healthColor2, healthColor2); - wlr.DrawLine(xy + q, z + q, healthColor, healthColor); - wlr.DrawLine(xy + r, z + r, healthColor2, healthColor2); + wlr.DrawLine(start + p, z + p, healthColor2, healthColor2); + wlr.DrawLine(start + q, z + q, healthColor, healthColor); + wlr.DrawLine(start + r, z + r, healthColor2, healthColor2); if (health.DisplayHp != health.HP) { @@ -127,7 +127,7 @@ namespace OpenRA.Graphics deltaColor.R / 2, deltaColor.G / 2, deltaColor.B / 2); - var zz = float2.Lerp(xy, Xy, (float)health.DisplayHp / health.MaxHP); + var zz = float2.Lerp(start, end, (float)health.DisplayHp / health.MaxHP); wlr.DrawLine(z + p, zz + p, deltaColor2, deltaColor2); wlr.DrawLine(z + q, zz + q, deltaColor, deltaColor); @@ -147,11 +147,11 @@ namespace OpenRA.Graphics var bounds = actor.Bounds; bounds.Offset(screenPos.X, screenPos.Y); - var xy = new float2(bounds.Left, bounds.Top); - var Xy = new float2(bounds.Right, bounds.Top); + var start = new float2(bounds.Left, bounds.Top); + var end = new float2(bounds.Right, bounds.Top); - DrawHealthBar(wr, health, xy, Xy); - DrawExtraBars(wr, xy, Xy); + DrawHealthBar(wr, health, start, end); + DrawExtraBars(wr, start, end); } public void RenderDebugGeometry(WorldRenderer wr) { } diff --git a/OpenRA.Game/Graphics/Vertex.cs b/OpenRA.Game/Graphics/Vertex.cs index 0d4e655610..2bb3c869ad 100644 --- a/OpenRA.Game/Graphics/Vertex.cs +++ b/OpenRA.Game/Graphics/Vertex.cs @@ -15,8 +15,8 @@ namespace OpenRA.Graphics [StructLayout(LayoutKind.Sequential)] public struct Vertex { - public float x, y, z, u, v; - public float p, c; + float x, y, z, u, v; + float p, c; public Vertex(float2 xy, float u, float v, float p, float c) { diff --git a/OpenRA.Game/Graphics/VoxelRenderer.cs b/OpenRA.Game/Graphics/VoxelRenderer.cs index 6b062b1faf..d74d557b78 100644 --- a/OpenRA.Game/Graphics/VoxelRenderer.cs +++ b/OpenRA.Game/Graphics/VoxelRenderer.cs @@ -25,7 +25,7 @@ namespace OpenRA.Graphics public VoxelRenderProxy(Sprite sprite, Sprite shadowSprite, float2[] projectedShadowBounds, float shadowDirection) { - Sprite = sprite; + this.Sprite = sprite; ShadowSprite = shadowSprite; ProjectedShadowBounds = projectedShadowBounds; ShadowDirection = shadowDirection; diff --git a/OpenRA.Game/Map/ActorInitializer.cs b/OpenRA.Game/Map/ActorInitializer.cs index 9c3325b757..903aed6284 100755 --- a/OpenRA.Game/Map/ActorInitializer.cs +++ b/OpenRA.Game/Map/ActorInitializer.cs @@ -19,17 +19,17 @@ namespace OpenRA public readonly Actor self; public World world { get { return self.World; } } - internal TypeDictionary dict; + internal TypeDictionary Dict; public ActorInitializer(Actor actor, TypeDictionary dict) { - this.self = actor; - this.dict = dict; + self = actor; + Dict = dict; } - public T Get() where T : IActorInit { return dict.Get(); } - public U Get() where T : IActorInit { return dict.Get().Value(world); } - public bool Contains() where T : IActorInit { return dict.Contains(); } + public T Get() where T : IActorInit { return Dict.Get(); } + public U Get() where T : IActorInit { return Dict.Get().Value(world); } + public bool Contains() where T : IActorInit { return Dict.Contains(); } } public interface IActorInit { } @@ -41,7 +41,7 @@ namespace OpenRA public class FacingInit : IActorInit { - [FieldFromYamlKey] public readonly int value = 128; + [FieldFromYamlKey] readonly int value = 128; public FacingInit() { } public FacingInit(int init) { value = init; } public int Value(World world) { return value; } @@ -49,7 +49,7 @@ namespace OpenRA public class TurretFacingInit : IActorInit { - [FieldFromYamlKey] public readonly int value = 128; + [FieldFromYamlKey] readonly int value = 128; public TurretFacingInit() { } public TurretFacingInit(int init) { value = init; } public int Value(World world) { return value; } @@ -57,7 +57,7 @@ namespace OpenRA public class LocationInit : IActorInit { - [FieldFromYamlKey] public readonly CPos value = CPos.Zero; + [FieldFromYamlKey] readonly CPos value = CPos.Zero; public LocationInit() { } public LocationInit(CPos init) { value = init; } public CPos Value(World world) { return value; } @@ -65,7 +65,7 @@ namespace OpenRA public class SubCellInit : IActorInit { - [FieldFromYamlKey] public readonly int value = (int)SubCell.FullCell; + [FieldFromYamlKey] readonly int value = (int)SubCell.FullCell; public SubCellInit() { } public SubCellInit(int init) { value = init; } public SubCellInit(SubCell init) { value = (int)init; } @@ -74,7 +74,7 @@ namespace OpenRA public class CenterPositionInit : IActorInit { - [FieldFromYamlKey] public readonly WPos value = WPos.Zero; + [FieldFromYamlKey] readonly WPos value = WPos.Zero; public CenterPositionInit() { } public CenterPositionInit(WPos init) { value = init; } public WPos Value(World world) { return value; } diff --git a/OpenRA.Game/Map/Map.cs b/OpenRA.Game/Map/Map.cs index 32e5050f1b..900f71d678 100644 --- a/OpenRA.Game/Map/Map.cs +++ b/OpenRA.Game/Map/Map.cs @@ -385,7 +385,7 @@ namespace OpenRA { return Actors.Value.Values .Where(a => a.Type == "mpspawn") - .Select(a => (CPos)a.InitDict.Get().value) + .Select(a => (CPos)a.InitDict.Get().Value(null)) .ToArray(); } @@ -847,7 +847,7 @@ namespace OpenRA return new WRange(Math.Min(x, y) * dir.Length); } - static CVec[][] TilesByDistance = InitTilesByDistance(MaxTilesInCircleRange); + static readonly CVec[][] TilesByDistance = InitTilesByDistance(MaxTilesInCircleRange); static CVec[][] InitTilesByDistance(int max) { diff --git a/OpenRA.Game/Map/MapPreview.cs b/OpenRA.Game/Map/MapPreview.cs old mode 100755 new mode 100644 index b14b5ce111..eb18d418a5 --- a/OpenRA.Game/Map/MapPreview.cs +++ b/OpenRA.Game/Map/MapPreview.cs @@ -11,6 +11,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.IO; using System.Linq; @@ -28,7 +29,9 @@ namespace OpenRA // Used for verifying map availability in the lobby public enum MapRuleStatus { Unknown, Cached, Invalid } - // Fields names must match the with the remote API + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Fields names must match the with the remote API.")] + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter", Justification = "Fields names must match the with the remote API.")] + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Fields names must match the with the remote API.")] public class RemoteMapData { public readonly string title; diff --git a/OpenRA.Game/MiniYaml.cs b/OpenRA.Game/MiniYaml.cs index 41493704a8..dc660fc2eb 100755 --- a/OpenRA.Game/MiniYaml.cs +++ b/OpenRA.Game/MiniYaml.cs @@ -83,8 +83,9 @@ namespace OpenRA public class MiniYaml { - static Func StringIdentity = s => s; - static Func MiniYamlIdentity = my => my; + static readonly Func StringIdentity = s => s; + static readonly Func MiniYamlIdentity = my => my; + public string Value; public List Nodes; diff --git a/OpenRA.Game/OpenRA.Game.csproj b/OpenRA.Game/OpenRA.Game.csproj index 136743823f..e24a3035fe 100644 --- a/OpenRA.Game/OpenRA.Game.csproj +++ b/OpenRA.Game/OpenRA.Game.csproj @@ -254,6 +254,8 @@ + + diff --git a/OpenRA.Game/Primitives/ObservableDictionary.cs b/OpenRA.Game/Primitives/ObservableDictionary.cs index 73e4a0c4c4..f821f4ded3 100644 --- a/OpenRA.Game/Primitives/ObservableDictionary.cs +++ b/OpenRA.Game/Primitives/ObservableDictionary.cs @@ -18,19 +18,19 @@ namespace OpenRA.Primitives { public ObservableSortedDictionary(IComparer comparer) { - InnerDict = new SortedDictionary(comparer); + innerDict = new SortedDictionary(comparer); } public override void Add(TKey key, TValue value) { - InnerDict.Add(key, value); + innerDict.Add(key, value); FireOnRefresh(); } } public class ObservableDictionary : IDictionary, IObservableCollection { - protected IDictionary InnerDict; + protected IDictionary innerDict; public event Action OnAdd = k => { }; public event Action OnRemove = k => { }; @@ -51,18 +51,18 @@ namespace OpenRA.Primitives public ObservableDictionary(IEqualityComparer comparer) { - InnerDict = new Dictionary(comparer); + innerDict = new Dictionary(comparer); } public virtual void Add(TKey key, TValue value) { - InnerDict.Add(key, value); + innerDict.Add(key, value); OnAdd(key); } public bool Remove(TKey key) { - var found = InnerDict.Remove(key); + var found = innerDict.Remove(key); if (found) OnRemove(key); return found; @@ -70,32 +70,32 @@ namespace OpenRA.Primitives public bool ContainsKey(TKey key) { - return InnerDict.ContainsKey(key); + return innerDict.ContainsKey(key); } - public ICollection Keys { get { return InnerDict.Keys; } } - public ICollection Values { get { return InnerDict.Values; } } + public ICollection Keys { get { return innerDict.Keys; } } + public ICollection Values { get { return innerDict.Values; } } public bool TryGetValue(TKey key, out TValue value) { - return InnerDict.TryGetValue(key, out value); + return innerDict.TryGetValue(key, out value); } public TValue this[TKey key] { - get { return InnerDict[key]; } - set { InnerDict[key] = value; } + get { return innerDict[key]; } + set { innerDict[key] = value; } } public void Clear() { - InnerDict.Clear(); + innerDict.Clear(); OnRefresh(); } public int Count { - get { return InnerDict.Count; } + get { return innerDict.Count; } } public void Add(KeyValuePair item) @@ -105,17 +105,17 @@ namespace OpenRA.Primitives public bool Contains(KeyValuePair item) { - return InnerDict.Contains(item); + return innerDict.Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { - InnerDict.CopyTo(array, arrayIndex); + innerDict.CopyTo(array, arrayIndex); } public bool IsReadOnly { - get { return InnerDict.IsReadOnly; } + get { return innerDict.IsReadOnly; } } public bool Remove(KeyValuePair item) @@ -125,17 +125,17 @@ namespace OpenRA.Primitives public IEnumerator> GetEnumerator() { - return InnerDict.GetEnumerator(); + return innerDict.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return InnerDict.GetEnumerator(); + return innerDict.GetEnumerator(); } public IEnumerable ObservedItems { - get { return InnerDict.Keys; } + get { return innerDict.Keys; } } } } diff --git a/OpenRA.Game/Primitives/Pair.cs b/OpenRA.Game/Primitives/Pair.cs index 0df1117e9e..569be51b8f 100644 --- a/OpenRA.Game/Primitives/Pair.cs +++ b/OpenRA.Game/Primitives/Pair.cs @@ -24,12 +24,12 @@ namespace OpenRA.Primitives Second = second; } - internal static IEqualityComparer tc = EqualityComparer.Default; - internal static IEqualityComparer uc = EqualityComparer.Default; + internal static IEqualityComparer Tcomparer = EqualityComparer.Default; + internal static IEqualityComparer Ucomparer = EqualityComparer.Default; public static bool operator ==(Pair a, Pair b) { - return tc.Equals(a.First, b.First) && uc.Equals(a.Second, b.Second); + return Tcomparer.Equals(a.First, b.First) && Ucomparer.Equals(a.Second, b.Second); } public static bool operator !=(Pair a, Pair b) @@ -74,7 +74,7 @@ namespace OpenRA.Primitives static Pair() { - Pair.uc = new ColorEqualityComparer(); + Pair.Ucomparer = new ColorEqualityComparer(); } // avoid the default crappy one diff --git a/OpenRA.Game/Primitives/float2.cs b/OpenRA.Game/Primitives/float2.cs index 6f36768725..0106c6456f 100644 --- a/OpenRA.Game/Primitives/float2.cs +++ b/OpenRA.Game/Primitives/float2.cs @@ -9,11 +9,13 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Runtime.InteropServices; namespace OpenRA { + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Mimic a built-in type alias.")] [StructLayout(LayoutKind.Sequential)] public struct float2 { diff --git a/OpenRA.Game/Primitives/int2.cs b/OpenRA.Game/Primitives/int2.cs index cb978d4f75..649c565b9d 100644 --- a/OpenRA.Game/Primitives/int2.cs +++ b/OpenRA.Game/Primitives/int2.cs @@ -9,14 +9,15 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Drawing; namespace OpenRA { + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Mimic a built-in type alias.")] public struct int2 { public int X, Y; - public int2(int x, int y) { this.X = x; this.Y = y; } public int2(Point p) { X = p.X; Y = p.Y; } public int2(Size p) { X = p.Width; Y = p.Height; } diff --git a/OpenRA.Game/Selection.cs b/OpenRA.Game/Selection.cs index 06c55dd774..8e6e6c0043 100644 --- a/OpenRA.Game/Selection.cs +++ b/OpenRA.Game/Selection.cs @@ -72,7 +72,7 @@ namespace OpenRA Cache> controlGroups = new Cache>(_ => new List()); - public void DoControlGroup(World world, WorldRenderer worldRenderer, int group, Modifiers mods, int MultiTapCount) + public void DoControlGroup(World world, WorldRenderer worldRenderer, int group, Modifiers mods, int multiTapCount) { var addModifier = Platform.CurrentPlatform == PlatformType.OSX ? Modifiers.Meta : Modifiers.Ctrl; if (mods.HasModifier(addModifier)) @@ -92,7 +92,7 @@ namespace OpenRA var groupActors = controlGroups[group].Where(a => !a.IsDead); - if (mods.HasModifier(Modifiers.Alt) || MultiTapCount >= 2) + if (mods.HasModifier(Modifiers.Alt) || multiTapCount >= 2) { worldRenderer.Viewport.Center(groupActors); return; diff --git a/OpenRA.Game/Server/Connection.cs b/OpenRA.Game/Server/Connection.cs index 4f56df5999..3cef2a2dee 100644 --- a/OpenRA.Game/Server/Connection.cs +++ b/OpenRA.Game/Server/Connection.cs @@ -18,8 +18,8 @@ namespace OpenRA.Server public class Connection { public const int MaxOrderLength = 131072; - public Socket socket; - public List data = new List(); + public Socket Socket; + public List Data = new List(); public ReceiveState State = ReceiveState.Header; public int ExpectLength = 8; public int Frame = 0; @@ -34,8 +34,8 @@ namespace OpenRA.Server public byte[] PopBytes(int n) { - var result = data.GetRange(0, n); - data.RemoveRange(0, n); + var result = Data.GetRange(0, n); + Data.RemoveRange(0, n); return result.ToArray(); } @@ -51,10 +51,10 @@ namespace OpenRA.Server // NOTE(jsd): Poll the socket first to see if there's anything there. // This avoids the exception with SocketErrorCode == `SocketError.WouldBlock` thrown // from `socket.Receive(rx)`. - if (!socket.Poll(0, SelectMode.SelectRead)) break; + if (!Socket.Poll(0, SelectMode.SelectRead)) break; - if (0 < (len = socket.Receive(rx))) - data.AddRange(rx.Take(len)); + if (0 < (len = Socket.Receive(rx))) + Data.AddRange(rx.Take(len)); else { if (len == 0) @@ -82,7 +82,7 @@ namespace OpenRA.Server public void ReadData(Server server) { if (ReadDataInner(server)) - while (data.Count >= ExpectLength) + while (Data.Count >= ExpectLength) { var bytes = PopBytes(ExpectLength); switch (State) diff --git a/OpenRA.Game/Server/Server.cs b/OpenRA.Game/Server/Server.cs index c6eab4e088..4d64b40dbb 100644 --- a/OpenRA.Game/Server/Server.cs +++ b/OpenRA.Game/Server/Server.cs @@ -157,8 +157,8 @@ namespace OpenRA.Server { var checkRead = new List(); if (State == ServerState.WaitingPlayers) checkRead.Add(listener.Server); - foreach (var c in Conns) checkRead.Add(c.socket); - foreach (var c in PreConns) checkRead.Add(c.socket); + foreach (var c in Conns) checkRead.Add(c.Socket); + foreach (var c in PreConns) checkRead.Add(c.Socket); if (checkRead.Count > 0) Socket.Select(checkRead, null, null, timeout); if (State == ServerState.ShuttingDown) @@ -171,12 +171,12 @@ namespace OpenRA.Server if (s == listener.Server) AcceptConnection(); else if (PreConns.Count > 0) { - var p = PreConns.SingleOrDefault(c => c.socket == s); + var p = PreConns.SingleOrDefault(c => c.Socket == s); if (p != null) p.ReadData(this); } else if (Conns.Count > 0) { - var conn = Conns.SingleOrDefault(c => c.socket == s); + var conn = Conns.SingleOrDefault(c => c.Socket == s); if (conn != null) conn.ReadData(this); } @@ -228,16 +228,16 @@ namespace OpenRA.Server return; } - var newConn = new Connection { socket = newSocket }; + var newConn = new Connection { Socket = newSocket }; try { - newConn.socket.Blocking = false; - newConn.socket.NoDelay = true; + newConn.Socket.Blocking = false; + newConn.Socket.NoDelay = true; // assign the player number. newConn.PlayerIndex = ChooseFreePlayerIndex(); - SendData(newConn.socket, BitConverter.GetBytes(ProtocolVersion.Version)); - SendData(newConn.socket, BitConverter.GetBytes(newConn.PlayerIndex)); + SendData(newConn.Socket, BitConverter.GetBytes(ProtocolVersion.Version)); + SendData(newConn.Socket, BitConverter.GetBytes(newConn.PlayerIndex)); PreConns.Add(newConn); // Dispatch a handshake order @@ -264,7 +264,7 @@ namespace OpenRA.Server if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", - newConn.socket.RemoteEndPoint); + newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); @@ -284,7 +284,7 @@ namespace OpenRA.Server var client = new Session.Client() { Name = handshake.Client.Name, - IpAddress = ((IPEndPoint)newConn.socket.RemoteEndPoint).Address.ToString(), + IpAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.Color, @@ -311,7 +311,7 @@ namespace OpenRA.Server if (ModData.Manifest.Mod.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", - newConn.socket.RemoteEndPoint); + newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); @@ -321,7 +321,7 @@ namespace OpenRA.Server if (ModData.Manifest.Mod.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", - newConn.socket.RemoteEndPoint); + newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); @@ -332,7 +332,7 @@ namespace OpenRA.Server var bans = Settings.Ban.Union(TempBans); 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")); DropClient(newConn); return; @@ -347,7 +347,7 @@ namespace OpenRA.Server LobbyInfo.ClientPings.Add(clientPing); Log.Write("server", "Client {0}: Accepted connection from {1}.", - newConn.PlayerIndex, newConn.socket.RemoteEndPoint); + newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); foreach (var t in serverTraits.WithInterface()) t.ClientJoined(this, newConn); @@ -391,10 +391,10 @@ namespace OpenRA.Server { try { - SendData(c.socket, BitConverter.GetBytes(data.Length + 4)); - SendData(c.socket, BitConverter.GetBytes(client)); - SendData(c.socket, BitConverter.GetBytes(frame)); - SendData(c.socket, data); + SendData(c.Socket, BitConverter.GetBytes(data.Length + 4)); + SendData(c.Socket, BitConverter.GetBytes(client)); + SendData(c.Socket, BitConverter.GetBytes(frame)); + SendData(c.Socket, data); } catch (Exception e) { @@ -571,7 +571,7 @@ namespace OpenRA.Server try { - toDrop.socket.Disconnect(false); + toDrop.Socket.Disconnect(false); } catch { } diff --git a/OpenRA.Game/Support/PerfHistory.cs b/OpenRA.Game/Support/PerfHistory.cs index e7e89b4449..9ea10961da 100644 --- a/OpenRA.Game/Support/PerfHistory.cs +++ b/OpenRA.Game/Support/PerfHistory.cs @@ -18,108 +18,31 @@ namespace OpenRA.Support { public static class PerfHistory { - static readonly Color[] colors = { Color.Red, Color.Green, + static readonly Color[] Colors = { Color.Red, Color.Green, Color.Orange, Color.Yellow, Color.Fuchsia, Color.Lime, Color.LightBlue, Color.Blue, Color.White, Color.Teal }; static int nextColor; - public static Cache items = new Cache( + public static Cache Items = new Cache( s => { - var x = new PerfItem(s, colors[nextColor++]); - if (nextColor >= colors.Length) nextColor = 0; + var x = new PerfItem(s, Colors[nextColor++]); + if (nextColor >= Colors.Length) nextColor = 0; return x; }); public static void Increment(string item, double x) { - items[item].val += x; + Items[item].Val += x; } public static void Tick() { - foreach (var item in items.Values) - if (item.hasNormalTick) + foreach (var item in Items.Values) + if (item.HasNormalTick) item.Tick(); } } - - public class PerfItem - { - public readonly Color c; - public readonly string Name; - public double[] samples = new double[100]; - public double val = 0.0; - int head = 1, tail = 0; - public bool hasNormalTick = true; - - public PerfItem(string name, Color c) - { - Name = name; - this.c = c; - } - - public void Tick() - { - samples[head++] = val; - if (head == samples.Length) head = 0; - if (head == tail && ++tail == samples.Length) tail = 0; - val = 0.0; - } - - public IEnumerable Samples() - { - var n = head; - while (n != tail) - { - --n; - if (n < 0) n = samples.Length - 1; - yield return samples[n]; - } - } - - public double Average(int count) - { - var i = 0; - var n = head; - double sum = 0; - while (i < count && n != tail) - { - if (--n < 0) n = samples.Length - 1; - sum += samples[n]; - i++; - } - - return sum / i; - } - - public double LastValue - { - get - { - var n = head; - if (--n < 0) n = samples.Length - 1; - return samples[n]; - } - } - } - - public struct PerfSample : IDisposable - { - readonly string item; - readonly long ticks; - - public PerfSample(string item) - { - this.item = item; - ticks = Stopwatch.GetTimestamp(); - } - - public void Dispose() - { - PerfHistory.Increment(item, 1000.0 * Math.Max(0, Stopwatch.GetTimestamp() - ticks) / Stopwatch.Frequency); - } - } -} +} \ No newline at end of file diff --git a/OpenRA.Game/Support/PerfItem.cs b/OpenRA.Game/Support/PerfItem.cs new file mode 100644 index 0000000000..76f3ab50dc --- /dev/null +++ b/OpenRA.Game/Support/PerfItem.cs @@ -0,0 +1,78 @@ +#region Copyright & License Information +/* + * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) + * This file is part of OpenRA, which is free software. It is made + * available to you under the terms of the GNU General Public License + * as published by the Free Software Foundation. For more information, + * see COPYING. + */ +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using OpenRA.Primitives; + +namespace OpenRA.Support +{ + public class PerfItem + { + public readonly Color C; + public readonly string Name; + double[] samples = new double[100]; + public double Val = 0.0; + int head = 1, tail = 0; + public bool HasNormalTick = true; + + public PerfItem(string name, Color c) + { + Name = name; + C = c; + } + + public void Tick() + { + samples[head++] = Val; + if (head == samples.Length) head = 0; + if (head == tail && ++tail == samples.Length) tail = 0; + Val = 0.0; + } + + public IEnumerable Samples() + { + var n = head; + while (n != tail) + { + --n; + if (n < 0) n = samples.Length - 1; + yield return samples[n]; + } + } + + public double Average(int count) + { + var i = 0; + var n = head; + double sum = 0; + while (i < count && n != tail) + { + if (--n < 0) n = samples.Length - 1; + sum += samples[n]; + i++; + } + + return sum / i; + } + + public double LastValue + { + get + { + var n = head; + if (--n < 0) n = samples.Length - 1; + return samples[n]; + } + } + } +} diff --git a/OpenRA.Game/Support/PerfSample.cs b/OpenRA.Game/Support/PerfSample.cs new file mode 100644 index 0000000000..e00183047e --- /dev/null +++ b/OpenRA.Game/Support/PerfSample.cs @@ -0,0 +1,35 @@ +#region Copyright & License Information +/* + * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) + * This file is part of OpenRA, which is free software. It is made + * available to you under the terms of the GNU General Public License + * as published by the Free Software Foundation. For more information, + * see COPYING. + */ +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using OpenRA.Primitives; + +namespace OpenRA.Support +{ + public struct PerfSample : IDisposable + { + readonly string item; + readonly long ticks; + + public PerfSample(string item) + { + this.item = item; + ticks = Stopwatch.GetTimestamp(); + } + + public void Dispose() + { + PerfHistory.Increment(item, 1000.0 * Math.Max(0, Stopwatch.GetTimestamp() - ticks) / Stopwatch.Frequency); + } + } +} \ No newline at end of file diff --git a/OpenRA.Game/Support/PerfTimer.cs b/OpenRA.Game/Support/PerfTimer.cs index 4c4c981ddf..5f313a5990 100755 --- a/OpenRA.Game/Support/PerfTimer.cs +++ b/OpenRA.Game/Support/PerfTimer.cs @@ -30,16 +30,16 @@ namespace OpenRA.Support List children; long ticks; - static ThreadLocal Parent = new ThreadLocal(); + static ThreadLocal parentThreadLocal = new ThreadLocal(); public PerfTimer(string name, float thresholdMs = 0) { this.name = name; this.thresholdMs = thresholdMs; - parent = Parent.Value; + parent = parentThreadLocal.Value; depth = parent == null ? (byte)0 : (byte)(parent.depth + 1); - Parent.Value = this; + parentThreadLocal.Value = this; ticks = Stopwatch.GetTimestamp(); } @@ -48,7 +48,7 @@ namespace OpenRA.Support { ticks = Stopwatch.GetTimestamp() - ticks; - Parent.Value = parent; + parentThreadLocal.Value = parent; if (parent == null) Write(); diff --git a/OpenRA.Game/Sync.cs b/OpenRA.Game/Sync.cs index 09405db226..c5c088dce3 100755 --- a/OpenRA.Game/Sync.cs +++ b/OpenRA.Game/Sync.cs @@ -33,18 +33,18 @@ namespace OpenRA static Dictionary hashFunctions = new Dictionary() { - { typeof(int2), ((Func)hash_int2).Method }, - { typeof(CPos), ((Func)hash_CPos).Method }, - { typeof(CVec), ((Func)hash_CVec).Method }, - { typeof(WRange), ((Func)hash).Method }, - { typeof(WPos), ((Func)hash).Method }, - { typeof(WVec), ((Func)hash).Method }, - { typeof(WAngle), ((Func)hash).Method }, - { typeof(WRot), ((Func)hash).Method }, - { typeof(TypeDictionary), ((Func)hash_tdict).Method }, - { typeof(Actor), ((Func)hash_actor).Method }, - { typeof(Player), ((Func)hash_player).Method }, - { typeof(Target), ((Func)hash_target).Method }, + { typeof(int2), ((Func)HashInt2).Method }, + { typeof(CPos), ((Func)HashCPos).Method }, + { typeof(CVec), ((Func)HashCVec).Method }, + { typeof(WRange), ((Func)Hash).Method }, + { typeof(WPos), ((Func)Hash).Method }, + { typeof(WVec), ((Func)Hash).Method }, + { typeof(WAngle), ((Func)Hash).Method }, + { typeof(WRot), ((Func)Hash).Method }, + { typeof(TypeDictionary), ((Func)HashTDict).Method }, + { typeof(Actor), ((Func)HashActor).Method }, + { typeof(Player), ((Func)HashPlayer).Method }, + { typeof(Target), ((Func)HashTarget).Method }, }; static void EmitSyncOpcodes(Type type, ILGenerator il) @@ -78,8 +78,8 @@ namespace OpenRA il.Emit(OpCodes.Stloc, this_); il.Emit(OpCodes.Ldc_I4_0); - const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - foreach (var field in t.GetFields(bf).Where(x => x.HasAttribute())) + const BindingFlags Binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + foreach (var field in t.GetFields(Binding).Where(x => x.HasAttribute())) { il.Emit(OpCodes.Ldloc, this_); il.Emit(OpCodes.Ldfld, field); @@ -87,7 +87,7 @@ namespace OpenRA EmitSyncOpcodes(field.FieldType, il); } - foreach (var prop in t.GetProperties(bf).Where(x => x.HasAttribute())) + foreach (var prop in t.GetProperties(Binding).Where(x => x.HasAttribute())) { il.Emit(OpCodes.Ldloc, this_); il.EmitCall(OpCodes.Call, prop.GetGetMethod(), null); @@ -99,22 +99,22 @@ namespace OpenRA return (Func)d.CreateDelegate(typeof(Func)); } - public static int hash_int2(int2 i2) + public static int HashInt2(int2 i2) { return ((i2.X * 5) ^ (i2.Y * 3)) / 4; } - public static int hash_CPos(CPos i2) - { - return ((i2.X * 5) ^ (i2.Y * 3)) / 4; - } - - public static int hash_CVec(CVec i2) + public static int HashCPos(CPos i2) { return ((i2.X * 5) ^ (i2.Y * 3)) / 4; } - public static int hash_tdict(TypeDictionary d) + public static int HashCVec(CVec i2) + { + return ((i2.X * 5) ^ (i2.Y * 3)) / 4; + } + + public static int HashTDict(TypeDictionary d) { var ret = 0; foreach (var o in d) @@ -122,21 +122,21 @@ namespace OpenRA return ret; } - public static int hash_actor(Actor a) + public static int HashActor(Actor a) { if (a != null) return (int)(a.ActorID << 16); return 0; } - public static int hash_player(Player p) + public static int HashPlayer(Player p) { if (p != null) return (int)(p.PlayerActor.ActorID << 16) * 0x567; return 0; } - public static int hash_target(Target t) + public static int HashTarget(Target t) { switch (t.Type) { @@ -147,7 +147,7 @@ namespace OpenRA return (int)(t.FrozenActor.Actor.ActorID << 16) * 0x567; case TargetType.Terrain: - return hash(t.CenterPosition); + return Hash(t.CenterPosition); default: case TargetType.Invalid: @@ -155,7 +155,7 @@ namespace OpenRA } } - public static int hash(T t) + public static int Hash(T t) { return t.GetHashCode(); } diff --git a/OpenRA.Game/Traits/BodyOrientation.cs b/OpenRA.Game/Traits/BodyOrientation.cs old mode 100755 new mode 100644 diff --git a/OpenRA.Game/Traits/CreatesShroud.cs b/OpenRA.Game/Traits/CreatesShroud.cs index 9f3fe0d9ab..7acab32a02 100644 --- a/OpenRA.Game/Traits/CreatesShroud.cs +++ b/OpenRA.Game/Traits/CreatesShroud.cs @@ -20,13 +20,13 @@ namespace OpenRA.Traits public class CreatesShroud : ITick, ISync { - CreatesShroudInfo Info; + CreatesShroudInfo info; [Sync] CPos cachedLocation; [Sync] bool cachedDisabled; public CreatesShroud(CreatesShroudInfo info) { - Info = info; + this.info = info; } public void Tick(Actor self) @@ -43,6 +43,6 @@ namespace OpenRA.Traits } } - public WRange Range { get { return cachedDisabled ? WRange.Zero : Info.Range; } } + public WRange Range { get { return cachedDisabled ? WRange.Zero : info.Range; } } } } \ No newline at end of file diff --git a/OpenRA.Game/Traits/DrawLineToTarget.cs b/OpenRA.Game/Traits/DrawLineToTarget.cs index 3612b519ce..0a253fd6ea 100644 --- a/OpenRA.Game/Traits/DrawLineToTarget.cs +++ b/OpenRA.Game/Traits/DrawLineToTarget.cs @@ -24,12 +24,12 @@ namespace OpenRA.Traits public class DrawLineToTarget : IPostRenderSelection, INotifySelected, INotifyBecomingIdle { Actor self; - DrawLineToTargetInfo Info; + DrawLineToTargetInfo info; List targets; Color c; int lifetime; - public DrawLineToTarget(Actor self, DrawLineToTargetInfo info) { this.self = self; this.Info = info; } + public DrawLineToTarget(Actor self, DrawLineToTargetInfo info) { this.self = self; this.info = info; } public void SetTarget(Actor self, Target target, Color c, bool display) { @@ -37,7 +37,7 @@ namespace OpenRA.Traits this.c = c; if (display) - lifetime = Info.Ticks; + lifetime = info.Ticks; } public void SetTargets(Actor self, List targets, Color c, bool display) @@ -46,7 +46,7 @@ namespace OpenRA.Traits this.c = c; if (display) - lifetime = Info.Ticks; + lifetime = info.Ticks; } public void Selected(Actor a) @@ -55,7 +55,7 @@ namespace OpenRA.Traits return; // Reset the order line timeout. - lifetime = Info.Ticks; + lifetime = info.Ticks; } public IEnumerable RenderAfterWorld(WorldRenderer wr) diff --git a/OpenRA.Game/Traits/Health.cs b/OpenRA.Game/Traits/Health.cs index f3bf03e9f1..ecb3ab5f93 100755 --- a/OpenRA.Game/Traits/Health.cs +++ b/OpenRA.Game/Traits/Health.cs @@ -171,7 +171,7 @@ namespace OpenRA.Traits public class HealthInit : IActorInit { - [FieldFromYamlKey] public readonly float value = 1f; + [FieldFromYamlKey] readonly float value = 1f; public HealthInit() { } public HealthInit(float init) { value = init; } public float Value(World world) { return value; } diff --git a/OpenRA.Game/Traits/Player/DeveloperMode.cs b/OpenRA.Game/Traits/Player/DeveloperMode.cs index 22fbd0a348..1d1a82ae27 100644 --- a/OpenRA.Game/Traits/Player/DeveloperMode.cs +++ b/OpenRA.Game/Traits/Player/DeveloperMode.cs @@ -30,7 +30,7 @@ namespace OpenRA.Traits public class DeveloperMode : IResolveOrder, ISync { - DeveloperModeInfo Info; + DeveloperModeInfo info; [Sync] public bool FastCharge; [Sync] public bool AllTech; [Sync] public bool FastBuild; @@ -46,7 +46,7 @@ namespace OpenRA.Traits public DeveloperMode(DeveloperModeInfo info) { - Info = info; + this.info = info; FastBuild = info.FastBuild; FastCharge = info.FastCharge; DisableShroud = info.DisableShroud; @@ -85,7 +85,7 @@ namespace OpenRA.Traits case "DevGiveCash": { - var amount = order.ExtraData != 0 ? (int)order.ExtraData : Info.Cash; + var amount = order.ExtraData != 0 ? (int)order.ExtraData : info.Cash; self.Trait().GiveCash(amount); break; } @@ -94,7 +94,7 @@ namespace OpenRA.Traits { foreach (var a in self.World.ActorsWithTrait()) { - for (var i = 0; i < Info.ResourceGrowth; i++) + for (var i = 0; i < info.ResourceGrowth; i++) a.Trait.Seed(a.Actor); } diff --git a/OpenRA.Game/Traits/Player/FrozenActorLayer.cs b/OpenRA.Game/Traits/Player/FrozenActorLayer.cs old mode 100755 new mode 100644 diff --git a/OpenRA.Game/Traits/Player/PlayerHighlightPalette.cs b/OpenRA.Game/Traits/Player/PlayerHighlightPalette.cs index 16c897d7ab..63dd4f6fc3 100644 --- a/OpenRA.Game/Traits/Player/PlayerHighlightPalette.cs +++ b/OpenRA.Game/Traits/Player/PlayerHighlightPalette.cs @@ -19,21 +19,21 @@ namespace OpenRA.Traits { [Desc("The prefix for the resulting player palettes")] public readonly string BaseName = "highlight"; - + public object Create(ActorInitializer init) { return new PlayerHighlightPalette(init.self.Owner, this); } } - + public class PlayerHighlightPalette : ILoadsPalettes { readonly Player owner; readonly PlayerHighlightPaletteInfo info; - + public PlayerHighlightPalette(Player owner, PlayerHighlightPaletteInfo info) { this.owner = owner; this.info = info; } - + public void LoadPalettes(WorldRenderer wr) { var argb = (uint)Color.FromArgb(128, owner.Color.RGB).ToArgb(); diff --git a/OpenRA.Game/Traits/Player/PlayerResources.cs b/OpenRA.Game/Traits/Player/PlayerResources.cs index 066011c47c..11a2e10a01 100644 --- a/OpenRA.Game/Traits/Player/PlayerResources.cs +++ b/OpenRA.Game/Traits/Player/PlayerResources.cs @@ -24,17 +24,17 @@ namespace OpenRA.Traits public class PlayerResources : ITick, ISync { - const float displayCashFracPerFrame = .07f; - const int displayCashDeltaPerFrame = 37; - readonly Player Owner; - int AdviceInterval; + const float DisplayCashFracPerFrame = .07f; + const int DisplayCashDeltaPerFrame = 37; + readonly Player owner; + int adviceInterval; public PlayerResources(Actor self, PlayerResourcesInfo info) { - Owner = self.Owner; + owner = self.Owner; Cash = self.World.LobbyInfo.GlobalSettings.StartingCash; - AdviceInterval = info.AdviceInterval; + adviceInterval = info.AdviceInterval; } [Sync] public int Cash; @@ -108,7 +108,7 @@ namespace OpenRA.Traits nextCashTickTime--; ResourceCapacity = self.World.ActorsWithTrait() - .Where(a => a.Actor.Owner == Owner) + .Where(a => a.Actor.Owner == owner) .Sum(a => a.Trait.Capacity); if (Resources > ResourceCapacity) @@ -118,53 +118,52 @@ namespace OpenRA.Traits { if (Resources > 0.8 * ResourceCapacity) { - Sound.PlayNotification(self.World.Map.Rules, Owner, "Speech", "SilosNeeded", Owner.Country.Race); + Sound.PlayNotification(self.World.Map.Rules, owner, "Speech", "SilosNeeded", owner.Country.Race); AlertSilo = true; } else AlertSilo = false; - nextSiloAdviceTime = AdviceInterval; + nextSiloAdviceTime = adviceInterval; } var diff = Math.Abs(Cash - DisplayCash); - var move = Math.Min(Math.Max((int)(diff * displayCashFracPerFrame), - displayCashDeltaPerFrame), diff); - + var move = Math.Min(Math.Max((int)(diff * DisplayCashFracPerFrame), DisplayCashDeltaPerFrame), diff); + if (DisplayCash < Cash) { DisplayCash += move; - playCashTickUp(self); + PlayCashTickUp(self); } else if (DisplayCash > Cash) { DisplayCash -= move; - playCashTickDown(self); + PlayCashTickDown(self); } diff = Math.Abs(Resources - DisplayResources); - move = Math.Min(Math.Max((int)(diff * displayCashFracPerFrame), - displayCashDeltaPerFrame), diff); + move = Math.Min(Math.Max((int)(diff * DisplayCashFracPerFrame), + DisplayCashDeltaPerFrame), diff); if (DisplayResources < Resources) { DisplayResources += move; - playCashTickUp(self); + PlayCashTickUp(self); } else if (DisplayResources > Resources) { DisplayResources -= move; - playCashTickDown(self); + PlayCashTickDown(self); } } - - public void playCashTickUp(Actor self) + + public void PlayCashTickUp(Actor self) { if (Game.Settings.Sound.CashTicks) Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Sounds", "CashTickUp", self.Owner.Country.Race); } - - public void playCashTickDown(Actor self) + + public void PlayCashTickDown(Actor self) { if (Game.Settings.Sound.CashTicks && nextCashTickTime == 0) { diff --git a/OpenRA.Game/Traits/RevealsShroud.cs b/OpenRA.Game/Traits/RevealsShroud.cs index a4fd6f25d8..0f4dbe9613 100644 --- a/OpenRA.Game/Traits/RevealsShroud.cs +++ b/OpenRA.Game/Traits/RevealsShroud.cs @@ -20,12 +20,12 @@ namespace OpenRA.Traits public class RevealsShroud : ITick, ISync { - RevealsShroudInfo Info; + RevealsShroudInfo info; [Sync] CPos cachedLocation; public RevealsShroud(RevealsShroudInfo info) { - Info = info; + this.info = info; } public void Tick(Actor self) @@ -39,6 +39,6 @@ namespace OpenRA.Traits } } - public WRange Range { get { return Info.Range; } } + public WRange Range { get { return info.Range; } } } } diff --git a/OpenRA.Game/Traits/SelectionDecorations.cs b/OpenRA.Game/Traits/SelectionDecorations.cs index d75cf9634f..1aa303b6de 100644 --- a/OpenRA.Game/Traits/SelectionDecorations.cs +++ b/OpenRA.Game/Traits/SelectionDecorations.cs @@ -24,8 +24,8 @@ namespace OpenRA.Traits public class SelectionDecorations : IPostRenderSelection { // depends on the order of pips in TraitsInterfaces.cs! - static readonly string[] pipStrings = { "pip-empty", "pip-green", "pip-yellow", "pip-red", "pip-gray", "pip-blue", "pip-ammo", "pip-ammoempty" }; - static readonly string[] tagStrings = { "", "tag-fake", "tag-primary" }; + static readonly string[] PipStrings = { "pip-empty", "pip-green", "pip-yellow", "pip-red", "pip-gray", "pip-blue", "pip-ammo", "pip-ammoempty" }; + static readonly string[] TagStrings = { "", "tag-fake", "tag-primary" }; public SelectionDecorationsInfo Info; Actor self; @@ -79,7 +79,7 @@ namespace OpenRA.Traits yield break; var pipImages = new Animation(self.World, "pips"); - pipImages.PlayRepeating(pipStrings[0]); + pipImages.PlayRepeating(PipStrings[0]); var pipSize = pipImages.Image.size.ToInt2(); var pipxyBase = basePosition + new int2(1 - pipSize.X / 2, -(3 + pipSize.Y / 2)); @@ -101,7 +101,7 @@ namespace OpenRA.Traits pipxyOffset.Y -= pipSize.Y; } - pipImages.PlayRepeating(pipStrings[(int)pip]); + pipImages.PlayRepeating(PipStrings[(int)pip]); pipxyOffset += new int2(pipSize.X, 0); yield return new UISpriteRenderable(pipImages.Image, pipxyBase + pipxyOffset, 0, pal, 1f); @@ -126,7 +126,7 @@ namespace OpenRA.Traits if (tag == TagType.None) continue; - tagImages.PlayRepeating(tagStrings[(int)tag]); + tagImages.PlayRepeating(TagStrings[(int)tag]); var pos = basePosition + tagxyOffset - (0.5f * tagImages.Image.size).ToInt2(); yield return new UISpriteRenderable(tagImages.Image, pos, 0, pal, 1f); diff --git a/OpenRA.Game/Traits/TraitsInterfaces.cs b/OpenRA.Game/Traits/TraitsInterfaces.cs index c7b2953209..7fbf5e11b0 100644 --- a/OpenRA.Game/Traits/TraitsInterfaces.cs +++ b/OpenRA.Game/Traits/TraitsInterfaces.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Linq; using OpenRA.Activities; @@ -240,7 +241,9 @@ namespace OpenRA.Traits public class TraitInfo : ITraitInfo where T : new() { public virtual object Create(ActorInitializer init) { return new T(); } } + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1302:InterfaceNamesMustBeginWithI", Justification = "Not a real interface, but more like a tag.")] public interface Requires where T : class, ITraitInfo { } + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1302:InterfaceNamesMustBeginWithI", Justification = "Not a real interface, but more like a tag.")] public interface UsesInit where T : IActorInit { } public interface INotifySelected { void Selected(Actor self); } diff --git a/OpenRA.Game/Traits/World/Shroud.cs b/OpenRA.Game/Traits/World/Shroud.cs index 685063e929..2b7feebe85 100644 --- a/OpenRA.Game/Traits/World/Shroud.cs +++ b/OpenRA.Game/Traits/World/Shroud.cs @@ -91,7 +91,7 @@ namespace OpenRA.Traits void Invalidate() { var oldHash = Hash; - Hash = Sync.hash_player(self.Owner) + self.World.WorldTick * 3; + Hash = Sync.HashPlayer(self.Owner) + self.World.WorldTick * 3; // Invalidate may be called multiple times in one world tick, which is decoupled from rendering. if (oldHash == Hash) diff --git a/OpenRA.Game/WAngle.cs b/OpenRA.Game/WAngle.cs index 0c9dd91c05..d7810d8814 100644 --- a/OpenRA.Game/WAngle.cs +++ b/OpenRA.Game/WAngle.cs @@ -103,7 +103,7 @@ namespace OpenRA public override string ToString() { return Angle.ToString(); } - static int[] CosineTable = + static readonly int[] CosineTable = { 1024, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1022, 1022, 1022, 1021, 1021, 1020, 1020, 1019, 1019, 1018, 1017, 1017, 1016, 1015, 1014, 1013, @@ -126,7 +126,7 @@ namespace OpenRA 56, 50, 43, 37, 31, 25, 18, 12, 6, 0 }; - static int[] TanTable = + static readonly int[] TanTable = { 0, 6, 12, 18, 25, 31, 37, 44, 50, 56, 62, 69, 75, 81, 88, 94, 100, 107, 113, 119, 126, 132, 139, 145, 151, 158, 164, 171, 177, 184, 190, 197, diff --git a/OpenRA.Game/Widgets/ChatDisplayWidget.cs b/OpenRA.Game/Widgets/ChatDisplayWidget.cs index 915482e001..7b2481c318 100644 --- a/OpenRA.Game/Widgets/ChatDisplayWidget.cs +++ b/OpenRA.Game/Widgets/ChatDisplayWidget.cs @@ -21,7 +21,7 @@ namespace OpenRA.Widgets public readonly bool UseContrast = false; public string Notification = ""; - const int logLength = 9; + const int LogLength = 9; List recentLines = new List(); public override Rectangle EventBounds { get { return Rectangle.Empty; } } @@ -72,7 +72,7 @@ namespace OpenRA.Widgets if (Notification != null) Sound.Play(Notification); - while (recentLines.Count > logLength) + while (recentLines.Count > LogLength) recentLines.RemoveAt(0); } diff --git a/OpenRA.Game/Widgets/PerfGraphWidget.cs b/OpenRA.Game/Widgets/PerfGraphWidget.cs index bf1e701879..26525cc5e4 100644 --- a/OpenRA.Game/Widgets/PerfGraphWidget.cs +++ b/OpenRA.Game/Widgets/PerfGraphWidget.cs @@ -26,7 +26,7 @@ namespace OpenRA.Widgets Game.Renderer.LineRenderer.DrawLine(origin + new float2(100, 0) * basis, origin + new float2(100, 100) * basis, Color.White, Color.White); var k = 0; - foreach (var item in PerfHistory.items.Values.ToArray()) + foreach (var item in PerfHistory.Items.Values.ToArray()) { var n = 0; item.Samples().Aggregate((a, b) => @@ -34,7 +34,7 @@ namespace OpenRA.Widgets Game.Renderer.LineRenderer.DrawLine( origin + new float2(n, (float)a) * basis, origin + new float2(n + 1, (float)b) * basis, - item.c, item.c); + item.C, item.C); ++n; return b; }); @@ -44,18 +44,18 @@ namespace OpenRA.Widgets Game.Renderer.LineRenderer.DrawLine( u + new float2(10, 10 * k + 5), u + new float2(12, 10 * k + 5), - item.c, item.c); + item.C, item.C); Game.Renderer.LineRenderer.DrawLine( u + new float2(10, 10 * k + 4), u + new float2(12, 10 * k + 4), - item.c, item.c); + item.C, item.C); ++k; } k = 0; - foreach (var item in PerfHistory.items.Values.ToArray()) + foreach (var item in PerfHistory.Items.Values.ToArray()) { Game.Renderer.Fonts["Tiny"].DrawText(item.Name, new float2(rect.Left, rect.Top) + new float2(18, 10 * k - 3), Color.White); ++k; diff --git a/OpenRA.Game/Widgets/ScrollPanelWidget.cs b/OpenRA.Game/Widgets/ScrollPanelWidget.cs index d5eb6d4cde..15007a0d94 100644 --- a/OpenRA.Game/Widgets/ScrollPanelWidget.cs +++ b/OpenRA.Game/Widgets/ScrollPanelWidget.cs @@ -43,11 +43,11 @@ namespace OpenRA.Widgets public bool CollapseHiddenChildren; public float SmoothScrollSpeed = 0.333f; - protected bool UpPressed; - protected bool DownPressed; - protected bool UpDisabled; - protected bool DownDisabled; - protected bool ThumbPressed; + protected bool upPressed; + protected bool downPressed; + protected bool upDisabled; + protected bool downDisabled; + protected bool thumbPressed; protected Rectangle upButtonRect; protected Rectangle downButtonRect; protected Rectangle backgroundRect; @@ -119,40 +119,40 @@ namespace OpenRA.Widgets var rb = RenderBounds; - var ScrollbarHeight = rb.Height - 2 * ScrollbarWidth; + var scrollbarHeight = rb.Height - 2 * ScrollbarWidth; - var thumbHeight = ContentHeight == 0 ? 0 : Math.Max(MinimumThumbSize, (int)(ScrollbarHeight * Math.Min(rb.Height * 1f / ContentHeight, 1f))); - var thumbOrigin = rb.Y + ScrollbarWidth + (int)((ScrollbarHeight - thumbHeight) * (-1f * currentListOffset / (ContentHeight - rb.Height))); - if (thumbHeight == ScrollbarHeight) + var thumbHeight = ContentHeight == 0 ? 0 : Math.Max(MinimumThumbSize, (int)(scrollbarHeight * Math.Min(rb.Height * 1f / ContentHeight, 1f))); + var thumbOrigin = rb.Y + ScrollbarWidth + (int)((scrollbarHeight - thumbHeight) * (-1f * currentListOffset / (ContentHeight - rb.Height))); + if (thumbHeight == scrollbarHeight) thumbHeight = 0; backgroundRect = new Rectangle(rb.X, rb.Y, rb.Width - ScrollbarWidth + 1, rb.Height); upButtonRect = new Rectangle(rb.Right - ScrollbarWidth, rb.Y, ScrollbarWidth, ScrollbarWidth); downButtonRect = new Rectangle(rb.Right - ScrollbarWidth, rb.Bottom - ScrollbarWidth, ScrollbarWidth, ScrollbarWidth); - scrollbarRect = new Rectangle(rb.Right - ScrollbarWidth, rb.Y + ScrollbarWidth - 1, ScrollbarWidth, ScrollbarHeight + 2); + scrollbarRect = new Rectangle(rb.Right - ScrollbarWidth, rb.Y + ScrollbarWidth - 1, ScrollbarWidth, scrollbarHeight + 2); thumbRect = new Rectangle(rb.Right - ScrollbarWidth, thumbOrigin, ScrollbarWidth, thumbHeight); var upHover = Ui.MouseOverWidget == this && upButtonRect.Contains(Viewport.LastMousePos); - UpDisabled = thumbHeight == 0 || currentListOffset >= 0; + upDisabled = thumbHeight == 0 || currentListOffset >= 0; var downHover = Ui.MouseOverWidget == this && downButtonRect.Contains(Viewport.LastMousePos); - DownDisabled = thumbHeight == 0 || currentListOffset <= Bounds.Height - ContentHeight; + downDisabled = thumbHeight == 0 || currentListOffset <= Bounds.Height - ContentHeight; var thumbHover = Ui.MouseOverWidget == this && thumbRect.Contains(Viewport.LastMousePos); WidgetUtils.DrawPanel(Background, backgroundRect); WidgetUtils.DrawPanel(Background, scrollbarRect); - ButtonWidget.DrawBackground(Button, upButtonRect, UpDisabled, UpPressed, upHover, false); - ButtonWidget.DrawBackground(Button, downButtonRect, DownDisabled, DownPressed, downHover, false); + ButtonWidget.DrawBackground(Button, upButtonRect, upDisabled, upPressed, upHover, false); + ButtonWidget.DrawBackground(Button, downButtonRect, downDisabled, downPressed, downHover, false); if (thumbHeight > 0) ButtonWidget.DrawBackground(Button, thumbRect, false, HasMouseFocus && thumbHover, thumbHover, false); - var upOffset = !UpPressed || UpDisabled ? 4 : 4 + ButtonDepth; - var downOffset = !DownPressed || DownDisabled ? 4 : 4 + ButtonDepth; + var upOffset = !upPressed || upDisabled ? 4 : 4 + ButtonDepth; + var downOffset = !downPressed || downDisabled ? 4 : 4 + ButtonDepth; - WidgetUtils.DrawRGBA(ChromeProvider.GetImage("scrollbar", UpPressed || UpDisabled ? "up_pressed" : "up_arrow"), + WidgetUtils.DrawRGBA(ChromeProvider.GetImage("scrollbar", upPressed || upDisabled ? "up_pressed" : "up_arrow"), new float2(upButtonRect.Left + upOffset, upButtonRect.Top + upOffset)); - WidgetUtils.DrawRGBA(ChromeProvider.GetImage("scrollbar", DownPressed || DownDisabled ? "down_pressed" : "down_arrow"), + WidgetUtils.DrawRGBA(ChromeProvider.GetImage("scrollbar", downPressed || downDisabled ? "down_pressed" : "down_arrow"), new float2(downButtonRect.Left + downOffset, downButtonRect.Top + downOffset)); Game.Renderer.EnableScissor(backgroundRect.InflateBy(-1, -1, -1, -1)); @@ -225,10 +225,10 @@ namespace OpenRA.Widgets public override void Tick() { - if (UpPressed) + if (upPressed) Scroll(1); - if (DownPressed) + if (downPressed) Scroll(-1); var offsetDiff = targetListOffset - currentListOffset; @@ -241,7 +241,7 @@ namespace OpenRA.Widgets public override bool YieldMouseFocus(MouseInput mi) { - UpPressed = DownPressed = ThumbPressed = false; + upPressed = downPressed = thumbPressed = false; return base.YieldMouseFocus(mi); } @@ -267,14 +267,14 @@ namespace OpenRA.Widgets if (HasMouseFocus && mi.Event == MouseInputEvent.Up) return YieldMouseFocus(mi); - if (ThumbPressed && mi.Event == MouseInputEvent.Move) + if (thumbPressed && mi.Event == MouseInputEvent.Move) { var rb = RenderBounds; - var ScrollbarHeight = rb.Height - 2 * ScrollbarWidth; - var thumbHeight = ContentHeight == 0 ? 0 : Math.Max(MinimumThumbSize, (int)(ScrollbarHeight * Math.Min(rb.Height * 1f / ContentHeight, 1f))); + var scrollbarHeight = rb.Height - 2 * ScrollbarWidth; + var thumbHeight = ContentHeight == 0 ? 0 : Math.Max(MinimumThumbSize, (int)(scrollbarHeight * Math.Min(rb.Height * 1f / ContentHeight, 1f))); var oldOffset = currentListOffset; - var newOffset = currentListOffset + ((int)((lastMouseLocation.Y - mi.Location.Y) * (ContentHeight - rb.Height) * 1f / (ScrollbarHeight - thumbHeight))); + var newOffset = currentListOffset + ((int)((lastMouseLocation.Y - mi.Location.Y) * (ContentHeight - rb.Height) * 1f / (scrollbarHeight - thumbHeight))); newOffset = Math.Min(0, Math.Max(rb.Height - ContentHeight, newOffset)); SetListOffset(newOffset, false); @@ -283,17 +283,17 @@ namespace OpenRA.Widgets } else { - UpPressed = upButtonRect.Contains(mi.Location); - DownPressed = downButtonRect.Contains(mi.Location); - ThumbPressed = thumbRect.Contains(mi.Location); - if (ThumbPressed) + upPressed = upButtonRect.Contains(mi.Location); + downPressed = downButtonRect.Contains(mi.Location); + thumbPressed = thumbRect.Contains(mi.Location); + if (thumbPressed) lastMouseLocation = mi.Location; - if (mi.Event == MouseInputEvent.Down && ((UpPressed && !UpDisabled) || (DownPressed && !DownDisabled) || ThumbPressed)) + if (mi.Event == MouseInputEvent.Down && ((upPressed && !upDisabled) || (downPressed && !downDisabled) || thumbPressed)) Sound.PlayNotification(modRules, null, "Sounds", "ClickSound", null); } - return UpPressed || DownPressed || ThumbPressed; + return upPressed || downPressed || thumbPressed; } IObservableCollection collection; diff --git a/OpenRA.Game/Widgets/SpriteSequenceWidget.cs b/OpenRA.Game/Widgets/SpriteSequenceWidget.cs index 85d43a55a3..4d323d567b 100644 --- a/OpenRA.Game/Widgets/SpriteSequenceWidget.cs +++ b/OpenRA.Game/Widgets/SpriteSequenceWidget.cs @@ -36,7 +36,7 @@ namespace OpenRA.Widgets if (Unit != null && Sequence != null) { - var anim = new Animation(worldRenderer.world, Unit, () => Facing); + var anim = new Animation(WorldRenderer.world, Unit, () => Facing); anim.PlayFetchIndex(Sequence, () => Frame); GetAnimation = () => anim; } diff --git a/OpenRA.Game/Widgets/SpriteWidget.cs b/OpenRA.Game/Widgets/SpriteWidget.cs index 7b3fbde15c..a875ac3a34 100644 --- a/OpenRA.Game/Widgets/SpriteWidget.cs +++ b/OpenRA.Game/Widgets/SpriteWidget.cs @@ -19,14 +19,14 @@ namespace OpenRA.Widgets public Func GetPalette; public Func GetSprite; - protected readonly WorldRenderer worldRenderer; + protected readonly WorldRenderer WorldRenderer; [ObjectCreator.UseCtor] public SpriteWidget(WorldRenderer worldRenderer) { GetPalette = () => Palette; - this.worldRenderer = worldRenderer; + this.WorldRenderer = worldRenderer; } protected SpriteWidget(SpriteWidget other) @@ -36,7 +36,7 @@ namespace OpenRA.Widgets GetPalette = other.GetPalette; GetSprite = other.GetSprite; - worldRenderer = other.worldRenderer; + WorldRenderer = other.WorldRenderer; } public override Widget Clone() { return new SpriteWidget(this); } @@ -62,7 +62,7 @@ namespace OpenRA.Widgets if (palette != cachedPalette) { - pr = worldRenderer.Palette(palette); + pr = WorldRenderer.Palette(palette); cachedPalette = palette; } diff --git a/OpenRA.Game/Widgets/Widget.cs b/OpenRA.Game/Widgets/Widget.cs index 1874f3db98..80fd2edc47 100644 --- a/OpenRA.Game/Widgets/Widget.cs +++ b/OpenRA.Game/Widgets/Widget.cs @@ -23,7 +23,7 @@ namespace OpenRA.Widgets public static int LastTickTime = Game.RunTime; - static Stack WindowList = new Stack(); + static readonly Stack WindowList = new Stack(); public static Widget MouseFocusWidget; public static Widget KeyboardFocusWidget; diff --git a/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs b/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs index a761f918f1..30361addf2 100644 --- a/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs +++ b/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs @@ -90,7 +90,7 @@ namespace OpenRA.Mods.Common.Server client.State = state; Log.Write("server", "Player @{0} is {1}", - conn.socket.RemoteEndPoint, client.State); + conn.Socket.RemoteEndPoint, client.State); server.SyncLobbyClients(); @@ -714,7 +714,7 @@ namespace OpenRA.Mods.Common.Server { "name", s => { - Log.Write("server", "Player@{0} is now known as {1}.", conn.socket.RemoteEndPoint, s); + Log.Write("server", "Player@{0} is now known as {1}.", conn.Socket.RemoteEndPoint, s); server.SendMessage("{0} is now known as {1}.".F(client.Name, s)); client.Name = s; server.SyncLobbyClients(); diff --git a/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs b/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs index 59b46d390f..eb5dd3fa72 100644 --- a/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs +++ b/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs @@ -43,18 +43,17 @@ namespace OpenRA.Mods.Common.Server { foreach (var c in server.Conns.ToList()) { - if (c == null || c.socket == null) + if (c == null || c.Socket == null) continue; var client = server.GetClient(c); - if (client == null) { server.DropClient(c, -1); server.SendMessage("A player has been dropped after timing out."); continue; } - + if (c.TimeSinceLastResponse < ConnTimeout) { server.SendOrderTo(c, "Ping", Game.RunTime.ToString()); @@ -81,11 +80,10 @@ namespace OpenRA.Mods.Common.Server foreach (var c in timeouts) { - if (c == null || c.socket == null) + if (c == null || c.Socket == null) continue; - + var client = server.GetClient(c); - if (client != null) server.SendMessage("{0} will be dropped in {1} seconds.".F(client.Name, (ConnTimeout - c.TimeSinceLastResponse) / 1000)); } diff --git a/OpenRA.Mods.Common/Traits/Player/MissionObjectives.cs b/OpenRA.Mods.Common/Traits/Player/MissionObjectives.cs index e719f56f11..82b805f7e3 100644 --- a/OpenRA.Mods.Common/Traits/Player/MissionObjectives.cs +++ b/OpenRA.Mods.Common/Traits/Player/MissionObjectives.cs @@ -58,7 +58,7 @@ namespace OpenRA.Mods.Common.Traits public ReadOnlyList Objectives; [Sync] - public int ObjectivesHash { get { return Objectives.Aggregate(0, (code, objective) => code ^ Sync.hash(objective.State)); } } + public int ObjectivesHash { get { return Objectives.Aggregate(0, (code, objective) => code ^ Sync.Hash(objective.State)); } } // This property is used as a flag in 'Cooperative' games to mark that the player has completed all his objectives. // The player's WinState is only updated when his allies have all completed their objective as well. diff --git a/OpenRA.Mods.RA/Render/RenderBuildingWall.cs b/OpenRA.Mods.RA/Render/RenderBuildingWall.cs index 35ca3ada9f..3c04d4fa80 100644 --- a/OpenRA.Mods.RA/Render/RenderBuildingWall.cs +++ b/OpenRA.Mods.RA/Render/RenderBuildingWall.cs @@ -65,7 +65,7 @@ namespace OpenRA.Mods.RA.Traits return; // Update connection to neighbours - var adjacentActors = CVec.directions.SelectMany(dir => + var adjacentActors = CVec.Directions.SelectMany(dir => self.World.ActorMap.GetUnitsAt(self.Location + dir)); adjacent = 0; @@ -93,7 +93,7 @@ namespace OpenRA.Mods.RA.Traits static void UpdateNeighbours(Actor self) { - var adjacentActors = CVec.directions.SelectMany(dir => + var adjacentActors = CVec.Directions.SelectMany(dir => self.World.ActorMap.GetUnitsAt(self.Location + dir)) .Select(a => a.TraitOrDefault()) .Where(a => a != null); diff --git a/OpenRA.Mods.RA/Traits/Buildings/RepairableBuilding.cs b/OpenRA.Mods.RA/Traits/Buildings/RepairableBuilding.cs index dbf0743f56..b1ec6aba56 100644 --- a/OpenRA.Mods.RA/Traits/Buildings/RepairableBuilding.cs +++ b/OpenRA.Mods.RA/Traits/Buildings/RepairableBuilding.cs @@ -35,7 +35,7 @@ namespace OpenRA.Mods.RA.Traits public class RepairableBuilding : UpgradableTrait, ITick { [Sync] - public int RepairersHash { get { return Repairers.Aggregate(0, (code, player) => code ^ Sync.hash_player(player)); } } + public int RepairersHash { get { return Repairers.Aggregate(0, (code, player) => code ^ Sync.HashPlayer(player)); } } public List Repairers = new List(); Health Health; diff --git a/OpenRA.Mods.RA/Traits/World/DomainIndex.cs b/OpenRA.Mods.RA/Traits/World/DomainIndex.cs index 0ae87bec53..3f0b57405d 100644 --- a/OpenRA.Mods.RA/Traits/World/DomainIndex.cs +++ b/OpenRA.Mods.RA/Traits/World/DomainIndex.cs @@ -91,7 +91,7 @@ namespace OpenRA.Mods.RA.Traits { // Select all neighbors inside the map boundries var thisCell = cell; // benign closure hazard - var neighbors = CVec.directions.Select(d => d + thisCell) + var neighbors = CVec.Directions.Select(d => d + thisCell) .Where(c => map.Contains(c)); var found = false; @@ -208,7 +208,7 @@ namespace OpenRA.Mods.RA.Traits domains[n] = domain; // Don't crawl off the map, or add already-visited cells - var neighbors = CVec.directions.Select(d => n + d) + var neighbors = CVec.Directions.Select(d => n + d) .Where(p => map.Contains(p) && !visited[p]); foreach (var neighbor in neighbors) diff --git a/OpenRA.Mods.RA/Traits/World/PathSearch.cs b/OpenRA.Mods.RA/Traits/World/PathSearch.cs index a9ba4518c2..a3472939b3 100644 --- a/OpenRA.Mods.RA/Traits/World/PathSearch.cs +++ b/OpenRA.Mods.RA/Traits/World/PathSearch.cs @@ -148,7 +148,7 @@ namespace OpenRA.Mods.RA.Traits new CVec[] { new CVec(-1, -1), new CVec(0, -1), new CVec(1, -1) }, new CVec[] { new CVec(-1, -1), new CVec(0, -1), new CVec(1, -1), new CVec(1, 0), new CVec(1, 1) }, new CVec[] { new CVec(-1, -1), new CVec(-1, 0), new CVec(-1, 1) }, - CVec.directions, + CVec.Directions, new CVec[] { new CVec(1, -1), new CVec(1, 0), new CVec(1, 1) }, new CVec[] { new CVec(-1, -1), new CVec(-1, 0), new CVec(-1, 1), new CVec(0, 1), new CVec(1, 1) }, new CVec[] { new CVec(-1, 1), new CVec(0, 1), new CVec(1, 1) }, diff --git a/OpenRA.Mods.RA/Widgets/Logic/PerfDebugLogic.cs b/OpenRA.Mods.RA/Widgets/Logic/PerfDebugLogic.cs index 1a29cd3118..f5ddadd129 100644 --- a/OpenRA.Mods.RA/Widgets/Logic/PerfDebugLogic.cs +++ b/OpenRA.Mods.RA/Widgets/Logic/PerfDebugLogic.cs @@ -25,9 +25,9 @@ namespace OpenRA.Mods.RA.Widgets.Logic perfText.IsVisible = () => Game.Settings.Debug.PerfText; perfText.GetText = () => "Tick {0} @ {1:F1} ms\nRender {2} @ {3:F1} ms\nBatches: {4}".F( - Game.LocalTick, PerfHistory.items["tick_time"].Average(Game.Settings.Debug.Samples), - Game.RenderFrame, PerfHistory.items["render"].Average(Game.Settings.Debug.Samples), - PerfHistory.items["batches"].LastValue); + Game.LocalTick, PerfHistory.Items["tick_time"].Average(Game.Settings.Debug.Samples), + Game.RenderFrame, PerfHistory.Items["render"].Average(Game.Settings.Debug.Samples), + PerfHistory.Items["batches"].LastValue); } } }